简体   繁体   English

R:使用粘贴的引用列名

[英]R: Reference column name with paste

I am attempting to reference a column in my data frame with paste given a variable name and the column is not being recognized.我正在尝试使用给定变量名称的粘贴来引用我的数据框中的列,并且该列未被识别。 Below is an example data frame and variable names that I am attempting to work with:下面是我尝试使用的示例数据框和变量名称:

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) = "

The desired output should read ARM_4 = ARM_1 + ARM_2 + ARM_3 and output the sum of each columns values.所需的输出应为 ARM_4 = ARM_1 + ARM_2 + ARM_3 并输出每列值的总和。

Thank you for your help.谢谢您的帮助。

We can use := with !!我们可以使用:=!! - along with rowSums on the columns that starts_with the value stored in arm - 以及以存储在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))

-output -输出

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

NOTE: rowSums would be better compared to + - 1) take care of NA elements with na.rm = TRUE , 2) compact option when there are more than 10 'ARM' columns注意:与+ - 1 相比, rowSums会更好 1)使用na.rm = TRUE处理NA元素,2)当有超过 10 个“ARM”列时使用紧凑选项


In case we want to get the value of the column with paste如果我们想通过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)

-output -输出

 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