How to rename columns based on a named list?

Viewed 62

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 :

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

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

Using data.table

data.table::setnames(mytable, names(mylist), unlist(mylist))
# mytable
#   toto titi var6
# 1    a    d    g
# 2    b    e    h
# 3    c    f    i

Base R:

colnames(mytable)[1:length(unname(unlist(mylist)))] <- unname(unlist(mylist))

mytable

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