如何解决反转igraphR包中的有向图转置图中的边
假设我在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创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。