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)
I am seeking a solution in tidyverse / dplyr packages.
Using col() function – To Dynamically rename all or multiple columns. Another way to change all column names on Dataframe is to use col() function.
PySpark has a withColumnRenamed() function on DataFrame to change a column name. This is the most straight forward approach; this function takes two parameters; the first is your existing column name and the second is the new column name you wish for. Returns a new DataFrame with a column renamed.
Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With