I have a sparse matrix (dgCMatrix
) as the result of fitting a glmnet
. I want to write this result to a .csv
but can't use write.table()
the matrix because it can't coerced into a data.frame
.
Is there a way to coerce the sparse matrix to either a data.frame
or a regular matrix? Or is there a way to write it to a file while keeping the coefficient names which are probably row names?
That will be dangerous to transform the sparse matrix to a normal one, if the sparse matrix size is too large. In my case (text classification task), I got a matrix of size 22490 by 120,000. If you try get the dense matrix, that will be more than 20 GB, I think. Then R will break down !
So my suggestion, you may simply store the sparse matrix in an efficient and memory friendly way, such as Matrix Market Format, which keeps all non-zero values and their coordinates (row & col number). In the R you can use the method writeMM
as.matrix()
will convert to the full dense representation:
> as.matrix(Matrix(0, 3, 2))
[,1] [,2]
[1,] 0 0
[2,] 0 0
[3,] 0 0
You can write the resulting object out using write.csv
or write.table
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With