正如您可能已经猜测的那样,我很难描述这个问题。我想通过对现有列的子集(由这些变量名称的小元素定义)求和来计算一个新变量包括其名称,然后根据新创建的变量计算一个新的条件变量。一如既往,通过示例更容易展示。玩具数据。总共七列,一列是 ID 变量,三列是大麻测量值(由列名中间的字母“cann”定义),三列是酒精测量值(由同一列中的字母“alc”定义)位置)。
set.seed(1)
d <- data.frame(id = letters[1:10],
q1_cann_a = round(rnorm(10),1),
q1_cann_b = round(rnorm(10),1),
q1_cann_c = round(rnorm(10),1),
q1_alc_a = round(rnorm(10),1),
q1_alc_b = round(rnorm(10),1),
q1_alc_c = round(rnorm(10),1))
d
# output
# id q1_cann_a q1_cann_b q1_cann_c q1_alc_a q1_alc_b q1_alc_c
# 1 a -0.6 1.5 0.9 1.4 -0.2 0.4
# 2 b 0.2 0.4 0.8 -0.1 -0.3 -0.6
# 3 c -0.8 -0.6 0.1 0.4 0.7 0.3
# 4 d 1.6 -2.2 -2.0 -0.1 0.6 -1.1
# 5 e 0.3 1.1 0.6 -1.4 -0.7 1.4
# 6 f -0.8 0.0 -0.1 -0.4 -0.7 2.0
# 7 g 0.5 0.0 -0.2 -0.4 0.4 -0.4
# 8 h 0.7 0.9 -1.5 -0.1 0.8 -1.0
# 9 i 0.6 0.8 -0.5 1.1 -0.1 0.6
# 10 j -0.3 0.6 0.4 0.8 0.9 -0.1
现在说我想计算三个大麻列的总和,所以我创建了一个函数,我可以将每组三个变量名称的中心字符串传递到一个函数中,该函数从该字符串中创建一个新的变量名称“_total”粘贴到末尾。那部分我能做。下一步(我无法完成)是使用新创建的变量创建一个新的条件变量,在这种情况下,如果三个变量的总和 > 0,则该元素为“正”(如果不 > 0) ,“负”。
sumFunct <- function(data, drug) {
d %>%
rowwise %>%
mutate(!!paste0(drug, "_total") := sum(c_across(contains(drug))),
!!paste0(drug, "_any") := factor(case_when(!!paste0(drug, "_total") > 0 ~ "positive",
TRUE ~ "negative"),
levels = c("negative",
"positive")))
}
sumFunct(d, "cann")
# A tibble: 10 × 9
# Rowwise:
# id q1_cann_a q1_cann_b q1_cann_c q1_alc_a q1_alc_b q1_alc_c cann_total cann_any
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <fct>
# 1 a -0.6 1.5 0.9 1.4 -0.2 0.4 1.8 positive
# 2 b 0.2 0.4 0.8 -0.1 -0.3 -0.6 1.4 positive
# 3 c -0.8 -0.6 0.1 0.4 0.7 0.3 -1.3 positive
# 4 d 1.6 -2.2 -2 -0.1 0.6 -1.1 -2.6 positive
# 5 e 0.3 1.1 0.6 -1.4 -0.7 1.4 2 positive
# 6 f -0.8 0 -0.1 -0.4 -0.7 2 -0.9 positive
# 7 g 0.5 0 -0.2 -0.4 0.4 -0.4 0.3 positive
# 8 h 0.7 0.9 -1.5 -0.1 0.8 -1 0.1 positive
# 9 i 0.6 0.8 -0.5 1.1 -0.1 0.6 0.9 positive
# 10 j -0.3 0.6 0.4 0.8 0.9 -0.1 0.7 positive
正如您所看到的,第一部分工作正常,条件的 name 有效,但条件本身失败了。我很确定这与计算
:=
右侧第二个变量的语法部分中第一个新变量的重述有关,但我不知道如何修复它。我在整理东西方面遇到了严重的麻烦,所以非常感谢任何帮助。我还会就如何更好地命名这篇文章寻求建议。
这就是我解决问题的方法。
rowwise
,而不是 sum
和 rowSums
。!!paste0(drug, "_total")
不正确,请改用 .data
。library(dplyr)
sumFunct <- function(data, drug) {
d %>%
mutate(!!paste0(drug, "_total") := rowSums(pick(contains(drug))),
!!paste0(drug, "_any") := factor(
case_when(.data[[paste0(drug, "_total")]] > 0 ~ "positive",
TRUE ~ "negative"),levels = c("negative","positive")))
}
sumFunct(d, "cann")
# id q1_cann_a q1_cann_b q1_cann_c q1_alc_a q1_alc_b q1_alc_c cann_total cann_any
#1 a -0.6 1.5 0.9 1.4 -0.2 0.4 1.8 positive
#2 b 0.2 0.4 0.8 -0.1 -0.3 -0.6 1.4 positive
#3 c -0.8 -0.6 0.1 0.4 0.7 0.3 -1.3 negative
#4 d 1.6 -2.2 -2.0 -0.1 0.6 -1.1 -2.6 negative
#5 e 0.3 1.1 0.6 -1.4 -0.7 1.4 2.0 positive
#6 f -0.8 0.0 -0.1 -0.4 -0.7 2.0 -0.9 negative
#7 g 0.5 0.0 -0.2 -0.4 0.4 -0.4 0.3 positive
#8 h 0.7 0.9 -1.5 -0.1 0.8 -1.0 0.1 positive
#9 i 0.6 0.8 -0.5 1.1 -0.1 0.6 0.9 positive
#10 j -0.3 0.6 0.4 0.8 0.9 -0.1 0.7 positive
在您的方法中,如果您根据第 2 点进行更改,它也应该有效。