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

房东的猫 提交于 2019-12-09 00:49:19

问题


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 would like to do the following actions using pipes:

rownames(mtcars) <- as.character(1:nrow(mtcars))

so that it looks like:

library(magrittr)
mtcars <-
    mtcars %>%
    ...???

Note that @akrun's answer shows that if the pipe is used in conjection with a function that coerces the data frame into a tbl_df, the row names will be lost.


回答1:


You can use row.names<-:

mtcars <- mtcars %>% `row.names<-`(as.character(1:nrow(mtcars)))

Should work. As a demo:

df <- data.frame(x = 1:5, y = 2:6)
df <- df %>% `row.names<-`(letters[1:5])
df

#   x y
# a 1 2
# b 2 3
# c 3 4
# d 4 5
# e 5 6



回答2:


Other possibility is to use set_rownames alias from magrittr library.

mtcars <- 
  mtcars %>%
  set_rownames(as.character(1:nrow(mtcars)))



回答3:


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
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#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.




回答4:


To actually "do the opposite of: Convert row names into first column" as stated at the top, i.e. turn a column of data into the row names, you'll want tibble::column_to_rownames(), which fits into pipes nicely. (I know your example specified something else, i.e. turning a sequence of numbers into the row names, for which you should use the other answers)

library(tidyverse)
starwars %>% column_to_rownames("name") %>% head()
#>                height mass  hair_color  skin_color eye_color birth_year
#> Luke Skywalker    172   77       blond        fair      blue       19.0
#> C-3PO             167   75        <NA>        gold    yellow      112.0
#> R2-D2              96   32        <NA> white, blue       red       33.0
#> Darth Vader       202  136        none       white    yellow       41.9
#> Leia Organa       150   49       brown       light     brown       19.0
#> Owen Lars         178  120 brown, grey       light      blue       52.0
#>                gender homeworld species
#> Luke Skywalker   male  Tatooine   Human
#> C-3PO            <NA>  Tatooine   Droid
#> R2-D2            <NA>     Naboo   Droid
#> Darth Vader      male  Tatooine   Human
#> Leia Organa    female  Alderaan   Human
#> Owen Lars        male  Tatooine   Human
#>                                                                                                                                                    films
#> Luke Skywalker                                           Revenge of the Sith, Return of the Jedi, The Empire Strikes Back, A New Hope, The Force Awakens
#> C-3PO                             Attack of the Clones, The Phantom Menace, Revenge of the Sith, Return of the Jedi, The Empire Strikes Back, A New Hope
#> R2-D2          Attack of the Clones, The Phantom Menace, Revenge of the Sith, Return of the Jedi, The Empire Strikes Back, A New Hope, The Force Awakens
#> Darth Vader                                                                 Revenge of the Sith, Return of the Jedi, The Empire Strikes Back, A New Hope
#> Leia Organa                                              Revenge of the Sith, Return of the Jedi, The Empire Strikes Back, A New Hope, The Force Awakens
#> Owen Lars                                                                                          Attack of the Clones, Revenge of the Sith, A New Hope
#>                                          vehicles                starships
#> Luke Skywalker Snowspeeder, Imperial Speeder Bike X-wing, Imperial shuttle
#> C-3PO                                                                     
#> R2-D2                                                                     
#> Darth Vader                                                TIE Advanced x1
#> Leia Organa                 Imperial Speeder Bike                         
#> Owen Lars

Created on 2019-03-18 by the reprex package (v0.2.1)



来源:https://stackoverflow.com/questions/38136662/how-to-add-a-row-names-to-a-data-frame-in-a-magrittr-chain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!