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 by two columns (say 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 decreasing order) and have the following code:
DT[order(-x)] #Error in -x : invalid argument to unary operator
Therefore, I think this error is due to the fact that class(DT$x)=character
. Could you give me any suggestion in order to solve this issue?
I know I can use DT[order(x,decreasing=TRUE)]
, but I want to know the syntax to sort by several columns using both ways (some decreasing, some increasing) at the same time.
Note that if you use DT[order(-y,v)]
the result is ok, but if you use DT[order(-x,v)]
there is an error. So, my question is: how to solve this error?