2017-07-12 114 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")