santoku
santoku

Reputation: 3427

how to filter out small subgraphs in R

suppose I have a network like this with multiple subgraphs.

How can I only keep the subgraph with the most number of vertices while removing the rest? In this case I want to keep the subgraph on the left and remove the 3-vertices one the lower right. Thanks!

enter image description here

Upvotes: 1

Views: 219

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48191

Given

set.seed(1)
g <- sample_gnp(20, 1 / 20)
plot(g)

enter image description here

we wish to keep the subgraph with 6 vertices. Using

(clu <- components(g))
# $membership
#  [1]  1  2  3  4  5  4  5  5  6  7  8  9 10  3  5 11  5  3 12  5

# $csize
#  [1] 1 1 3 2 6 1 1 1 1 1 1 1

# $no
# [1] 12
gMax <- induced_subgraph(g, V(g)[clu$membership == which.max(clu$csize)])

we then get

plot(gMax)

enter image description here

This assumes that there is a single largest connected subgraph. Otherwise the "first" one will be chosen.

Upvotes: 4

Related Questions