如何将邻接矩阵另存为CSV文件? [英] How to save an adjacency matrix as a CSV file?

查看:361
本文介绍了如何将邻接矩阵另存为CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created an adjacency matrix in R out of a CSV file that looks like this:

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

上面的方法工作正常,这是邻接矩阵.

The above worked fine, and here's the adjacency matrix.

> 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无济于事.

How can I export this adjacency matrix to a CSV file? I've been trying write.table to no avail.

例如:

> 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库具有可以实现此目的的功能.

The MASS library has a function that can achieve this.

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

First I set up some example data:

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

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

Next, I load the library and write the file:

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

在文本编辑器中打开

'asdf.txt'如下所示:

'asdf.txt' looks like this when opened in a text editor:

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

这篇关于如何将邻接矩阵另存为CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆