繁体   English   中英

R:使用粘贴的引用列名

[英]R: Reference column name with paste

我正在尝试使用给定变量名称的粘贴来引用我的数据框中的列,并且该列未被识别。 下面是我尝试使用的示例数据框和变量名称:

arm <- "ARM"

ex_df <- data.frame(col1 = c("A","B","C"), col2 = c("X","Y","Z"), ARM_1 = c(1,2,3), ARM_2 = c(4,5,6,), ARM_3 = c(7,8,9), ARM_4 = c(0,0,0))

ex_df %>%
    transmute(col1 = col1, col2 = str_to_title(col2), paste0(arm,"_",4) = paste0(arm,"_",1) + paste0(arm,"_",2) + paste0(arm,"_",3)) %>%
    arrange(col1,col2)

Error: unexpected '=' in:
    "col2 = str_to_title(col2),
    paste0(arm,"_",4) = "

所需的输出应为 ARM_4 = ARM_1 + ARM_2 + ARM_3 并输出每列值的总和。

谢谢您的帮助。

我们可以使用:=!! - 以及以存储在arm中的值starts_with的列上的rowSums

library(dplyr)
library(stringr)
ex_df %>%
    transmute(col1 = col1, col2 = str_to_title(col2), 
    !!paste0(arm,"_",4) := rowSums(across(starts_with(arm)), na.rm = TRUE))

-输出

 col1 col2 ARM_4
1    A    X    12
2    B    Y    15
3    C    Z    18

注意:与+ - 1 相比, rowSums会更好 1)使用na.rm = TRUE处理NA元素,2)当有超过 10 个“ARM”列时使用紧凑选项


如果我们想通过paste获取列的值

ex_df %>%
    transmute(col1 = col1, col2 = str_to_title(col2), 
   !!paste0(arm,"_",4) := .data[[paste0(arm,"_",1)]] + 
                         .data[[paste0(arm,"_",2)]] + 
                        .data[[paste0(arm,"_",3)]]) %>%
    arrange(col1,col2)

-输出

 col1 col2 ARM_4
1    A    X    12
2    B    Y    15
3    C    Z    18

暂无
暂无

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

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