与列表元素的所有可能组合相交 [英] Intersect all possible combinations of list elements

查看:80
本文介绍了与列表元素的所有可能组合相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量列表:

> 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"

我想计算列表元素的所有可能的成对组合之间的重叠长度,即(结果的格式无关紧要):

I would like to calculate the length of the overlap between all possible pairwise combinations of the list elements, i.e. (the format of the result doesn't matter):

AintB 2
AintC 2
AintD 0
BintC 1
BintD 0
CintD 1


我知道combn(x, 2)可用于获取向量中所有可能的成对组合的矩阵,而length(intersect(a, b))会给我两个向量的重叠长度,但是我想不出一种方法将这两件事放在一起.


I know combn(x, 2) can be used to get a matrix of all possible pairwise combinations in a vector and that length(intersect(a, b)) would give me the length of the overlap of two vectors, but I can't think of a way to put the two things together.

非常感谢您的帮助!谢谢.

Any help is much appreciated! Thanks.

推荐答案

combn也适用于列表结构,您只需要对结果进行一些unlist处理就可以使用intersect ...

combn works with list structures as well, you just need a little unlist'ing of the result to use 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

这篇关于与列表元素的所有可能组合相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆