Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph.union summing edge weights attributes (igraph R)

Tags:

r

igraph

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 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

enter image description here

Question:

How can I recode to get finally following graph:

enter image description here

Comment: I am not looking for a manual solution (E(g)["A" %->% "D"]$label= 100), as I am handling lots of edges.

like image 586
user2030503 Avatar asked Sep 28 '22 08:09

user2030503


1 Answers

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

like image 105
user2030503 Avatar answered Sep 30 '22 22:09

user2030503