You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:15:12