dplyr - Group by and select TOP x %

后端 未结 5 1868
天命终不由人
天命终不由人 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 11:56

    I believe this gets to the answer you're looking for.

    library(dplyr)
    
    mtcars %>% select(gear, wt) %>% 
      group_by(gear) %>% 
      arrange(gear, wt) %>% 
      filter(row_number() / n() <= .2)
    

提交回复
热议问题