Seibar
Seibar

Reputation: 70253

In R, how does one coerce a Matrix to a Data Frame?

I want to convert a simple Matrix to a Data Frame in R.

library(Matrix)

m <- Matrix(c(1:6), 2, 3)
rownames(m) <- c("row a", "row b")
colnames(m) <- c("col a", "col b", "col c")
df <- as.data.frame(m)

This results in an error:

Error in as.data.frame.default(m) : 
  cannot coerce class "structure("dgeMatrix", package = "Matrix")" to a data.frame

Upvotes: 0

Views: 2769

Answers (1)

David Heckmann
David Heckmann

Reputation: 2939

there is a method for as.matrix() so you could do:

as.data.frame(as.matrix(m))

Upvotes: 2

Related Questions