Abigail575
Abigail575

Reputation: 175

Retrieving a list of nodes and edges from a specific cluster in igraph

Suppose I have the following clusters in a graph:

library("igraph")
set.seed(3)
g <- barabasi.game(20, m=2, directed=FALSE)
eb <- cluster_edge_betweenness(g)
plot(eb, g, layout=layout_with_fr) 

Is it possible to retrieve a list or data frame of the nodes and corresponding edges of the cluster containing the number 5? What about a node that is present in more than one cluster, such as 8 or 14?

Thanks!

Upvotes: 1

Views: 1524

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

Maybe you can try the code below

grps <- split(V(g),eb$membership)
grp <- unlist(subset(grps,mapply(`%in%`,5,grps)))
df <- subset(get.data.frame(g),from %in% grp & to %in% grp)

such that

> df
   from to
9     4  6
16    4 10
17    5 10
34    4 19
35    5 19

Upvotes: 1

desval
desval

Reputation: 2435

I am not aware of any method that lets do that automatically. However, you can easily do that by hand.

I am not sure about what you mean by "present in more than one cluster". Cluster membership is mutually exclusive, as you can see from the color of the nodes in the graph, and by the output of the betweenness clustering. There are 6 groups:

print(eb)
IGRAPH clustering edge betweenness, groups: 6, mod: 0.26
+ groups:
  $`1`
  [1]  1  2  3 14 15

  $`2`
  [1]  4  5  6 10 19

  $`3`
  [1]  7 11 16

  $`4`
  + ... omitted several groups/vertices

eb$membership
[1] 1 1 1 2 2 2 3 4 5 2 3 4 6 1 1 3 4 4 2 4

# extract all edges of the graph
d <- igraph::as_data_frame(g, what="edges")

# get membership of interested node
memb <- eb$membership[V(g)==5]
memb
[1] 2

# get all nodes with the same membership
memb_nodes <- V(g)[eb$membership==memb]
memb_nodes
+ 5/20 vertices, from 293a69d:
[1]  4  5  6 10 19

# subset
d <- d[d$from %in% memb_nodes & d$to %in% memb_nodes, ]
d
   from to
9     4  6
16    4 10
17    5 10
34    4 19
35    5 19

enter image description here

Upvotes: 2

Related Questions