Skip to content
Prev 182072 / 398500 Next

Generating a count variable

On Jun 1, 2009, at 1:14 PM, Joseph Magagnoli wrote:

            
The rle function is generally useful for such problems. Having created  
a data.frame, dd, with those elements:

  rledd<- rle(paste(dd$Country,dd$MID,sep=".") )

  as.vector(unlist(sapply(rledd$lengths, FUN=function(x) seq(1,x)))) -  
dd$MID
  [1] NA  1  2  0  1  1  0  1  2  3

 > dd$Count <- as.vector(unlist(sapply(rledd$lengths, FUN=function(x)  
seq(1,x))))-dd$MID
 > dd
    Country MID Count
1        1  NA    NA
2        1   0     1
3        1   0     2
4        1   1     0
5        1   0     1
6        2   0     1
7        2   1     0
8        2   0     1
9        2   0     2
10       2   0     3