Cumulative count of each value

user1165199 picture user1165199 · Apr 5, 2012 · Viewed 14.5k times · Source

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...

Thanks

Answer

Joshua Ulrich picture Joshua Ulrich · Apr 5, 2012

The ave function computes a function by group.

> id <- c(1,2,3,2,2,1,2,3)
> data.frame(id,count=ave(id==id, id, FUN=cumsum))
  id count
1  1     1
2  2     1
3  3     1
4  2     2
5  2     3
6  1     2
7  2     4
8  3     2

I use id==id to create a vector of all TRUE values, which get converted to numeric when passed to cumsum. You could replace id==id with rep(1,length(id)).