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

R data.table按组排序时如何将每个分组内g2为other的行置于底部

实现代码

你可以通过新增临时排序逻辑实现需求,利用逻辑值g2 == "other"的排序特性(FALSE对应数值0、TRUE对应数值1,升序排列时非other的行会排在other行前面),一行代码即可完成:

写法1:原位排序(效率更高,适合大数据量场景)

直接修改原data.table的顺序:

library(data.table)
# 排序顺序:先按g1的因子水平排序,再把非other行排前面,最后非other行按n降序
setorder(dt, g1, g2 == "other", -n)

写法2:生成新对象,不修改原数据

sorted_dt <- dt[order(g1, g2 == "other", -n)]

执行后输出结果和你给出的预期完全一致:

g1     g2     n
1: Australia things  5000
2: Australia  stuff  1000
3: Australia  other 10000
4:    Canada things  3500
5:    Canada  stuff  3000
6:    Canada  other     0
7:    Mexico  stuff  2000
8:    Mexico things   100
9:    Mexico  other 10000

内容的提问来源于stack exchange,提问作者qdread

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:39:01