An alternative much faster way without using rle
would be to split with consecutive 0's as follows:
# following thelatemail's comment, changed '0+' to '[^1]+'
strsplit(x, "[^1]+", perl=TRUE)
Then you can loop over and get maximum characters for each element of your list. This'll be faster than rle
solution as well. and is also faster than the gregexpr
solution from @Joshua. Some benchmarking...
zz <- function(x) {
vapply(strsplit(x, "[^1]+", perl=TRUE), function(x) max(nchar(x)), 0L)
}
I just realised that @Joshua's function could also be tweaked by adding perl=TRUE
and using vapply
. So, I'll compare that as well.
g2 <- function(S) vapply(gregexpr("1*",S, perl=TRUE),
function(x) max(attr(x,'match.length')), 0L)
require(microbenchmark)
microbenchmark(t1 <- zz(unname(s)), t2 <- g(unname(s)), t3 <- g2(unname(s)), times=50)
Unit: seconds
expr min lq median uq max neval
t1 <- zz(unname(s)) 1.187197 1.285065 1.344371 1.497564 1.565481 50
t2 <- g(unname(s)) 2.154038 2.307953 2.357789 2.417259 2.596787 50
t3 <- g2(unname(s)) 1.562661 1.854143 1.914597 1.954795 2.203543 50
identical(t1, t2) # [1] TRUE
identical(t1, t3) # [1] TRUE