Search code examples
rfor-loopnames

Rename dataframe columns by string matching in R


I am looping through a series of ids, loading 2 csvs for each, and applying some analysis to them. I need rename the columns of one of the 2 csvs to match the row values of the other. I need to do this inside the loop in order to apply it to the csvs for every id.

I have tried renaming the columns like this:

`names(LCC_diff)[2:length(LCC_diff)] <- c("Bare.areas" = "Bare areas",
"Tree." = "Tree ", "Urban.areas" = "Urban areas", 
"Water.bodies" = "Water bodies")`

where LCC_diff is a dataframe and the first value in each pair is the original column name and the second is the name that i want to assign to that column, but it just replaces the column names in order, and does not match them.

This is a problem because not all column names need replaced, and the csvs for different ids have these columns in different orders.

How do I match the original column names to the strings that I want to use to replace them?


Solution

  • Try rename them first, it should be much easier if they have the same name.

    library(stringr)
    
    str_replace_all(c("Tree ","Bare areas")," ",".")
    
    
    [1] "Tree."      "Bare.areas"