Home > Mobile >  How to identify multiple independent subgraphs and assign its corresponding subgraph to each node in
How to identify multiple independent subgraphs and assign its corresponding subgraph to each node in

Time:09-25

I have a problem with network data in R. Suppose I have a graph that looks like this:

library(igraph)
a1=data.frame(A=c(1,1,2,2,3,7,9,10),B=c(2,3,4,5,6,8,8,11))
a2=graph_from_data_frame(a1, directed = F)
plot(a2)

I can see that there are three independent subgraphs, and nodes 1 to 6 belong to subgraph 1, nodes 7 to 9 belong to subgraph 2, and nodes 10 and 11 belong to subgraph 3.

a3=data.frame(node=c(1:11),sub=c(1,1,1,1,1,1,2,2,2,3,3))

I want to output a table like a3, and is there direct code to do this assignment in R?

CodePudding user response:

Here is a solution.

sub <- clusters(a2)$membership
a3 <- data.frame(node = names(sub), sub)
a3 <- a3[order(as.integer(a3$node)), ]
a3

An alternative:

cmp <- components(a2)
data.frame(node = unlist(groups(cmp)), 
           sub = sort(as.integer(cmp$membership)))

CodePudding user response:

Another option using decompose

> Map(
    function(x, y) data.frame(node = names(V(x)), sub = y),
    d <- decompose(a2),
    seq_along(d)
  )
[[1]]
  node sub
1    1   1
2    2   1
3    3   1
4    4   1
5    5   1
6    6   1

[[2]]
  node sub
1    7   2
2    9   2
3    8   2

[[3]]
  node sub
1   10   3
2   11   3
  • Related