将有向图转换为无向图并添加权重

时间:2017-06-27 18:21:44

标签: r igraph directed-graph undirected-graph

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

有关如何做的任何想法?

1 个答案:

答案 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