首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >两组向量的相交

两组向量的相交
EN

Stack Overflow用户
提问于 2014-02-20 18:55:36
回答 2查看 824关注 0票数 0

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

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

有什么简单的方法吗?谢谢

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

第一套:

代码语言:javascript
复制
V1 <- c("a", "b")
V2 <- c("c", "d")
V3 <- c("e", "f")

第二套:

代码语言:javascript
复制
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

谢谢你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2014-02-20 19:14:54

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

代码语言:javascript
复制
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个向量,同样的方式

代码语言:javascript
复制
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

作为名单,

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-02-20 21:48:36

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

代码语言:javascript
复制
# 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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21917001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档