Search code examples
dataframenames

Renaming columns in dataframe according to reference key


Let's assume I have a simple data frame:

df <- data.frame("one"= c(1:5), "two" = c(6:10), "three" =c(7:11))

I would like like to rename my column names, so that they match the reference Let my reference be following:

df2 <- data.frame("Name" = c("A", "B", "C"), "Oldname" = c("one", "two", "three"))

How could I replace my column names from df with those from df2, if they match whats there (So that column names in df are: A, B C)?

In my original data df2 is way bigger and I have multiple data sets such a df, so for a solution to work, the code should be as generic as possible. Thanks in advance!


Solution

  • We can use the match function here to map the new names onto the old ones:

    names(df) <- df2$Name[match(names(df), df2$Oldname)]
    names(df)
    [1] "A" "B" "C"
    

    Demo