Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R how do you write a sparse matrix to a file?

I have a sparse matrix A, generated as an output of glmnet function. When I print the matrix A, it shows all the entries and at the top it reads -

    1897 x 100 sparse Matrix of class "dgCMatrix"
   [[ suppressing 32 column names 's0', 's1', 's2' ... ]]

However, when I try to see the dimensions of the matrix it shows NULL:

> dim(A)
NULL

Thus if I use as.matrix to convert it into a regular matrix and write to a file I get an error:

as.matrix(fit$A[,1])
Error in as.matrix(fit$A[, 1]) : 
  error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Error in fit$A[, 1] : incorrect number of dimensions

How do I fetch the values in this sparse matrix and write to a file?

I encounter this problem when I do multinomial regression (family = "multinomial") in the glmnet function. However this works fine when I am doing binomail regression (family = "binomial").

Also, I have tried with writeMM function. That does not work either:

> library('Matrix')
> writeMM(fit$A,file='test.txt')
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function 'writeMM' for signature '"list"'
like image 811
tan Avatar asked Jul 10 '13 15:07

tan


1 Answers

You can use writeMM and readMM to Read and write sparse matrix, so no need to coerce it to a matrix.

writeMM(fit$A,file='test.txt')
readMM(file='test.txt')

EDIT within multinomial, glmnet returns a list of coefficients. SO you need to loop over this list and write each coefficient. Here an example:

library(glmnet)
g4=sample(1:4,100,replace=TRUE)
fit3=glmnet(x,g4,family="multinomial")
lapply(seq_along(fit3$beta),function(x)
       writeMM(fit3$beta[[x]],file=paste0('coef.beta',x,'.txt')))
like image 168
agstudy Avatar answered Sep 18 '22 09:09

agstudy