Could we use data.table setorder by group?

Viewed 164

Simple question :

I want to use data.table::setorder on my DT, but I can not do this by group. Is it possible ?

In this example, I order my whole DT :

DT = data.table(a=rep(c('C', 'A', 'D', 'B', 'E'), each = 4), b=sample(1:1000,20))
setorder(DT, b)
DT

But I want to keep a fixed.

Thanks !

2 Answers

Do you mean something like below?

> DT[, .SD[order(b)], a]
    a   b
 1: C 129
 2: C 679
 3: C 836
 4: C 930
 5: A 270
 6: A 299
 7: A 471
 8: A 509
 9: D 187
10: D 307
11: D 597
12: D 978
13: B 277
14: B 494
15: B 874
16: B 950
17: E 330
18: E 591
19: E 775
20: E 841

> DT[, setorder(.SD, b), a]
    a   b
 1: C 129
 2: C 679
 3: C 836
 4: C 930
 5: A 270
 6: A 299
 7: A 471
 8: A 509
 9: D 187
10: D 307
11: D 597
12: D 978
13: B 277
14: B 494
15: B 874
16: B 950
17: E 330
18: E 591
19: E 775
20: E 841

Here is another option:

DT[order(rleid(a), b)]
Related