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 a column using string from another column in R (dplyr)


data <- structure(list(Fruit = c("Apple", "Berry", "Cherry"), `Apr 22` = c(1, 
2, 3), `May 22` = c(4, 5, 6)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -3L))

I am trying to rename the third column in my dataframe (May 22) by pasting in the string from my second column. My end goal is to have the third column named "Apr 22 – May 22". Intuitively, I thought that something like this would work

library(dplyr)

data %>% 
  rename(paste(colnames(2), "-", colnames(3)) = 3)

However this doesn’t get me to what I need. Any suggestions

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

>Solution :

Use := with !!

library(dplyr)
data <- data %>% 
  rename(!!paste(colnames(.)[2], "-", colnames(.)[3]) := 3)

-output

data
# A tibble: 3 × 3
  Fruit  `Apr 22` `Apr 22 - May 22`
  <chr>     <dbl>             <dbl>
1 Apple         1                 4
2 Berry         2                 5
3 Cherry        3                 6
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