Home > Mobile >  R How to count by group starting when condition is met
R How to count by group starting when condition is met

Time:12-21

df <- data.frame (id  = c(1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,4),
                  qresult=c(0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0),
                  count=c(0,0,0,0,1,2,0,0,1,2,1,2,3,4,5,6))

> df
   id qresult count
1   1       0     0
2   1       0     0
3   1       0     0
4   2       0     0
5   2       1     1
6   2       0     2
7   3       0     0
8   3       0     0
9   3       1     1
10  3       0     2
11  4       1     1
12  4       0     2
13  4       0     3
14  4       0     4
15  4       0     5
16  4       0     6

What would be a way to obtain the count column which begins counting when the condition, q_result==1 is met and resets for each new id?

CodePudding user response:

We could wrap with double cumsum on a logical vector after grouping

library(dplyr)
df %>% 
  group_by(id) %>%
  mutate(count2 = cumsum(cumsum(qresult))) %>%
  ungroup

-output

# A tibble: 16 × 4
      id qresult count count2
   <dbl>   <dbl> <dbl>  <dbl>
 1     1       0     0      0
 2     1       0     0      0
 3     1       0     0      0
 4     2       0     0      0
 5     2       1     1      1
 6     2       0     2      2
 7     3       0     0      0
 8     3       0     0      0
 9     3       1     1      1
10     3       0     2      2
11     4       1     1      1
12     4       0     2      2
13     4       0     3      3
14     4       0     4      4
15     4       0     5      5
16     4       0     6      6
  • Related