Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep rownames when converting matrix to data frame

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?

like image 783
user42485 Avatar asked Feb 05 '18 15:02

user42485


1 Answers

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)
like image 141
Robot-Scott Avatar answered Oct 09 '22 16:10

Robot-Scott