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)
When joining both with graph.union()
, igraph
by default creates weight_1, weight_2
attributes.
Problem:
I want the joined graph to have edge weight attributes summed up. Applying existing SO answer is not optimal.
First the solution does not scale well in case graph.union()
creates many more weight_...
attributes. Second it leads in case of the reproducible example only to a partial solution, as 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
Question:
How can I recode to get finally following graph:
Comment: I am not looking for a manual solution (E(g)["A" %->% "D"]$label= 100
), as I am 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With