Graph.union summing edge weights attributes (igraph R) -


i have 2 graphs, weight labels:

library(igraph)  g1= graph.formula(a -+ b, -+ c) e(g1)["a" %->% "b"]$weight= 1 e(g1)["a" %->% "c"]$weight= 2 e(g1)$label= e(g1)$weight  g2= graph.formula(a -+ b, -+ c, -+ 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 joining both graph.union(), igraph default creates weight_1, weight_2 attributes.

problem:

i want joined graph have edge weight attributes summed up. applying existing so answer not optimal. first solution not scale in case graph.union() creates many more weight_... attributes. second leads in case of reproducible example partial solution, 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 recode following graph:

enter image description here

comment: not looking manual solution (e(g)["a" %->% "d"]$label= 100), handling lots of edges.

based on gabor's advise:

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


Comments