dplyr - Group by and select TOP x %

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

    A slight variation using top_n and dplyr:

    mtcars %>% 
     group_by(gear) %>% 
     select(gear, wt) %>% 
     arrange(gear) %>% 
     top_n(seq(n()*.2))
    
      gear    wt
       
    1     3  5.42
    2     3  5.34
    3     3  5.25
    4     4  3.44
    5     4  3.44
    6     5  3.57
    

提交回复
热议问题