2
votes

I'm dealing with a large dataframe (over 100 columns) and I need to rename the columns. Let's say the dataframe of interest looks like this:

      C     D     E     F     G     H
1    10   200    50    40    60    10
2    30   400    20    30    30    10
3    20    40    30    30    50    10

I also have a "relational" dataframe with rows matching original column names to the desired new names that looks like this:

  Code  Name 
1 C     Cat  
2 D     Dog  
3 E     Emu  
4 F     Fish 
5 G     Goat 
6 H     Hog  

What I'm looking for is a base or package function that allows me to use this match dataframe to rename the original columns, yielding a final dataframe that looks like this:

    Cat   Dog   Emu  Fish  Goat   Hog
1    10   200    50    40    60    10
2    30   400    20    30    30    10
3    20    40    30    30    50    10

Remember, the real application has something like 100+ columns, so the smallest amount of by hand coding possible is desirable here-- Thanks!

2

2 Answers

4
votes

It can be done with rename_at (assuming that the columns 'code', 'Name' are character class in the relational dataset)

library(dplyr)
df1 %>%
   rename_at(vars(relational$Code), ~ relational$Name)

Or another option is setnames from data.table

library(data.table)
setDT(df1)
setnames(df1, relational$Code, relational$Name)

Or in base R

names(df1) <- setNames(relational$Name, relational$Code)[names(df1)]

data

df1 <- structure(list(C = c(10L, 30L, 20L), D = c(200L, 400L, 40L), 
    E = c(50L, 20L, 30L), F = c(40L, 30L, 30L), G = c(60L, 30L, 
    50L), H = c(10L, 10L, 10L)), class = "data.frame", row.names = c("1", 
"2", "3"))

relational <- structure(list(Code = c("C", "D", "E", "F", "G", "H"), Name = c("Cat", 
"Dog", "Emu", "Fish", "Goat", "Hog")), class = "data.frame",
row.names = c("1", 
"2", "3", "4", "5", "6"))
0
votes

We can use match, to match the column names with Code and get the corresponding Name.

names(df) <- relational$Name[match(names(df), relational$Code)]
df
#  Cat Dog Emu Fish Goat Hog
#1  10 200  50   40   60  10
#2  30 400  20   30   30  10
#3  20  40  30   30   50  10