如何找出一个事件是否发生在另外两个事件之间
How to find out if an event occurred between two other events
我需要找出一个变量的实例在另一个变量的两个实例之间出现了多少次。给定数据:
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)
我想看这个:
some_function(v, w)
> 2
some_function(w, x)
> 1
some_function(w, y)
> 0
some_function(v, z)
> 1
这样 some_function()
的第一个参数划定 windows 在其中我可以检查第二个参数是否发生了任何事情。请注意,输出不应区分每个 window 中发生一次或两次的事件,而应计算发生一个或多个事件的 windows 的数量。
像这样:
some_function <- function(a, b){
sum(sapply(split(b, cumsum(a)), sum) > 0)
}
> some_function(v, w)
[1] 2
> some_function(w, x)
[1] 1
> some_function(w, y)
[1] 0
> some_function(w, z) # Not sure why you are getting 0 here?
[1] 1
> some_function(v, z)
[1] 1
基于findInterval()
的另一种方法:
some_function <- function(x, y) {
sum(unique(findInterval(which(y==1), which(x==1), left.open=TRUE)) != 0)
}
> some_function(v, w)
[1] 2
> some_function(w, x)
[1] 1
> some_function(w, y)
[1] 0
> some_function(w, z) # Probably a mistake in the question
[1] 1
> some_function(v, z)
[1] 1
您可以使用 rowsum()
,按 cumsum()
分组。这应该很快。
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
我需要找出一个变量的实例在另一个变量的两个实例之间出现了多少次。给定数据:
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)
我想看这个:
some_function(v, w)
> 2
some_function(w, x)
> 1
some_function(w, y)
> 0
some_function(v, z)
> 1
这样 some_function()
的第一个参数划定 windows 在其中我可以检查第二个参数是否发生了任何事情。请注意,输出不应区分每个 window 中发生一次或两次的事件,而应计算发生一个或多个事件的 windows 的数量。
像这样:
some_function <- function(a, b){
sum(sapply(split(b, cumsum(a)), sum) > 0)
}
> some_function(v, w)
[1] 2
> some_function(w, x)
[1] 1
> some_function(w, y)
[1] 0
> some_function(w, z) # Not sure why you are getting 0 here?
[1] 1
> some_function(v, z)
[1] 1
基于findInterval()
的另一种方法:
some_function <- function(x, y) {
sum(unique(findInterval(which(y==1), which(x==1), left.open=TRUE)) != 0)
}
> some_function(v, w)
[1] 2
> some_function(w, x)
[1] 1
> some_function(w, y)
[1] 0
> some_function(w, z) # Probably a mistake in the question
[1] 1
> some_function(v, z)
[1] 1
您可以使用 rowsum()
,按 cumsum()
分组。这应该很快。
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