在 igraph(R 包)中反转有向图(转置图)中的边
Invert edges in a directed graph (transpose graph) in igraph (R packages)
假设我在 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 (v0.3.0)
于 2020-09-10 创建
性能比较表明它在 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
我目前运行以下代码,因为它保留了所有节点和边缘属性。
library(igraph)
#>
#> Attache Paket: 'igraph'
#> The following objects are masked from 'package:stats':
#>
#> decompose, spectrum
#> The following object is masked from 'package:base':
#>
#> union
g <- make_star(n=6)
V(g)$name <- LETTERS[1:6]
E(g)$weight <- 1:5
plot(g)
transposeGraph <- function(g){
gDf <- as_data_frame(g, what = "both")
graph_from_data_frame(gDf$edges[,c(2:1, 3:ncol(gDf$edges))], directed = T, gDf$vertices)
}
gt <- transposeGraph(g)
plot(gt)
由 reprex package (v0.3.0)
于 2020-09-28 创建
假设我在 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 (v0.3.0)
于 2020-09-10 创建性能比较表明它在 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
我目前运行以下代码,因为它保留了所有节点和边缘属性。
library(igraph)
#>
#> Attache Paket: 'igraph'
#> The following objects are masked from 'package:stats':
#>
#> decompose, spectrum
#> The following object is masked from 'package:base':
#>
#> union
g <- make_star(n=6)
V(g)$name <- LETTERS[1:6]
E(g)$weight <- 1:5
plot(g)
transposeGraph <- function(g){
gDf <- as_data_frame(g, what = "both")
graph_from_data_frame(gDf$edges[,c(2:1, 3:ncol(gDf$edges))], directed = T, gDf$vertices)
}
gt <- transposeGraph(g)
plot(gt)
由 reprex package (v0.3.0)
于 2020-09-28 创建