Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem with write.csv() and as.data.frame()

I’m trying to save my matrix to a file, but a get an error:
“Error in command 'as.data.frame.default(A)': cannot convert class 'structure("dsCMatrix", package = "Matrix")' to class "data.frame"”

I know I cannot use the matrix in write.csv() function but I have a problem converting the matrix into a data frame. Can anyone give me some tips

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You get an error because you’re trying to directly convert a sparse matrix into a data frame. You can convert a sparse matrix into a full matrix, and then use as.data.frame() to convert it into a data frame. Then you can save the data frame to a file using the write.csv() command.
But be careful with using as.matrix() as it may consume more memory.

object_df <- as.data.frame(as.matrix(object))
write.csv(object_df, "path/to/save/object.csv")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading