我有一个向量列表:
> l <- list(A=c("one", "two", "three", "four"), B=c("one", "two"), C=c("two", "four", "five", "six"), D=c("six", "seven"))
> l
$A
[1] "one" "two" "three" "four"
$B
[1] "one" "two"
$C
[1] "two" "four" "five" "six"
$D
[1] "six" "seven"
我想计算列表元素的所有可能的成对组合之间的重叠长度,即(结果的格式无关紧要):
AintB 2
AintC 2
AintD 0
BintC 1
BintD 0
CintD 1
我知道combn(x, 2)
可以用来获取向量中所有可能的成对组合的矩阵,length(intersect(a, b))
这会给我两个向量重叠的长度,但是我想不出一种将这两件事放在一起的方法。
任何帮助深表感谢!谢谢。
combn
同样适用于列表结构,您只需要使用一些unlist
结果即可intersect
...
# Get the combinations of names of list elements
nms <- combn( names(l) , 2 , FUN = paste0 , collapse = "" , simplify = FALSE )
# Make the combinations of list elements
ll <- combn( l , 2 , simplify = FALSE )
# Intersect the list elements
out <- lapply( ll , function(x) length( intersect( x[[1]] , x[[2]] ) ) )
# Output with names
setNames( out , nms )
#$AB
#[1] 2
#$AC
#[1] 2
#$AD
#[1] 0
#$BC
#[1] 1
#$BD
#[1] 0
#$CD
#[1] 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句