Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R How to count by group starting when condition is met

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading