需要帮助计算具有多个条件(包括部分字符串)的多个列的出现次数,然后汇总这些结果

Need help counting occurences with respect to multiple columns with multiple conditions (including a partial string), then aggregating those results

我找不到一个简单的方法来执行以下操作:

我需要计算 整个 行中下列条件成立的次数: “t2”x2=4x3=0

在下面的数据框中,第 8、10 和 19 行都是如此。所以答案是 (t2, x2=4, x3=0) = 3 因为迭代发生了两次。

     x1 x2 x3
1  t2xy  1  0
2  m1xy  3  0
3  m2xy  3  0
4  t1xy  4  1
5  m1yx  3  1
6  m2xy  3  1
7  m2yx  3  0
8  t2yx  4  0
9  t1xy  4  0
10 t2yx  4  0
11 m2yx  1  0
12 m1xy  3  0
13 m2yx  3  0
14 m2xy  1  0
15 t2yx  4  1
16 t2xy  1  1
17 m1xy  2  1
18 t1xy  2  1
19 t2xy  4  0
20 t1yx  2  1

我需要为每个部分字符串匹配执行此操作:t1、t2、m1、m2 并存储在它们自己的变量中或以某种方式聚合。这是 t1:

的所有排列的示例
(t1, x2=1, x3=0) = 12
(t1, x2=1, x3=1) = 15
(t1, x2=2, x3=0) = 7
(t1, x2=2, x3=1) = 6
(t1, x2=3, x3=0) = 11
(t1, x2=3, x3=1) = 9
(t1, x2=4, x3=0) = 9
(t1, x2=4, x3=1) = 13

(这些输出只是示例,并不反映上述数据帧)

这也适用于 t2、m1 和 m2 排列。

这是我用来创建一些假数据的代码:

x1<- sample(c("t1xy", "t2xy", "m1xy", "m2xy","t1yx", "t2yx", "m1yx", "m2yx"), 20, replace = T)
x2<- sample(1:4, 20, replace = T)
x3<- sample(0:1, 20, replace = T)

df_x <- data.frame(x1,x2,x3)
df_x

提前致谢!

我们可以使用 add_count 条件:

library(dplyr)
library(stringr)
df %>% 
  add_count(t2 = str_detect(x1, "t2") & x2==4 & x3==0)
     x1 x2 x3    t2  n
1  t2xy  1  0 FALSE 17
2  m1xy  3  0 FALSE 17
3  m2xy  3  0 FALSE 17
4  t1xy  4  1 FALSE 17
5  m1yx  3  1 FALSE 17
6  m2xy  3  1 FALSE 17
7  m2yx  3  0 FALSE 17
8  t2yx  4  0  TRUE  3
9  t1xy  4  0 FALSE 17
10 t2yx  4  0  TRUE  3
11 m2yx  1  0 FALSE 17
12 m1xy  3  0 FALSE 17
13 m2yx  3  0 FALSE 17
14 m2xy  1  0 FALSE 17
15 t2yx  4  1 FALSE 17
16 t2xy  1  1 FALSE 17
17 m1xy  2  1 FALSE 17
18 t1xy  2  1 FALSE 17
19 t2xy  4  0  TRUE  3
20 t1yx  2  1 FALSE 17