我试图引用一个列在我的数据框架粘贴给定的变量名称和列不被识别。下面是我试图使用的一个示例数据框架和变量名称:
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
注意: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