Home > Enterprise >  How to rename a column using string from another column in R (dplyr)
How to rename a column using string from another column in R (dplyr)

Time:07-13


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

CodePudding user response:

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

CodePudding user response:

Base solution:

 colnames(data)[3] <- paste( colnames(data)[2:3], collapse="-")
  • Related