r - R:几个向量之间的所有交集
问题描述
在 R 中,向量 myvector 包含多个向量。我如何将 myvector 中的所有向量相互比较。我希望在 myvector 中的每两个向量之间有交集。
a <- c(1,2,3,4)
b <- c(1,3,5,7,8,9)
d <- c(1,2,5,7,9)
e <- c(1,3,4,8,0,10)
f <- c(2,3)
myvector <- c(a,b,d,e,f)
简而言之,如何简化模式如下。
intersect1 <- intersect(a,b)
intersect2 <- intersect(a,d)
intersect3 <- intersect(a,e)
intersect4 <- intersect(a,f)
intersect5 <- intersect(b,d)
#......
interscet_abd <- intersect(1,d)
interscet_abe <- intersect(1,e)
#......
intersect_abdef <- intersect(abde,f)
解决方案
将您的向量放入 a 中list
,然后您可以使用outer
a Vectorize
d intersect
:
l <- list(a,b,d,e,f)
names(l) = c("a", "b", "d", "e", "f")
result = outer(l, l, Vectorize(intersect))
result
# a b d e f
# a numeric,4 numeric,2 numeric,2 numeric,3 numeric,2
# b numeric,2 numeric,6 numeric,4 numeric,3 3
# d numeric,2 numeric,4 numeric,5 1 2
# e numeric,3 numeric,3 1 numeric,6 3
# f numeric,2 3 2 3 numeric,2
result["a", "d"]
# [[1]]
# [1] 1 2
受到这个答案的启发。
根据您的用例,您可能想要改进这个想法 -intersect
是可交换的,并且向量与其自身的相交并不有趣,因此通过执行每对有序组合,这会进行很多额外的计算。如果你有很多向量,使用combn
生成所有唯一的无序对会更有效,但这对于少量输入来说足够快。
推荐阅读
- ios - 如何将图像和有关这些图像的信息存储在 iPhone 内存中然后加载?
- webdriver - 在 Firefox 中使用 withFrame() 方法时 selenium.WebDriverException 抛出失败代码 0x80004005
- python - python点击setuptools集成问题
- biopython - Biopython Genbank.Record : 试图理解源代码
- excel - 如果另一个单元格中有值,则无法开发 vba 代码以复制某些单元格并将它们粘贴到依赖项中
- javascript - 包含 where 的环回查询
- php - PHP MYSQL 需要对特定列中具有相同值的行进行分组
- c# - botFramework v4 如何在 LUIS 调用后处理对话响应
- c# - 从代码 c# 自动配置 ceate IIS 服务或其他东西
- vb6 - 如何在构建管道中指定我的自定义代理?