如何在 R igraph 中连接方向子图
how to connect directional sub-graphs in R igraph
我有一个方向加权图,由两个 或更多 个断开的子图组成(除了 weight
之外还有一些属性):
require(igraph)
df<-data.frame(from=c(1,2,4,5),to=c(2,3,5,6),weight=c(1,1,1,1),attr=c(0.1,0.1,0.1,0.1))
g<-graph_from_data_frame(df,directed=T)
我的最终目标是找到最短路径,但这只能针对连通图来完成。
因此,我需要将这两个子图连接起来,边在 3 和 4 之间,权重较大(可能 vcount(g)
),所以最后我只有一个图。通常,顶点名称是定义方向(从小到大)的日期。可以存在多个间隙。
对于你的情况,你可以这样做:
(感谢
的评论
h <- add.edges(g, c("3","4"), weight = vcount(g))
如果你有一个以上的差距(即两个以上的集群),你可以尝试下面的代码
e <- c(sapply(decompose(g),function(x) names(V(x))[degree(x)==1]))
G <- g %>%
add.edges(e[2:(length(e)-1)],weight = vcount(g))
这样
> get.data.frame(G)
from to weight attr
1 1 2 1 0.1
2 2 3 1 0.1
3 4 5 1 0.1
4 5 6 1 0.1
5 7 8 1 0.1
6 8 9 1 0.1
7 3 4 9 NA
8 6 7 9 NA
数据
df <-
data.frame(
from = c(1, 2, 4, 5, 7, 8),
to = c(2, 3, 5, 6, 8, 9),
weight = c(1, 1, 1, 1, 1, 1),
attr = c(0.1, 0.1, 0.1, 0.1, 0.1, 0.1)
)
我有一个方向加权图,由两个 或更多 个断开的子图组成(除了 weight
之外还有一些属性):
require(igraph)
df<-data.frame(from=c(1,2,4,5),to=c(2,3,5,6),weight=c(1,1,1,1),attr=c(0.1,0.1,0.1,0.1))
g<-graph_from_data_frame(df,directed=T)
我的最终目标是找到最短路径,但这只能针对连通图来完成。
因此,我需要将这两个子图连接起来,边在 3 和 4 之间,权重较大(可能 vcount(g)
),所以最后我只有一个图。通常,顶点名称是定义方向(从小到大)的日期。可以存在多个间隙。
对于你的情况,你可以这样做:
(感谢
h <- add.edges(g, c("3","4"), weight = vcount(g))
如果你有一个以上的差距(即两个以上的集群),你可以尝试下面的代码
e <- c(sapply(decompose(g),function(x) names(V(x))[degree(x)==1]))
G <- g %>%
add.edges(e[2:(length(e)-1)],weight = vcount(g))
这样
> get.data.frame(G)
from to weight attr
1 1 2 1 0.1
2 2 3 1 0.1
3 4 5 1 0.1
4 5 6 1 0.1
5 7 8 1 0.1
6 8 9 1 0.1
7 3 4 9 NA
8 6 7 9 NA
数据
df <-
data.frame(
from = c(1, 2, 4, 5, 7, 8),
to = c(2, 3, 5, 6, 8, 9),
weight = c(1, 1, 1, 1, 1, 1),
attr = c(0.1, 0.1, 0.1, 0.1, 0.1, 0.1)
)