统计两个逻辑向量中第一个向量中每个连续的1序列的交点数量。

huangapple go评论69阅读模式
英文:

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 时,xy 的数值被转换为逻辑值,其中1表示为 TRUEFALSE 表示为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 &amp; y), lengths == 1 &amp; values))
#[1] 1

When we do x &amp; 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 &lt;= 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 &amp; y), lengths * values) == 1)
#[1] 1

huangapple
  • 本文由 发表于 2020年1月6日 16:49:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定