Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

I am seeking a solution in tidyverse / dplyr packages.

like image 990
mnfn Avatar asked Aug 16 '17 15:08

mnfn


People also ask

How do I rename multiple columns in spark data frame?

Using col() function – To Dynamically rename all or multiple columns. Another way to change all column names on Dataframe is to use col() function.

How do you rename columns in a DataFrame PySpark?

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.

How do you name data frames?

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.


1 Answers

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
like image 129
Psidom Avatar answered Nov 03 '22 06:11

Psidom