Graph.union 求和边权重属性(igraph R)

Graph.union summing edge weights attributes (igraph R)

我有 2 个图表,带有权重标签:

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)

当与 graph.union() 连接时,igraph 默认创建 weight_1, weight_2 属性。

问题:

我希望连接图的边权重属性相加。应用现有的 并不是最优的。 首先,如果 graph.union() 创建更多 weight_... 属性,则解决方案无法很好地扩展。其次,在可重现示例的情况下,它仅导致部分解决方案,因为边 "A" "D" 不包含总和。

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

问题:

我如何重新编码以获得最终的下图:

评论:我不是在寻找手动解决方案 (E(g)["A" %->% "D"]$label= 100),因为我要处理很多边缘。

根据 Gabor 的建议:

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)