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

How to tally occurrences of a value in a column in R?

I have the following data:

df <- data.frame(id = c("1", "1", "1", "1", "2", "2", "2"), 
                 x = c(0, 1, 0, 1, 0, 1, 0))

id x
 1 0
 1 1
 1 0
 1 1
 2 0
 2 1
 2 0

I want to tally the occurences of 1 in x. The desired output:

id x count
 1 0     0
 1 1     1
 1 0     0
 1 1     2
 2 0     0
 2 1     1
 2 0     0

How do I do this? A dplyr solution is preferred.

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

>Solution :

You may take cumulative sum of x values and keep the result to be 0 where value of x is 0 for each id.

library(dplyr)

df %>%
  mutate(count = replace(cumsum(x), x == 0, 0), .by = id)

#  id x count
#1  1 0     0
#2  1 1     1
#3  1 0     0
#4  1 1     2
#5  2 0     0
#6  2 1     1
#7  2 0     0
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