将 igraph.vs 转换为数据框

Turning an igraph.vs into a data frame

所以我使用 all_shortest_paths 来获得输出,如下所示:

PathsE

$res[[1]]
+ 4/990 vertices, named:
[1] Sortilin  GGA1      Ubiquitin PIMT     

$res[[2]]
+ 4/990 vertices, named:
[1] Sortilin TrkA     PLK1     PIMT    

$res[[3]]
+ 4/990 vertices, named:
[1] Sortilin APP      JAB1     PIMT  

我想把它变成一个数据框,以便我可以操作它。 作为参考,我希望数据框看起来像这样:

                  Prot1      Prot2   Prot3   Prot4
         Pathway1 Sortilin   GGA1    PLK1    PIMT
         Pathway2 Sortilin   TrkA    PLK1    PIMT 
         Pathway3 Sortilin   APP     JAB1    PIMT               

*我知道如何更改轴名称
我试过了

PathsDF<-as.data.frame(PathsE)

但是我得到这个错误:

Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ""igraph.vs"" to a data.frame

我也试过这个:

PathDF <- as.data.frame(get.edgelist(PathsE))

但是我得到这个错误

Error in get.edgelist(PathsE) : Not a graph object

当我使用

检查数据结构时
class(PathsEF)

它说这是一个列表。但是当我使用

str(PathsE)

看起来像这样:

..$ :Class 'igraph.vs'  atomic [1:4] 338 204 40 913
.. .. ..- attr(*, "env")=<weakref>
.. .. ..- attr(*, "graph")= chr "717e99fb-b7db-4e35-8fd3-1d8d741e6612" 
etc

这对我来说就像一个矩阵。

根据这些信息,你们中的任何人是否对如何将其转换为数据框有任何想法。如果我遗漏了任何明显的东西,我很抱歉 - 我是 R 的新手!

首先,澄清几点。 all_shortest_paths 创建的对象是一个包含两个元素的列表:1) res 和 2) nrgeores 对象也是一个列表——但是 igraph.vs 对象的列表。 igraph.vs 对象是一个 igraph 特定对象,称为顶点序列。 Base R 函数不知道如何处理它。所以我们使用 as_id 函数将 igraph.vs 对象转换为 id 向量。

由于 PathsE$resigraph.vs 个对象的列表,您需要遍历该列表并将其折叠成一个数据框。有几种方法可以做到这一点。这是一个:

set.seed(6857)
g <- sample_smallworld(1, 100, 5, 0.05) #Building a random graph
sp <- all_shortest_paths(g, 5, 70)
mat <- sapply(sp$res, as_ids) 
#sapply iterates the function as_ids over all elements in the list sp$res and collapses it into a matrix

这会生成一个矩阵,但请注意它是您想要的矩阵的转置:

> mat
     [,1] [,2] [,3] [,4]
[1,]    5    5    5    5
[2,]  100    4  100    1
[3,]   95   65   65   75
[4,]   70   70   70   70

因此,将其转置并转换为数据框:

> df <- as.data.frame(t(mat))
  V1  V2 V3 V4
1  5 100 95 70
2  5   4 65 70
3  5 100 65 70
4  5   1 75 70

我们可以在一行代码中完成:

set.seed(6857)
g <- sample_smallworld(1, 100, 5, 0.05)
sp <- all_shortest_paths(g, 5, 70)
df <- as.dataframe(t(sapply(sp$res, as_ids)))

其实很简单:

data.frame <- get.data.frame(g, what= c("vertices", "edges", "both") )

注意在 "what" 选项中进行选择。

您也可以使用此脚本将其保存为 .csv 格式:

write.csv(data.frame, "data.frame.csv")