I can't quite get the syntax right for this. I have a data.table where I would like to sort first by a grouping column g1 (ordered factor), then in descending order by another column n. The only catch is that I would like rows labeled "other" for a third column g2 to appear at the bottom of each group, regardless of their value of n.
Example:
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))
This is the expected output, where within each g1, we have descending order of n except that rows where g2 == 'other' are always at the bottom:
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