两组矢量的交点

时间:2014-02-20 18:55:37

标签: r

我有两组11个向量,每个向量有大约8000个元素。

我希望制作一个11x11的矩阵,显示所有可能的向量组合之间的交叉长度。

有一种简单的方法吗?感谢


一个较小的例子:两组,每组三个向量。

第一集:

V1 <- c("a", "b")
V2 <- c("c", "d")
V3 <- c("e", "f")

第二集:

V4 <- c("a", "b", "d")
V5 <- c("e", "f")
V6 <- "c"

现在我想计算矢量V1,V2,V3和矢量V4,V5,V6之间所有可能的交点的长度,这样:

矢量V1和V4,V5,V6的交点长度分别为:2,0,0 矢量V2和V4,V5,V6的交点长度分别为:1,0,1 矢量V3和V4,V5,V6的交点长度分别为:0,2,0

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用100行的任意矩阵,11个向量(代表来自你的8k个元素的11个向量)

m<-matrix(sample(1:1000,1100, replace=T), nrow=100)
mat<-matrix(character(),ncol=11, nrow=11)
for (i in 1:11){
  for (j in i:11){
    mat[i,j]<-paste(intersect(m[,i],m[,j]),collapse=",")
  }
}

在编辑之后,仍然以5 * 11的矩阵回答,如果它的列表,11个向量,同样的方式

l1<-replicate(5,sample(letters,11))
l2<-replicate(5,sample(letters,11))
mat<-matrix(numeric(),ncol=11, nrow=11)
for (i in 1:11){
  for (j in 1:11){

    mat[i,j]<-length(intersect(l1[i,],l2[j,]))
  }

}



mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
 [1,]    0    2    2    0    0    2    0    1    0     2     1
 [2,]    1    0    2    1    0    1    0    1    2     1     1
 [3,]    1    1    1    0    1    0    0    0    1     1     0
 [4,]    0    1    1    1    1    1    3    1    1     2     0
 [5,]    2    0    1    1    1    1    0    1    1     1     1
 [6,]    0    1    2    1    0    1    1    1    0     1     1
 [7,]    0    0    2    1    0    0    1    2    0     0     4
 [8,]    0    0    1    1    1    0    1    2    0     0     2
 [9,]    1    1    0    2    1    2    1    0    1     1     0
[10,]    1    0    0    1    1    1    2    0    3     0     1
[11,]    1    1    1    0    0    1    1    2    2     0     1

作为清单,

ll1<-apply(l1,1,unique)
ll2<-apply(l2,1,unique)
mat<-matrix(numeric(),ncol=11, nrow=11)
for (i in 1:11){
  for (j in 1:11){

    mat[i,j]<-length(intersect(ll1[[i]],ll2[[j]]))
  }

}

答案 1 :(得分:1)

这是另一种可能性,使用您的示例数据:

# put the two set of vectors in lists
l1 <- list(V1 = c("a", "b"),
           V2 = c("c", "d"),
           V3 = c("e", "f"))

l2 <- list(V4 = c("a", "b", "d"),
           V5 = c("e", "f"),
           V6 = "c")

# create all combinations of list elements
idx <- expand.grid(seq_along(l1), seq_along(l2))

# loop over combinations of list elements with mapply
# for each combination, calculate length of intersect
# put result in matrix 
matrix(mapply(FUN = function(x, y) length(intersect(l1[[x]], l2[[y]])),
       idx[ , 2], idx[ , 1]),
       ncol = length(l2),
       byrow = TRUE,
       dimnames = list(names(l1), names(l2)))

#    V4 V5 V6
# V1  2  0  0
# V2  1  0  1
# V3  0  2  0