How do I save the adjacency matrix as a CSV file?
I created an adjacency matrix in R from a CSV file that looks like this:
Gene1 Gene2 Weight
A B 1
A C 0.5
B D -0.5
A D -1
Here's my R code:
el=read.csv("~/my.csv", sep="\t")
library(igraph)
g = graph.data.frame(el)
adj = as_adj(g, attr='Weight')
The above works well 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 . . . .
How can I export this adjacency matrix to a CSV file? I have tried to write.table
no avail.
For example:
> 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
+3
source to share
1 answer
The library MASS
has a function that can do this.
I installed some sample data first:
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()
Then I load the library and write the file:
library(MASS)
write.matrix(m,file="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
+8
source to share