簡體   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