繁体   English   中英

如何将邻接矩阵另存为CSV文件?

[英]How to save an adjacency matrix as a CSV file?

我从CSV文件中在R中创建了一个邻接矩阵,如下所示:

Gene1   Gene2   Weight 
A       B       1
A       C       0.5
B       D       -0.5
A       D       -1

这是我的R代码:

el=read.csv("~/my.csv", sep="\t")
library(igraph)
g = graph.data.frame(el)
adj = as_adj(g, attr='Weight')

上面的工作正常,这是邻接矩阵。

> adj
4 x 4 sparse Matrix of class "dgCMatrix"
  A B   C    D
A . 1 0.5 -1.0
B . . .   -0.5
C . . .    .  
D . . .    .  

如何将该邻接矩阵导出到CSV文件? 我一直在尝试write.table无济于事。

例如:

> write.table(adj, file="~/matrix.txt", row.names=FALSE, col.names=FALSE)
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class "structure("dgCMatrix", package = "Matrix")" to a data.frame

MASS库具有可以实现此目的的功能。

首先,我设置一些示例数据:

library(Matrix)
m <- Matrix(c(0,0,2:0), 3,5)
print(m)
3 x 5 sparse Matrix of class "dgCMatrix"


[1,] . 1 . . 2
[2,] . . 2 . 1
[3,] 2 . 1 . .
str(m)
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:6] 2 0 1 2 0 1
  ..@ p       : int [1:6] 0 1 2 4 4 6
  ..@ Dim     : int [1:2] 3 5
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:6] 2 1 2 1 2 1
  ..@ factors : list()

接下来,我加载库并编写文件:

library(MASS)
write.matrix(m,file="asdf.txt")

在文本编辑器中打开时,“ asdf.txt”如下所示:

0 1 0 0 2
0 0 2 0 1
2 0 1 0 0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM