计算两个零之间的数字

时间:2014-01-28 02:21:49

标签: r

假设我有一个载体,比如说:

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

我希望获得一个向两个零之间的值求和的向量,即输出应该如下:

y = c(1,2,4,1,1,1)

请注意,所有的开头都应该为零,最后为零,否则不会计算。所以字符串01010只产生1。

我尝试使用索引为零的游程长度。

先谢谢

1 个答案:

答案 0 :(得分:5)

sum.between.zeroes <- function(x) {
  library(stringr)
  x.str <- paste(x, collapse = "")
  nchar(str_extract_all(x.str, "01+0")[[1]]) - 2L
}

sum.between.zeroes(c(1,0,1,0,0,0,1,1,0,0,1,1,1,1,0,1,1,0,1,0,0,0,0,0,1,0,1,0,1,0))
# [1] 1 2 4 1 1 1

sum.between.zeroes(c(0,1,0,1,0))
# [1] 1

sum.between.zeroes(c(1,1))
# integer(0)

如果您想留在基本套餐中,可以使用gregexprregmatches

sum.between.zeroes <- function(x) {
  x.str <- paste(x, collapse = "")
  nchar(regmatches(x.str, gregexpr("01+0", x.str))[[1]]) - 2L
}