如何用dplyr的slice_max按组保留指定数量的Top行?
解决dplyr按组动态保留指定行数的slice_max报错问题
之前用top_n函数可实现按exam_number分组,根据keep列指定的数量保留每组total_score最高的行(比如组"19-7415"保留前5行,组"21-320"保留前6行),但top_n已被弃用,改用官方推荐的slice_max时执行以下代码报错:
data %>% group_by(exam_number) %>% slice_max(order_by = total_score, n = keep)
错误提示:n must be a round number, not a function。
正确实现方法
因为每组内的keep值是统一的(同一分组的保留行数相同),需明确提取每组的keep值作为参数,以下两种方法均可实现需求:
方法1:优化slice_max调用
data %>% group_by(exam_number) %>% slice_max(order_by = total_score, n = first(keep))
用first(keep)获取当前分组的保留行数,确保n为单一数值,符合slice_max的参数要求。
方法2:用row_number()筛选
data %>% group_by(exam_number) %>% arrange(desc(total_score)) %>% slice(1:first(keep))
先按total_score降序排列,再截取每组前first(keep)行,逻辑更直观。
内容的提问来源于stack exchange,提问作者Jeff Henderson
相关产品推荐
相关产品推荐

