Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename columns in R with dplyr using a character object?

Tags:

r

rename

dplyr

My data frame is as such:

#generic dataset
datatest <- data.frame(col1 = c(1,2,3,4), col2 = c('A', 'B', 'C', 'D'))

#character objects
name1 <- 'A'
name2 <- 'B'

I want to rename my columns using the name1 and name2 objects. These dynamically change in the code so I can't use the following:

#I DON'T WANT THIS
datatest %>% rename(A = col1, B = col2)

I want to use this:

datatest %>% rename(name1 = col1, name2 = col2)

but then the data table columns end up becoming 'name1' and 'name2' respectively, when they should be A and B. Here is the data table at the moment.

name1 (I want this to be A) name2 (I want this to be B)
1 A
2 B
3 C
4 D

Any help is hugely appreciated. I have the same issue with kable tables too. Thanks in advance!

like image 702
J_sdata Avatar asked Aug 30 '25 16:08

J_sdata


2 Answers

Couple of options -

  1. Using rename_with -
library(dplyr)

name1 <- 'A'
name2 <- 'B'

datatest %>% rename_with(~c(name1, name2), c(col1, col2))

#If there are only two columns in datatest
datatest %>% rename_with(~c(name1, name2))

#  A B
#1 1 A
#2 2 B
#3 3 C
#4 4 D
  1. Use a named vector
name <- c(A = 'col1', B = 'col2')
datatest %>% rename(!!name)
like image 107
Ronak Shah Avatar answered Sep 02 '25 08:09

Ronak Shah


You may try

datatest %>% rename({{name1}} := col1, {{name2}} := col2)

  A B
1 1 A
2 2 B
3 3 C
4 4 D
like image 44
Park Avatar answered Sep 02 '25 09:09

Park