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)
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.
Is there any R package for range intersections which could help here?
解决方案
我认为这应该有效(调用你的逻辑向量x
和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
计数。
推荐阅读
- python-3.x - 通过所有方法安装opencv后无法安装和导入cv2
- python - 如何比较两个 Pandas DataFrame 并显示 DataFrame 2 中的差异
- bash - 使用 sed 删除日志中的日期
- solr - Solr云集群可以做增量备份吗?
- magento2 - 如何在销售订单网格上使用批量操作显示弹出窗口 - Magento 2.2.4
- python - 更改 matplotlib 动画中点的颜色
- python - GoogleCloudStorageToBigQueryOperator source_objects 通过 XCom 接收列表
- java - 创建对象时的 Mockito 来自其他类的私有方法
- sap - 在java中过滤JCoTable
- xamarin - Xamarin UITest:正在安装 DeviceAgent,但未运行 .APP 和测试