[R] counts of a vector

Erik Iverson eriki at ccbr.umn.edu
Wed May 26 20:35:53 CEST 2010



speretti wrote:
> Hi,
> 
> I need help to find an efficient way to transform a vector like:
> 
> a<-c(1,1,0,1,0,0,0,1,1,1,1,0,1,0,1,1)
> 
> in a vector that counts only di 1 elements, like:
> 
> b<-c(1,2,0,1,0,0,0,1,2,3,4,0,1,0,1,2)
> 
> 
> Thank you!

One way:

rl <- rle(a)

unlist(mapply("*", lapply(rl$lengths, function(x) 1:x), as.list(rl$values)))



More information about the R-help mailing list