Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an adjacency matrix as a CSV file?

Tags:

r

csv

igraph

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

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 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 . . .    .  

How can I export this adjacency matrix to a CSV file? I've been trying write.table to 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
like image 827
ktm5124 Avatar asked Aug 04 '15 18:08

ktm5124


1 Answers

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' looks like this when opened in a text editor:

0 1 0 0 2
0 0 2 0 1
2 0 1 0 0
like image 64
bjoseph Avatar answered Nov 13 '22 08:11

bjoseph