Search code examples
rdplyr

Renaming columns based on variables in another data frame


I have this data frame with variable names and a column based on which my new table should be renamed.

df1 <- data.frame(id = 1:7,
                  tes = c("eeny", "meeny", "miny", "moe", "catch", "tiger", "toe"),
                  var = c("var_1", "var_2", "var_3", "var_4", "var_5", "var_6", "var_7"))
df1
> df1
  id   tes   var
1  1  eeny var_1
2  2 meeny var_2
3  3  miny var_3
4  4   moe var_4
5  5 catch var_5
6  6 tiger var_6
7  7   toe var_7

Now I have the following data frame which I want to rename the variables that matches the column tes and var of df1.

df2 <- data.frame(id = 1:3,
                  var_2 = c(12, 13, 14),
                  var_5 = c(22, 23, 24))
df2

> df2
  id var_2 var_5
1  1    12    22
2  2    13    23
3  3    14    24

Now the after renaming, the output should look like this,

> df2
  id meeny catch
1  1    12    22
2  2    13    23
3  3    14    24

I am trying to use dplyr::rename_with:

df2 |> 
  rename_with(~ df1, all_of(names(df2)))

But it shows an error

> df2 |> 
+   rename_with(~ df1, all_of(names(df2)))
Error in `rename_with()`:
! `.fn` must return a character vector, not a data frame.
Run `rlang::last_trace()` to see where the error occurred.

Any idea how to solve this issue?


Solution

  • We need a named vector as a lookup, not a dataframe:

    lookup <- setNames(df1$var, df1$tes)
    
    df2 |> rename(any_of(lookup))
    
    #  id meeny catch
    #1  1    12    22
    #2  2    13    23
    #3  3    14    24