r - 如何将邻接矩阵保存为 CSV 文件?

标签 r csv igraph

我用一个 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

关于r - 如何将邻接矩阵保存为 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31816180/

相关文章:

r - 在函数中修改后,第一次调用时不显示 data.table

R:双枢轴使用 DPLYR?

r - 在 `googleAuthR` 中使用来自 `googlesheets` 的 token

python - 将 html 写入 csv 时出现奇怪的格式

r - 如何使用R从具有多列的数据框中计算(共)发生矩阵?

r - 调整 ggsurvplot 中 x 轴刻度线的频率

javascript - 使用 FileReader 加载 CSV 以制作 map 标记的 JS 对象( map API)

python - pandas read_csv 列 dtype 设置为十进制但转换为字符串

r - 使用 ggtree 绘制 igraph 树对象

python - pagerank Networkx 与 iGraph 的结果不一致