假设我在 R 中给出了一个 igraph 图并想要反转所有边:
library(igraph)
library(tidyverse)
g <- make_star(n=6)
plot(g)
gt <- transposeGraph(g) # hypothetical function
plot(gt)
一种方法似乎是重建图,但我担心顶点属性的性能和损失:
gt <- graph_from_data_frame(as_data_frame(g) %>% select(to, from))
还有其他想法吗?
最佳答案
可以找到可能的答案here ,但是它不保留顶点属性。
应该可以使用 get.vertex.attribute
和 set.vertex.attribute
尝试:
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)
由 reprex package 创建于 2020-09-10 (v0.3.0)
性能比较表明它在 100 个顶点的星上快了大约 10 倍:
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
关于r - 在 igraph(R 包)中反转有向图(转置图)中的边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63826748/