我有一个有向图,其中代理从node1移动到node2,如下所示
node1 node2 flow
A B 12
B A 6
C A 1
D B 3
E A 4
A E 10
E B 1
B E 2
我想将此有向图更改为无向图,将边之间的流量相加,渲染结果如
node1 node2 flow
A B 18
C A 1
D B 3
A E 14
B E 3
我尝试在边缘创建单个ID,但没有成功。
有关如何做的任何想法?
答案 0 :(得分:3)
您可以使用igraph
函数as.undirected
并将参数edge.attr.comb
设置为sum
。首先生成有向图:
library(igraph)
weighted_edgelist <- data.frame(
node1 = c("A", "B", "C", "D", "E", "A", "E", "B"),
node2 = c("B", "A", "A", "B", "A", "E", "B", "E"),
flow = c(12, 6, 1, 3, 4, 10, 1, 2)
)
directed_graph <- graph.data.frame(weighted_edgelist, directed = TRUE)
然后将有向边折叠到无向边,对边权重求和(在您的情况下为流):
undirected_graph <- as.undirected(directed_graph,
mode = "collapse", edge.attr.comb = "sum")
结果:
res <- data.frame(get.edgelist(undirected_graph),
get.edge.attribute(undirected_graph, "flow"))
colnames(res) <- c("node1", "node2", "flow")
res
node1 node2 flow
1 A B 18
2 A C 1
3 B D 3
4 A E 14
5 B E 3