感谢 MrFlick:使用 Update1 版本不起作用,因为在 rowSums 中使用 . 会绕过 across()(请参阅评论 MrFlick)
因此,我们可以在 dplyr 工作流程中将rowwise 与c_across 和sum 一起使用:
这是一个例子,ID == 2:
2.更新:
数据:
df <- structure(list(ID = 2L, Item1 = 2L, Item2 = 3L, Item3 = 2L, Item4 = 3L,
Newvariable = 2L), class = "data.frame", row.names = c(NA,
-1L))
代码:
library(dplyr)
df %>%
rowwise() %>%
mutate(Total = sum(c_across(-ID)==2))
输出:
# Rowwise:
ID Item1 Item2 Item3 Item4 Newvariable Total
<int> <int> <int> <int> <int> <int> <int>
1 2 2 3 2 3 2 3
更新1: (不起作用)
在rowSums 中使用. 会绕过across()(见评论MrFlick)
df %>%
mutate(across(-ID), Total = rowSums(. == 2))
第一个答案:
我们可以使用rowSums:
library(dplyr)
df %>%
mutate(Total = rowSums(. == 2))
ID Item1 Item2 Item3 Item4 Newvariable Total
1 1 2 3 2 3 2 3