Update
If you want to show the cluster labels, you can use membership
+ components
to add this attribute like below
set.seed(1)
do.call(
graph.disjoint.union,
lapply(
rpois(30, 1) + 1,
make_full_graph
)
) %>%
set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
set_vertex_attr(name = "cluster_label", value = membership(components(.))) %>%
as_tbl_graph(directed = FALSE)
which gives
# A tbl_graph: 62 nodes and 49 edges
#
# An undirected simple graph with 30 components
#
# Node Data: 62 x 2 (active)
names cluster_label
<int> <dbl>
1 1 1
2 2 2
3 3 2
4 4 3
5 5 3
6 6 4
# ... with 56 more rows
#
# Edge Data: 49 x 2
from to
<int> <int>
1 2 3
2 4 5
3 6 7
# ... with 46 more rows
You can use disjoint.union
+ make_full_graph
like below (assuming you have 3 fully connected components with 1,2, and 3 nodes respectively)
library(tidygraph)
library(igraph)
do.call(
graph.disjoint.union,
lapply(
1:3,
make_full_graph
)
) %>%
set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
as_tbl_graph(directed = FALSE)
which gives you
# A tbl_graph: 6 nodes and 4 edges
#
# An undirected simple graph with 3 components
#
# Node Data: 6 x 1 (active)
names
<int>
1 1
2 2
3 3
4 4
5 5
6 6
#
# Edge Data: 4 x 2
from to
<int> <int>
1 2 3
2 4 5
3 4 6
# ... with 1 more row
Regarding the use of rpois(30,1)+1
, perhaps this could help if you replace 1:3
with rpois(30,1)+1
, e.g.,
set.seed(1)
do.call(
graph.disjoint.union,
lapply(
rpois(30,1)+1,
make_full_graph
)
) %>%
set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
as_tbl_graph(directed = FALSE)
and a graph is generated with the following info
# A tbl_graph: 62 nodes and 49 edges
#
# An undirected simple graph with 30 components
#
# Node Data: 62 x 1 (active)
names
<int>
1 1
2 2
3 3
4 4
5 5
6 6
# ... with 56 more rows
#
# Edge Data: 49 x 2
from to
<int> <int>
1 2 3
2 4 5
3 6 7
# ... with 46 more rows