简体   繁体   English

如何使用 R 中另一列的字符串重命名列(dplyr)

[英]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.我正在尝试通过粘贴第二列中的字符串来重命名数据框中的第三列( May 22 )。 My end goal is to have the third column named "Apr 22 - May 22".我的最终目标是将第三列命名为“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="-")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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