Keep rownames when converting matrix to data frame
11,924
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)
Author by
user42485
Updated on June 28, 2022Comments
-
user42485 almost 2 years
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?
-
otayeby over 4 years
data.frame(your_matrix)
already preserves the row names, but nice trick if you want to make a special column for the row names in the same line.