I need to find out how many times an instance of one variable occurred between two instances of another variable. Given the data:
v <- c(1, 0, 0, 1, 0, 0, 0, 1)
w <- c(0, 0, 1, 0, 0, 0, 1, 0)
x <- c(0, 0, 0, 1, 1, 0, 0, 0)
y <- c(0, 0, 0, 0, 0, 0, 0, 0)
z <- c(0, 0, 0, 1, 0, 0, 0, 0)
I want to see this:
some_function(v, w)
> 2
some_function(w, x)
> 1
some_function(w, y)
> 0
some_function(v, z)
> 1
Such that the first argument of some_function()
demarcates windows within which I can check whether anything happened in the second argument. Note that the output should not distinguish between the event happening once or twice within each window, but rather should count the number of windows within which one or more events occurred.
You can use rowsum()
, grouped by cumsum()
. This should be pretty quick.
some_function <- function(a, b) sum(rowsum(b, cumsum(a)) > 0)
some_function(v, w)
# [1] 2
some_function(w, x)
# [1] 1
some_function(w, y)
# [1] 0
some_function(w, z) ## possible typo in question
# [1] 1
some_function(v, z)
# [1] 1