Using the order initialisation parameter, you can set the table to display the data in exactly the order that you want. The order parameter is an array of arrays where the first value of the inner array is the column to order on, and the second is 'asc' (ascending ordering) or 'desc' (descending ordering) as required.
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.
You can use DT[order(-rank(x), y)]
.
x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6
You can only use -
on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:
DT[order(x,-v,decreasing=TRUE),]
x y v
[1,] c 1 7
[2,] c 3 8
[3,] c 6 9
[4,] b 1 1
[5,] b 3 2
[6,] b 6 3
[7,] a 1 4
[8,] a 3 5
[9,] a 6 6
DT[order(-x)]
works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x)
syntax in keeping with the set* commands like setnames
, setkey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With