Maintain rownames when filter a data frame with %>%

时间:2017-07-12 08:04:41

标签: r dplyr

Look two codes below, myup1 maintain row names, myup2 does not.

myup1<-outdf2[outdf2$label == "Up-Regulated", ]
myup2<-outdf2 %>%filter(label == "Up-Regulated" )

Is there a way to report rownames with %>% approach?

1 个答案:

答案 0 :(得分:4)

要使用示例扩展我的评论,我们可以使用add_rownames但不推荐使用,因此请改用tibble::rownames_to_column()

library(dplyr)
library(tibble)

df1 <- mtcars[1:5, 1:3]
df1
#                    mpg cyl disp
# Mazda RX4         21.0   6  160
# Mazda RX4 Wag     21.0   6  160
# Datsun 710        22.8   4  108
# Hornet 4 Drive    21.4   6  258
# Hornet Sportabout 18.7   8  3

df1[ df1$cyl == 6, ]
#                 mpg cyl disp
# Mazda RX4      21.0   6  160
# Mazda RX4 Wag  21.0   6  160
# Hornet 4 Drive 21.4   6  258

df1 %>%
  rownames_to_column("myCars") %>% 
  filter(cyl == 6)
# # A tibble: 3 x 4
#           myCars   mpg   cyl  disp
#            <chr> <dbl> <dbl> <dbl>
# 1      Mazda RX4  21.0     6   160
# 2  Mazda RX4 Wag  21.0     6   160
# 3 Hornet 4 Drive  21.4     6   258