2

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The logic is as follows: for each index of a tibble in Site_list, get unique value of SiteLoc in tibble with this index, and rename columns in this tibble adding this prefix to it (using the same code snipped you shared). Hope this helps!
Thank you so much, that has worked perfectly! And it's a lot simpler than the ways I was trying to do it. Really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.