Skip to content
Prev 385469 / 398506 Next

how to create a sequence to consecutive values

cumsum is a bit faster...

a <- c( 0, 0, 0, 1, 1, 1, 1, 0, 0, 0
      , 0, 1, 1, 0, 1, 1, 1, 0
      )

f1 <- function(a) {
  z <- rle(a)
  v <- z$values
  v[v==1] <- seq_along(v[v==1]) ## or use cumsum
  rep(v,z$lengths)
}

f2 <- function(a) {
  v <- cumsum( c( a[1], 1==diff(a) ) )
  v[ 0==a ] <- 0
  v
}

f2(a)

library(microbenchmark)

a2 <- rep( c( 0,0, 1, 1, 1 )
         , 300 )

microbenchmark( res1 <- f1(a2)
              , res2 <- f2(a2)
              )
stopifnot( res1 == res2 )
On August 28, 2020 8:19:41 AM PDT, Stefano Sofia <stefano.sofia at regione.marche.it> wrote: