1

我有一个有向图,其中代理从节点 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,但没有成功。

关于如何做的任何想法?

4

1 回答 1

3

您可以使用参数设置为的igraph函数。首先生成您的有向图:as.undirectededge.attr.combsum

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
于 2017-06-28T15:47:10.130 回答