Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename variables (columns) in datasets that are in a list – R

I have a list of datasets with different variables. I need to rename them according to the naming convention in the name dataframe below.

df1 <- data.frame(x1= c(1,2,3), x2=c(1,2,3))
df2 <- data.frame(x1= c(1,2,3), x3=c(1,2,3))
df3 <- data.frame(x4= c(1,2,3), x5=c(1,2,3))

mylist <- list(df1,df2,df3)

name <- data.frame(old= c("x1","x2","x3","x4","x5"), new=c("A","B","A","A","C"))

I can do this one by one, but I am wondering how to be more efficient and rename them all at once

newdf <- map_if(mylist, ~ "x1" %in% colnames(.x),
                .f = list(. %>% rename("A"="x1")))

I was hoping something like this would work, but it doesn’t:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (i in nrow(name)){

newdf <- map_if(mylist, ~ name[i,1] %in% colnames(.x),
                .f = list(. %>% rename(name[2]=name[1])))

}

>Solution :

You can use setnames from data.table, which can take a list of old and new names.

library(data.table)
library(purrr)

map(mylist, ~ setnames(.x, name$old, name$new, skip_absent=T))

Output

[[1]]
  A B
1 1 1
2 2 2
3 3 3

[[2]]
  A A
1 1 1
2 2 2
3 3 3

[[3]]
  A C
1 1 1
2 2 2
3 3 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading