如何根据特定条件创建递增索引?

How to create an increasing index based on a certain condition?

假设我有这个数据框:

df <- data.frame(co11 = c(rep(1, 5), 5, 6, rep(1, 3), 2, 3, 4, 5, 8, rep(1, 2), rep(2, 2), 8, 10))

我想创建另一列 (col2),只要行中的值至少为 5,组索引就会增加。为了说明,这里是我想要的结果 df获得:

   co11  col2
1     1     1
2     1     1
3     1     1
4     1     1
5     1     1
6     5     2
7     6     3
8     1     3
9     1     3
10    1     3
11    2     3
12    3     3
13    4     3
14    5     4
15    8     5
16    1     5
17    1     5
18    2     5
19    2     5
20    8     6
21   10     7

dplyr 中是否有可以执行此操作的可用函数?谢谢!

您可以使用 pmax 查找每行的最大值,并使用 cumsum5 以上出现的次数求和:

df  %>% mutate(newcol=cumsum(do.call(pmax,select(.,everything()))>=5)+1)

   co11 newcol
1     1      1
2     1      1
3     1      1
4     1      1
5     1      1
6     5      2
7     6      3
8     1      3
9     1      3
10    1      3
11    2      3
12    3      3
13    4      3
14    5      4
15    8      5
16    1      5
17    1      5
18    2      5
19    2      5
20    8      6
21   10      7

Waldi 的回答很好,这里是一个稍微修改的版本:

library(dplyr)

df %>% 
  group_by(col2 =cumsum(co11 >= 5)+1) 
 co11 col2
1     1    1
2     1    1
3     1    1
4     1    1
5     1    1
6     5    2
7     6    3
8     1    3
9     1    3
10    1    3
11    2    3
12    3    3
13    4    3
14    5    4
15    8    5
16    1    5
17    1    5
18    2    5
19    2    5
20    8    6
21   10    7