另一种更快的方法不使用rle是用连续的0分割,如下所示:
# following thelatemail's comment, changed '0+' to '[^1]+'
strsplit(x, "[^1]+", perl=TRUE)
然后您可以循环并获取列表中每个元素的最大字符数。这也将比rle 解决方案更快。并且也比@Joshua 的gregexpr 解决方案更快。一些基准测试...
zz <- function(x) {
vapply(strsplit(x, "[^1]+", perl=TRUE), function(x) max(nchar(x)), 0L)
}
我刚刚意识到@Joshua 的功能也可以通过添加perl=TRUE 和使用vapply 来调整。所以,我也会比较一下。
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