我有4个列表
a <- list(1,2,3,4) b <- list(5,6,7,8) c <- list(7,9,0) d <- list(12,14)我想知道哪些列表具有相同的元素.在此示例中,列表b和c具有共同的元素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更多推荐
列表的多个交集
发布评论