合并在公共 R 中甚至有一个元素的集合 [英] merging sets which have even one element in common R

查看:39
本文介绍了合并在公共 R 中甚至有一个元素的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

lista=list()    
lista[[1]]=c( 1,  2,  4,  6,  8,  9, 10, 11, 12, 19, 32, 34, 35, 36, 37, 38)    
lista[[2]]=c(7,8)    
lista[[3]]=c(13, 14, 16, 26, 27, 28, 29, 30, 31)    
lista[[4]]=c(20, 21, 23, 25, 27, 28, 29, 30)    
lista[[5]]=c(9,10,39)
lista[[6]]=c(39,40)

所以我希望我的输出是这样的:

group[[1]]=c(1,2,4,6,7,8,9,10,11,12,19,32,34,35,36,37,38,39,40)    
group[[2]]=c(13,14,16,20,21,23,24,26,27,28,29,30,31)

打开盒子":

lista[[1]]lista[[2]]lista[[5]] 合并,因为它们有公共元素.

lista[[1]], lista[[2]] and lista[[5]] merged because they have commom elements.

lista[[5]]lista[[6]] 合并,因为它们有公共元素.所以,lista[[5]] 连接 lista[[1]]lista[[2]]lista[[5]].

lista[[5]] and lista[[6]] merged because they have commom elements. So, lista[[5]] connect lista[[1]], lista[[2]] and lista[[5]].

我正在尝试这张票:

合并共享公共元素的列表

推荐答案

这是另一种方法,它构造一个矩阵,显示列表的哪些元素彼此相交,并使用 igraph 包来推导组:

Here is another approach which constructs a matrix showing which elements of the list intersect with each other and uses the igraph package to deduce the groups:

library(igraph)
## Construct the matrix
m = sapply(lista,function(x) sapply(lista,function(y) length(intersect(x,y))>0))
      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
[1,]  TRUE  TRUE FALSE FALSE  TRUE FALSE
[2,]  TRUE  TRUE FALSE FALSE FALSE FALSE
[3,] FALSE FALSE  TRUE  TRUE FALSE FALSE
[4,] FALSE FALSE  TRUE  TRUE FALSE FALSE
[5,]  TRUE FALSE FALSE FALSE  TRUE  TRUE
[6,] FALSE FALSE FALSE FALSE  TRUE  TRUE

## Determine the groups of the graph constructed from m
groups = groups(components(graph_from_adjacency_matrix(m)))
$`1`
[1] 1 2 5 6

$`2`
[1] 3 4

## Get the unique elements of each group
res = lapply(groups,function(x) sort(unique(unlist(lista[x]))))
$`1`
 [1]  1  2  4  6  7  8  9 10 11 12 19 32 34 35 36 37 38 39 40

$`2`
 [1] 13 14 16 20 21 23 25 26 27 28 29 30 31

这篇关于合并在公共 R 中甚至有一个元素的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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