1

I have a directed graph where agents move from node1 to node2 like the following

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

I would like to change this directed graph into an undirected one, summing the flow between edges, rendering a result such as

node1 node2 flow
A B 18
C A 1
D B 3
A E 14
B E 3

I tried creating individual ids base on the edges, but without success.

Any thoughts on how to do it?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Felipe Alvarenga
  • 2,572
  • 1
  • 17
  • 36

1 Answers1

3

You can use the igraph function as.undirected with the argument edge.attr.comb set to sum. First generate your directed graph:

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)

And then collapse the directed edges to undirected edges, summing the edge weights (in your case, flow):

undirected_graph <- as.undirected(directed_graph,
                                  mode = "collapse", edge.attr.comb = "sum")

The result:

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
George Wood
  • 1,914
  • 17
  • 18