我有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
属性。
问题:
我希望连接图有总结边权属性。应用现有的SO answer并非最佳选择。
首先,如果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
),因为我正在处理许多边缘。
答案 0 :(得分:3)
基于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)