【问题标题】:Turning an igraph.vs into a data frame将 igraph.vs 转换为数据框
【发布时间】:2017-12-17 12:25:39
【问题描述】:

所以我使用 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)

但我收到此错误:

as.data.frame.default(x[[i]], optional = TRUE) 中的错误: 无法将“igraph.vs”类强制转换为 data.frame

我也试过这个:

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

但我收到此错误

get.edgelist(PathsE) 中的错误:不是图形对象

当我检查数据结构时使用

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 很陌生!

【问题讨论】:

  • 你希望你的数据框是什么样子的?
  • 请看我的编辑!

标签: r dataframe igraph


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!这有效(并且澄清了很多!)
【解决方案2】:

其实很简单:

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

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

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

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

【讨论】:

  • 这仅适用于图形对象,不适用于最短路径 igraph.vs 对象的向量
猜你喜欢
  • 2020-04-03
  • 1970-01-01
  • 2020-04-15
  • 2017-12-10
  • 2011-05-16
  • 2022-01-20
  • 2018-02-16
  • 2021-03-25
  • 2018-03-30
相关资源
最近更新 更多