【发布时间】:2021-12-03 20:46:31
【问题描述】:
我无法完全掌握正确的语法。我有一个data.table,我想首先按分组列g1(有序因子)排序,然后按另一列n 降序排列。唯一的问题是,我希望第三列 g2 的标记为“其他”的行出现在每个组的底部,而不管它们的值是 n。
例子:
library(data.table)
dt <- data.table(g1 = factor(rep(c('Australia', 'Mexico', 'Canada'), 3), levels = c('Australia', 'Canada', 'Mexico')),
g2 = rep(c('stuff', 'things', 'other'), each = 3),
n = c(1000, 2000, 3000, 5000, 100, 3500, 10000, 10000, 0))
这是预期的输出,在每个g1 中,我们的降序排列为n,除了g2 == 'other' 始终位于底部的行:
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
【问题讨论】:
标签: r data.table