Keep rownames when converting matrix to data frame

user42485 picture user42485 · Feb 5, 2018 · Viewed 10.2k times · Source

I want to convert a matrix to a data frame. When I use

df <- mat %>% data.frame()

I lose the rownames. How do I keep them?

Answer

Robot-Scott picture Robot-Scott · Apr 30, 2019

This is how I like to do it:

myDF <- data.frame(columnNameILike = row.names(myMatrix), myMatrix)

It just has the slight advantage that you can name the row.names what you like.

Example:

mat = matrix(c(1,2,3,2,3,4))
row.names(mat) = c("one","two","three","frour","frive","six")
df = data.frame(columnNameILike = row.names(mat), mat)