首页 > 解决方案 > 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)

标签: r

解决方案


将您的向量放入 a 中list,然后您可以使用outera Vectorized 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生成所有唯一的无序对会更有效,但这对于少量输入来说足够快。


推荐阅读