mnfn mnfn - 2 months ago 18
R Question

Programmatically rename data frame columns using lookup data frame

What is the best way to batch rename columns using a lookup data frame?

Can I do it as part of a pipe?

library(tidyverse)

df <- data_frame(
a = seq(1, 10)
, b = seq(10, 1)
, c = rep(1, 10)
)

df_lookup <- data_frame(
old_name = c("b", "c", "a")
, new_name = c("y", "z", "x")
)


I know how to do it manually

df %>%
rename(x = a
, y = b
, z = c)


And I know enough R to write a bad function to do it myself, but there must be a good way to do this using tidyverse / dplyr 0.7 packages.

Thanks

Answer Source

Use rlang; Firstly build up a list of names using syms, and then splice the arguments to rename with UQS or !!! operator:

library(rlang); library(dplyr)

df %>% rename(!!!syms(with(df_lookup, setNames(old_name, new_name))))

# A tibble: 10 x 3
#       x     y     z
#   <int> <int> <dbl>
# 1     1    10     1
# 2     2     9     1
# 3     3     8     1
# 4     4     7     1
# 5     5     6     1
# 6     6     5     1
# 7     7     4     1
# 8     8     3     1
# 9     9     2     1
#10    10     1     1