Reputation: 21
Suppose I have a vector, say:
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)
and I would like to obtain a vector that sums the values that falls between two zeros, i.e. the output should look like:
y = c(1,2,4,1,1,1)
Note that all ones should have zero at the beginning and zero at the end, otherwise it will not be counted. so the string 01010 only produce 1.
I tried to use run length with an index of zeros.
Thanks in Advance
Upvotes: 0
Views: 148
Reputation: 89067
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)
If you want to remain within the base package, you can use gregexpr
and regmatches
:
sum.between.zeroes <- function(x) {
x.str <- paste(x, collapse = "")
nchar(regmatches(x.str, gregexpr("01+0", x.str))[[1]]) - 2L
}
Upvotes: 5