8

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?

starball
  • 20,030
  • 7
  • 43
  • 238
user42485
  • 751
  • 2
  • 9
  • 19
  • 4
    Try `mat %>% as.data.frame %>% cbind(rn = row.names(mat), .)` BTW, `data.frame` keeps the row names as such. If you use `data_frame`, it would strip off those. – akrun Feb 05 '18 at 15:14
  • 3
    I can't reproduce the issue: `mat <- matrix(1:10, nrow = 2, dimnames = list(letters[1:2], letters[1:5])); data.frame(mat)` works fine for me – Russ Hyde Feb 05 '18 at 15:15
  • 1
    @akrun - won't the cbind convert it all back to a matrix again? I think that all that is needed is `as.data.frame(mat)` – dww Feb 05 '18 at 15:18
  • 1
    @dww It wont' because the `cbind` is doing the cbind of data.frame with row names and here it disptaches `cbind.data.frame` I suggested it in case the OP is performing such operations using tidyverse then the row names will get lost in the process – akrun Feb 05 '18 at 15:19
  • @akrun Thanks, as.data.frame() seems to work. What is the difference between using data.frame() and as.data.frame? – user42485 Feb 05 '18 at 15:34
  • 1
    @user42485 You can check the difference here `as.data.frame(mat, ind = 5)` and `data.frame(mat, ind = 5)` the former doesn't create a new column – akrun Feb 05 '18 at 15:38
  • @RussHyde, this might depend on R version – JelenaČuklina Feb 20 '19 at 14:41
  • 1
    Then could OP post the R version they are using, please – Russ Hyde Feb 21 '19 at 10:34
  • works with R 3.5.2/`dplyr` v 0.8.0.1. Voting to close as unclear until version numbers get posted (possibly by someone else who can replicate the problem). – Ben Bolker Apr 30 '19 at 12:34
  • can't replicate the problem in base R. – s_baldur Apr 30 '19 at 12:46

1 Answers1

4

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)
  • 1
    `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. – otayeby Aug 07 '19 at 02:37