Union of intersecting vectors in a list in R

后端 未结 5 1311
北恋
北恋 2020-12-06 05:19

I have a list of vectors as follows.

data <- list(v1=c(\"a\", \"b\", \"c\"), v2=c(\"g\", \"h\", \"k\"), 
             v3=c(\"c\", \"d\"), v4=c(\"n\", \"a\         


        
5条回答
  •  情歌与酒
    2020-12-06 05:49

    This is kind of like a graph problem so I like to use the igraph library for this, using your sample data, you can do

    library(igraph)
    #build edgelist
    el <- do.call("rbind",lapply(data, embed, 2))
    #make a graph
    gg <- graph.edgelist(el, directed=F)
    #partition the graph into disjoint sets
    split(V(gg)$name, clusters(gg)$membership)
    
    # $`1`
    # [1] "b" "a" "c" "d" "n"
    # 
    # $`2`
    # [1] "h" "g" "k" "i"
    

    And we can view the results with

    V(gg)$color=c("green","purple")[clusters(gg)$membership]
    plot(gg)
    

    enter image description here

提交回复
热议问题