1

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.

SVS
  • 17
  • 5

2 Answers2

3

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)
  )
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thank you, I just modified one line because the degree is usually not equal to one for my graphs: `e<-c(sapply(decompose(g),function(x) names(V(x))[c(1,length(V(x)))]))` – SVS Apr 17 '21 at 11:15
2

In your case, you could do: (Thanks for the comment by @ThomasIsCoding

h <- add.edges(g, c("3","4"), weight = vcount(g))
Onyambu
  • 67,392
  • 3
  • 24
  • 53