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

How to rename columns based on a named list?

I’m looking to rename columns in my data.frame from another list.
Here’s my example :

mylist <- list(
  var1 = "toto",
  var2 = "titi"
)

mytable <- data.frame(
  var1 = letters[1:3],
  var2 = letters[4:6],
  var6 = letters[7:9]
)

I tried that but without success :

names(mytable) <- sapply(names(mytable), function(x) mylist$x)

Expected result :

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

names(mytable) <- c("toto","titi","var6")

>Solution :

We can use match on the names of the list and the data.frame to get the index and use that to subset the column names and assign the values of ‘mylist’

i1 <- match(names(mylist), names(mytable))
names(mytable)[1:2] <- unlist(mylist)

-output

> mytable
  toto titi var6
1    a    d    g
2    b    e    h
3    c    f    i

Or with rename_with

library(dplyr)
mytable %>% 
  rename_with(~ unlist(mylist), all_of(names(mylist)))
  toto titi var6
1    a    d    g
2    b    e    h
3    c    f    i

In addition, if the list was constructed with key/value pairs inverted, we could use !!! with rename

library(hash)
mytable %>%
  rename(!!!as.list(invert(hash(mylist))))
  toto titi var6
1    a    d    g
2    b    e    h
3    c    f    i
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