将有向图转换为无向图并添加权重
Transform directed graph into an undirected graph and adding the weights
我有一个有向图,其中代理从节点 1 移动到节点 2,如下所示
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,但没有成功。
有什么想法吗?
您可以使用 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
我有一个有向图,其中代理从节点 1 移动到节点 2,如下所示
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,但没有成功。
有什么想法吗?
您可以使用 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