% "B"]$weight= 1 E(g-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:57:59 25 4
gpt4 key购买 nike

我有 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)

enter image description here

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

enter image description here

问题:

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

enter image description here

评论:我不是在寻找手动解决方案( 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)

enter image description here

关于r - Graph.union 求和边权重属性 (igraph R),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31417071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com