Hatshepsut
Hatshepsut

Reputation: 6662

Rename columns by looking up in another dataframe

I have a dataframe

> original
  a b
1 1 4
2 2 5
3 3 6

and another dataframe that relates old names to new names

> new
  old_name new_name
1        a        c
2        b        d

and I want to apply the mapping, so the columns get new names:

> result
  c d
1 1 4
2 2 5
3 3 6

Here's the code:

library(tidyverse)
original = data.frame(a=c(1,2,3),b=c(4,5,6))
new = data.frame(old_name=c('a','b'), new_name=c('c','d'))
result = original %>% rename(c=a,d=b)
dput(list(original, new, result))

Upvotes: 0

Views: 348

Answers (2)

akuiper
akuiper

Reputation: 215127

Or use dplyr::rename with UQS or !!! (unquote and splice the arguments):

library(dplyr)

original %>% 
    rename(!!!setNames(new$old_name, new$new_name))

#  c d
#1 1 4
#2 2 5
#3 3 6

Create a mapping from old names to new names:

mapping <- setNames(new$old_name, new$new_name)
mapping
#  c   d 
#"a" "b"

splice the mapping to rename with !!!:

original %>% rename(!!!mapping)

which is equivalent to rename(c = a, d = b).

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

We can match the names of original with new$old_name and then select the corresponding new_name and apply it to names of original.

names(original) <- new$new_name[match(names(original), new$old_name)]

original

#  c d
#1 1 4
#2 2 5
#3 3 6

And using the same logic in dplyr with setnames

library(dplyr)
original %>%
  setNames(new$new_name[match(names(original), new$old_name)])

Upvotes: 2

Related Questions