英文:
Counting intersections per run of 1s in the first of two logical vectors
问题
这个问题的更一般版本已经在这里得到了回答。一位用户建议我提出这个更具体版本的问题作为一个独立的帖子。
我有两个逻辑向量,看起来像这样:
x = c(0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0)
y = c(0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0)
我想要计算连续值范围(在这个例子中是1111)之间的交集,以便在第一个向量中的每个1运行中最多计算一个交集。
使用上述提到的答案中的 sum(rle(x & y)$values)
,我可以计算上述向量的总交集数为两个,但我期望是一个。
英文:
A more general version of this question has been answered here. A user proposed I ask this more specific version of the question as a separate post.
I have two logical vectors which look like this:
x = c(0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0)
y = c(0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0)
I want to count the intersections between ranges of consecutive values (in this example 1111) in such a way, that at most one intersection per run of 1s in the first vector is counted.
Using sum(rle(x & y)$values)
from the above mentioned answer, I can count the total number of intersections of the above vectors as two, but I expect one.
答案1
得分: 2
你想要求交集的最大长度为1吗?如果是的话,你可以这样做:
sum(with(rle(x & y), lengths == 1 & values))
#[1] 1
当我们执行 x & y
时,x
和 y
的数值被转换为逻辑值,其中1表示为 TRUE
,FALSE
表示为0。由于我们只关心1(即 TRUE
)的交集,最多只允许1个交集,所以我们计算满足条件的次数,即 lengths == 1
(或者 lengths <= 1
,因为我们需要检查最多的情况),以及 values
意味着只有1(即 TRUE
)。
英文:
Do you want max length of the intersection to be 1. If so, you can do
sum(with(rle(x & y), lengths == 1 & values))
#[1] 1
When we do x & y
the numeric values of x
and y
are changed to logical values where 1 is represented as TRUE
and FALSE
as 0. Since we are only interested in intersection of 1's (i.e TRUE
) with at most 1 intersection we count the number of times where this condition is satisfied i.e lengths == 1
(or lengths <= 1
as we need to check for at most) and values
meaning only 1's i.e TRUE
.
答案2
得分: 0
sum(with(rle(x & y), lengths * values) == 1)
#1 1
英文:
We can also write it as
sum(with(rle(x & y), lengths * values) == 1)
#[1] 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论