Reputation: 1031
I created a simulated network (via SBM) the igraph
package in R:
library(igraph)
pr_mat <- cbind(c(0.5,0.001), c(0.001, 0.5))
g <- sample_sbm(10, pref.matrix = pr_mat, block.sizes = c(5,5),
directed = FALSE, loops = FALSE)
The adjacency matrix of graph g
confirms that nodes 1-5 are considered one group, and nodes 6-10 are considered another group.
> as_adj(g)
[1,] . 1 . 1 . . . . . .
[2,] 1 . 1 1 . . . . . .
[3,] . 1 . 1 1 . . . . .
[4,] 1 1 1 . 1 . . . . .
[5,] . . 1 1 . . . . . .
[6,] . . . . . . 1 1 . 1
[7,] . . . . . 1 . 1 1 1
[8,] . . . . . 1 1 . 1 .
[9,] . . . . . . 1 1 . 1
[10,] . . . . . 1 1 . 1 .
But the resulting igraph object produced by my sample_sbm
call doesn't include group membership as a vertex attribute.
> g
IGRAPH 8750fb0 U--- 10 15 -- Stochastic block-model
+ attr: name (g/c), loops (g/l)
+ edges from 8750fb0:
[1] 1-- 2 2-- 3 1-- 4 2-- 4 3-- 4 3-- 5 4-- 5 6-- 7 6-- 8 7-- 8 7-- 9 8-- 9 6--10 7--10 9--10
How can I add this info for plotting and analysis?
Upvotes: 0
Views: 932
Reputation: 3739
If your sampled graph contains two distinct components with no shared edges (as in the example you provide), then you can use components()$membership
to get group membership and assign it to a node attribute:
library(igraph)
set.seed(1234)
pr_mat <- cbind(c(0.5,0.001), c(0.001, 0.5))
g <- sample_sbm(10, pref.matrix = pr_mat, block.sizes = c(5,5),
directed = FALSE, loops = FALSE)
V(g)$group <- components(g)$membership
plot(g, vertex.color = V(g)$group)
This only works because the preference matrix you provide creates two distinct components. If there are edges between the blocks then obviously there is only one component in the graph. In that case, you can use one of the cluster_*()
functions:
set.seed(1234)
pr_mat <- cbind(c(0.5,0.1), c(0.1, 0.5))
g <- sample_sbm(10, pref.matrix = pr_mat, block.sizes = c(5,5),
directed = FALSE, loops = FALSE)
V(g)$group <- cluster_louvain(g)$membership
plot(g, vertex.color = V(g)$group)
Created on 2020-04-14 by the reprex package (v0.3.0)
Upvotes: 1