How to add a row names to a data frame in a magrittr chain

前端 未结 4 1071
傲寒
傲寒 2021-01-13 10:49

I want to do the opposite of: Convert row names into first column

Somewhere down the chain of pipes I would like to add row names to the data frame, for example, I w

4条回答
  •  孤城傲影
    2021-01-13 11:14

    The tbl_df changes it to row number. So, we don't need to do any extra effort in changing row names.

    library(dplyr)
    tbl_df(mtcars)
    

    The same applies if we are using data.table

    as.data.table(mtcars)
    

    As the OP commented about changing the names to something other than the sequence of rows, if we use the same assignment showed in the other post

     mtcars %>%
         `row.names<-`(c(letters, LETTERS)[1:32]) %>%
          group_by(gear) %>%
          slice(1)
    #     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
    #            
    #1  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
    #2  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
    #3  26.0     4 120.3    91  4.43 2.140 16.70     0     1     5     2
    

    As we can see, the row names changes to sequence again. So, if we change the row names to something else and do the dplyr chain operations, the previous change is worthless.

提交回复
热议问题