Sorting rows in data.table in descending order by the string key 'order (-x, v)' gives an error in data.table 1.9.4 or earlier.

Let's say I have the following data.table in R :

  library(data.table) DT = data.table(x=rep(c("b","a","c"),each=3), y=c(1,3,6), v=1:9) 

I want to order it in two columns (e.g. columns x and v ). I used this:

  DT[order(x,v)] # sorts first by x then by v (both in ascending order) 

But now I want to sort it by x (in descending order) and have the following code:

  DT[order(-x)] #Error in -x : invalid argument to unary operator 

Therefore, I believe that this error is due to the fact that class(DT$x)=character . Could you give me any suggestion to solve this problem?

I know that I can use DT[order(x,decreasing=TRUE)] , but I want to know the syntax for sorting by several columns, using both methods (some decreasing, some increasing) at the same time.

Please note that if you use DT[order(-y,v)] , the result will be approved, but if you use DT[order(-x,v)] , an error appears. So my question is: how to solve this error?

+107
string sorting r key order data.table
Sep 10 '12 at 14:30
source share
3 answers

Refresh

data.table v1.9 . 6+ now supports the initial OP attempt, and the next answer is no longer needed.




You can use DT[order(-rank(x), y)] .

  xyv 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 
+126
Sep 10
source share

You can use only - for numeric entries, so you can use decrease and cancel those that you want in ascending order:

 DT[order(x,-v,decreasing=TRUE),] xyv [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 
+20
Sep 10 '12 at 15:00
source share

DT[order(-x)] works as expected. I have data.table version 1.9.4. Perhaps this has been fixed in the latest version.
In addition, I suggest setorder(DT, -x) syntax according to set * commands such as setnames , setkey

+13
Aug 19 '15 at 3:44
source share



All Articles