简体   繁体   中英

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

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

基础解决方案:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM