dplyr - Group by and select TOP x %

后端 未结 5 1859
天命终不由人
天命终不由人 2020-12-01 11:31

Using the package dplyr and the function sample_frac it is possible to sample a percentage from every group. What I need is to first sort the elements in every

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 12:11

    Or another option with dplyr:

    mtcars %>% select(gear, wt) %>% 
      group_by(gear) %>% 
      arrange(gear, desc(wt)) %>% 
      filter(wt > quantile(wt, .8))
    
    Source: local data frame [7 x 2]
    Groups: gear [3]
    
       gear    wt
      (dbl) (dbl)
    1     3 5.424
    2     3 5.345
    3     3 5.250
    4     4 3.440
    5     4 3.440
    6     4 3.190
    7     5 3.570
    

提交回复
热议问题