Home > OS >  Converting dgCMatrix to data frame and getting error in R
Converting dgCMatrix to data frame and getting error in R

Time:12-04

I am trying to convert a matrix to a data frame using as.data.frame() and I am getting an error:

Error in as.data.frame.default(coef) : 
  cannot coerce class ‘structure("dgCMatrix", package = "Matrix")’ to a data.frame

Is there a simple solution to this?

Matrix class:

class(coef)
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"

CodePudding user response:

First convert to regular matrix and then use as.data.frame

library(Matrix)
as.data.frame.matrix(Matrix(0, 3, 2))

-output

  V1 V2
1  0  0
2  0  0
3  0  0

Instead of

> as.data.frame(Matrix(0, 3, 2))
Error in as.data.frame.default(Matrix(0, 3, 2)) : 
  cannot coerce class ‘structure("dgCMatrix", package = "Matrix")’ to a data.frame
  • Related