Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

magrittr

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.

like image 994
Alex Avatar asked Jul 01 '16 03:07

Alex


1 Answers

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
like image 179
Psidom Avatar answered Sep 29 '22 15:09

Psidom