Graph.union summarizes edge weight attributes (igraph R)

I have 2 graphs with weight labels:

library(igraph)

g1= graph.formula(A -+ B, A -+ C)
E(g1)["A" %->% "B"]$weight= 1
E(g1)["A" %->% "C"]$weight= 2
E(g1)$label= E(g1)$weight

g2= graph.formula(A -+ B, A -+ C, A -+ D)
E(g2)["A" %->% "B"]$weight= 10
E(g2)["A" %->% "C"]$weight= 20
E(g2)["A" %->% "D"]$weight= 100
E(g2)$label= E(g2)$weight

par(mfrow= c(2,1), mar= rep(0,4))
plot(g1); plot(g2)

      

enter image description here

When combined with graph.union()

, igraph

creates attributes by default weight_1, weight_2

.

Problem:

I want the merged graph to get edge weight attributes. Applying the existing SO answer is not optimal. At first, the solution doesn't scale well if it graph.union()

creates many more attributes weight_...

. Second, this leads to a reproducible example only to a partial solution, since the edge "A" "D"

contains no sum.

g= graph.union(g1, g2)
E(g)$weight= E(g)$weight_1 + E(g)$weight_2
E(g)$label= E(g)$weight

      

enter image description here

Question:

How can I recode to get the final graph:

enter image description here

Commentary: I am not looking for a manual solution ( E(g)["A" %->% "D"]$label= 100

) as I am handling many edges.

+3


source to share


1 answer


Based on Gabor report:

library(igraph)
library(intergraph)
library(dplyr)

# helper function
as.data.frame.igraph= function(g) {
  # prepare data frame
  res= cbind(as.data.frame(get.edgelist(g)),
             asDF(g)$edges)[ , c(-3, -4)]
  # unfactorize
  res$V1= as.character(res$V1)
  res$V2= as.character(res$V2)
  # return df
  res
}

df_g1= as.data.frame(g1)
df_g2= as.data.frame(g2)
df= rbind_all(list(df_g1, df_g2)) %>%
  group_by(V1, V2) %>%
  summarise(weight= sum(weight))

new_graph= simplify(graph.data.frame(df, directed = T))
E(new_graph)$weight=  df$weight
E(new_graph)$label= E(new_graph)$weight

plot(new_graph)

      



enter image description here

+3


source







All Articles