列表的多个交集 [英] Multiple intersection of lists

查看:84
本文介绍了列表的多个交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个列表

a <- list(1,2,3,4)
b <- list(5,6,7,8)
c <- list(7,9,0)
d <- list(12,14)

我想知道哪些列表具有相同的元素.在此示例中,列表bc具有共同的元素7.

I would like to know which of the lists have elements in common. In this example, lists b and c have the element 7 in common.

暴力破解方法是获取列表的每个组合并找到交点.在R中还有其他有效的方法吗?

A brute force approach would be to take every combination of lists and find the intersection. Is there any other efficient way to do it in R?

另一种方法是从所有列表中创建一个列表,然后查找重复的列表.然后,也许我们可以使用映射功能来指示这些重复项来自哪个原始列表.但是我不确定如何去做.我碰到了这篇文章

Another approach would be to make a single list from all the lists and find the duplicates. Then maybe we could have a mapping function to indicate from which original lists these duplicates are from. But am not so sure about how to do it. I came across this post

查找重复行的索引

我在考虑是否可以对其进行修改,以找出包含重复项的实际列表.

I was thinking if we could modify this to find out the actual lists which have duplicates.

我必须对许多列表组重复此过程. 任何建议/想法将不胜感激! 预先感谢

I have to repeat this process for many groups of lists. Any suggestions/ideas are greatly appreciated! Thanks in advance

推荐答案

使用双重sapply怎么办?

l <- list(a,b,c,d)

sapply(seq_len(length(l)), function(x) 
  sapply(seq_len(length(l)), function(y) length(intersect(unlist(l[x]), unlist(l[y])))))
     [,1] [,2] [,3] [,4]
[1,]    4    0    0    0
[2,]    0    4    1    0
[3,]    0    1    3    0
[4,]    0    0    0    2

解释:例如矩阵的[1,2]元素显示列表l的第一个元素(在本例中为子列表a)与第二个列表元素(即子列表b)有多少个元素

Interpretation: e.g. the element [1,2] of the matrix shows you how many elements the first element of the list l (in this case the sublist a) has in commom with the second list element (i.e. the sublist b)

或者仅查看与其他子列表具有相同值的子列表的索引:

Or alternatively just to see the indices of the sublists which have a common value with some other sublist:

which(sapply(seq_len(length(l)), function(x) length(intersect(l[[x]], unlist(l[-x])))) >= 1)
[1] 2 3

这篇关于列表的多个交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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