Search code examples
rcountcumulative-sumrunning-count

Cumulative count of each value


I want to create a cumulative counter of the number of times each value appears.

e.g. say I have the column:

id  
1  
2  
3  
2  
2  
1  
2  
3

This would become:

id   count  
1     1  
2     1  
3     1  
2     2  
2     3  
1     2  
2     4  
3     2  

etc...


Solution

  • The dplyr way:

    library(dplyr)
    
    foo <- data.frame(id=c(1, 2, 3, 2, 2, 1, 2, 3))
    foo <- foo %>% group_by(id) %>% mutate(count=row_number())
    foo
    
    # A tibble: 8 x 2
    # Groups:   id [3]
         id count
      <dbl> <int>
    1     1     1
    2     2     1
    3     3     1
    4     2     2
    5     2     3
    6     1     2
    7     2     4
    8     3     2
    

    That ends up grouped by id. If you want it not grouped, add %>% ungroup().