根据条件统计30个变量?

Count 30 variables based on condition?

大家好,我是 R 的新手,我基本上得到了一个由 31 个变量(ID,以及编码为 1、2、3 的 30 个项目)组成的数据框

我想根据特定条件创建一个新变量..我想这样:

(因为 2 只出现在这 2 个项目(item1 和 item3)中,所以基本上我想创建一个新变量来显示在这 30 个项目中选择了多少次 2)

非常感谢您的帮助

此致

感谢 MrFlick:使用 Update1 版本不起作用,因为在 rowSums 中使用 . 会绕过 across()(参见评论 MrFlick)

因此我们可以在 dplyr 工作流程中将 rowwisec_acrosssum 一起使用:

这是一个示例,其中 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

Update1: (不起作用)

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