Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading