R中逻辑向量中连续值的相交范围 [英] Intersecting ranges of consecutive values in logical vectors in R
问题描述
我有两个逻辑向量,如下所示:
I have two logical vectors which look like this:
x = c(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
y = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
我想计算连续值范围之间的交集.这意味着连续值(1 秒)作为一个范围处理.所以在上面的例子中,每个向量包含一个 1 的范围,这些范围只相交一次.
I would like to count the intersections between ranges of consecutive values. Meaning that consecutive values (of 1s) are handled as one range. So in the above example, each vector contains one range of 1s and these ranges intersect only once.
是否有任何用于范围交叉的 R 包可以在这里提供帮助?
Is there any R package for range intersections which could help here?
推荐答案
我认为这应该可行(调用您的逻辑向量 x
和 y
):
I think this should work (calling your logical vectors x
and y
):
sum(rle(x & y)$values)
几个例子:
x = c(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
y = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
sum(rle(x & y)$values)
# [1] 1
x = c(1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
y = c(0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
sum(rle(x & y)$values)
# [1] 2
x = c(1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0)
y = c(0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0)
sum(rle(x & y)$values)
# [1] 3
作为解释,x &y
给出每个元素级别的交集,rle
折叠相邻交集的运行,以及 sum
计数.
By way of explanation, x & y
gives the intersections on a per-element level, rle
collapses runs of adjacent intersections, and sum
counts.
这篇关于R中逻辑向量中连续值的相交范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!