我的最终目标是建立一个无方向的边缘列表:
每个由3个组件组成的网络,全连接,一个带1个节点,一个有2个节点,另一个有3个节点:
将有6个节点,但由于第一个组件仅由1个节点组成,因此node1没有边。
tibble(from = c(2,4,4,5),
to = (3,5,6,6)
)
但是组件的数量可能会高于3,比如说30。将在rpois(30,1)+1
之后裁定组件内的边缘的平均数量。
在tidygraph
中,创建完整图的函数是create_complete
,理论上我可以继续生成完整图并绑定它们的边缘列表。但在这种情况下,我将遇到命名边的问题,并且我可能会错过未连接的节点。
更新
如果你想显示集群标签,你可以使用membership
+components
来添加这个属性,就像下面的一样
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)
它给出
# 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
您可以使用disjoint.union
+make_full_graph
,如下所示(假设您有3个完全连接的组件,分别具有1,2和3个节点(
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)
这会给你
# 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
关于rpois(30,1)+1
的使用,如果用rpois(30,1)+1
替换1:3
,例如,这可能会有所帮助
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)
并且生成具有以下信息的图形
# 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