列表的多个交集

编程入门 行业动态 更新时间:2024-10-15 02:33:57
本文介绍了列表的多个交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有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

更多推荐

列表的多个交集

本文发布于:2023-11-29 12:25:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!