Search code examples
rmagrittr

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


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.


Solution

  • 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