I have a directional weighted graph that is made of two or more disconnected sub-graphs (with some attributes, in addition to 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)
My ultimate goal is to find shortest path, but this can be done only for connected graphs.
As a result, I need to connect these two sub-graphs with an edge between 3 and 4 with the large weight (perhaps vcount(g)
) so at the end I have just one graph. In general, vertex names are dates that define direction (from smaller to larger). More than one gap can be present.
You can try the code below if you have more than one gap (i.e., more than two clusters)
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))
such that
> 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
Data
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)
)