2017-07-12 33 views
2

所以我用all_shortest_paths得到一个输出,它看起来像这样:翻动igraph.vs到数据帧

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)) 

但是当我审视使用

class(PathsEF) 

它说,这是一个列表中的数据strture我得到这个错误

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

。但是当我使用

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来说很新!

+0

你想干什么你的数据帧的样子:

您也可以使用这个脚本保存在一个.csv格式? – paqmo

+0

请参阅我的编辑! –

回答

1

首先,阐明几点。由all_shortest_paths创建的对象是一个包含两个元素的列表:1)res和2)nrgeores对象也是一个列表 - 但是一个igraph.vs对象的列表。 igraph.vs对象是一个被称为顶点序列的特定对象。 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))) 
+0

非常感谢!这工作(并澄清了很多!) –

0

其实,这很简单:

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

注意在“做什么”的选项中进行选择。

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