guyabel
guyabel

Reputation: 8366

Create vector of the culmative counts per level

I have lots of little vectors like this:

 id<-c(2,2,5,2,1,9,4,4,3,9,5,5)

and I want to create another vector of the same length that has the cumulative number of occurrences of each id thus far. For the above example data this would look like:

> id.count
 [1] 1 2 1 3 1 1 1 2 1 2 2 3

I can not find a function that does this easily, maybe because I do not really know how to fully articulate in words what it is that I actually want (hence the slightly awkward question title). Any suggestions?

Upvotes: 2

Views: 119

Answers (2)

Sacha Epskamp
Sacha Epskamp

Reputation: 47541

Here is another way:

ave(id,id,FUN=seq_along)

Gives:

 [1] 1 2 1 3 1 1 1 2 1 2 2 3

Upvotes: 7

Backlin
Backlin

Reputation: 14842

> sapply(1:length(id), function(i) sum(id[1:i] == id[i]))
 [1] 1 2 1 3 1 1 1 2 1 2 2 3

Or if you have NAs in id you should use id[1:i] %in% id[i] instead.

Upvotes: 3

Related Questions