Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert edges in a directed graph (transpose graph) in igraph (R packages)

suppose I have given an igraph graph in R and want to invert all edges:

Transpose_graph

see Transpose graph

library(igraph)
library(tidyverse)
g <- make_star(n=6)
plot(g)
gt <- transposeGraph(g) # hypothetical function
plot(gt)

One way seems to be to rebuild the graph, but I am concerned about the performance and the loss of vertex attributes:

gt <- graph_from_data_frame(as_data_frame(g) %>% select(to, from))

Any other ideas?

like image 450
c0bra Avatar asked Oct 28 '25 21:10

c0bra


1 Answers

A possible answer can be found here, however it doesn't keep the vertices attributes.
It should be possible to restore attributes using get.vertex.attribute and set.vertex.attribute

Try:

library(igraph)
library(tidyverse)

g <- make_star(n=6)
plot(g)

transposeGraph <- function(g) {
  g %>% get.edgelist %>%
    {cbind(.[, 2], .[, 1])} %>%
    graph.edgelist
}

gt <- transposeGraph(g)
plot(gt)

Created on 2020-09-10 by the reprex package (v0.3.0)

Performance comparison shows that it's about 10x faster on a 100 vertices star:

Unit: microseconds
                                                         expr      min        lq     mean   median
 graph_from_data_frame(as_data_frame(g) %>% select(to, from)) 4300.308 4495.1795 4844.328 4654.769
                                            transposeGraph(g)  315.487  350.5645  457.711  404.308
       uq       max neval cld
 4806.770 13324.719   100   b
  437.539  4488.205   100  a 

like image 85
Waldi Avatar answered Oct 31 '25 12:10

Waldi