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

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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With