Adding a column value prefix to selected column names in multiple dataframes within a list

Viewed 60

I have a list of 149 dataframes; I want to change selected column names in each dataframe to be prefixed with the value in the SiteLoc column. An abbreviated version of the list is below:

SL1_68 <- tibble(SiteLoc=rep("SL1_68",5),
                 Cov1=c(10,50,0,75,10),
                  Cov2=c(50,20,15,50,75),
                   Cov3=c(25,5,0,0,75))

SL2_70 <- tibble(SiteLoc=rep("SL2_70",5),
                 Cov1=c(10,50,0,75,10),
                  Cov2=c(50,20,15,50,75),
                   Cov3=c(25,5,0,0,75))

Site_list <- list(SL1_68,SL2_70)

I found the following code, which allows me to change selected column names in a given dataframe:

Site_list$SL1_68 <- Site_list$SL1_68 %>% 
  rename_at(2:4, ~ paste("SL1_68", ., sep = "_"))

However I don't want to have to go through each individual dataframe and instead would like to write a loop or function for the whole list that would prefix column names with the value in "SiteLoc" (which will be unique to each dataframe).

I found the following question/answer, which seemed to go some of the way to helping me out, but I wasn't sure how to apply the function and the answer below to my own code to only apply it to columns 2-4:

R append dataframe name to each of its columns within a list of dataframes

Any help would be very gratefully received.

1 Answers

You can do it in a for loop.

for(i in 1:length(Site_list)) {
  prefix <- unique(Site_list[[i]]$SiteLoc)

  Site_list[[i]] <- Site_list[[i]] %>% 
    rename_at(2:4, ~ paste(prefix, ., sep = "_"))
} 

There is probably a more elegant way, but this seems to work.

Related