Create counter within consecutive runs of certain values

William Dunlap’s posts on R-help are the place to look for all things related to run lengths. His f7 from this post is

f7 <- function(x){ tmp<-cumsum(x);tmp-cummax((!x)*tmp)}

and in the current situation f7(!x). In terms of performance there is

> x <- sample(0:1, 1000000, TRUE)
> system.time(res7 <- f7(!x))
   user  system elapsed 
  0.076   0.000   0.077 
> system.time(res0 <- cumul_zeros(x))
   user  system elapsed 
  0.345   0.003   0.349 
> identical(res7, res0)
[1] TRUE

Leave a Comment