Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse order for data.table `setkey()`

What is the optimal way to setkey the data.table with reversed order of the records? So far I use the combination of setkey() and setorder():

setkeyrev <- function(inputDT,...){
  setkey(inputDT, ...)
  setorderv(inputDT, key(inputDT), order = -1)
  invisible(inputDT)
}

Is there a better solution?

UPD. here is an example:

myDT <- fread('
colA colB
1 b1
3 b3
8 b8
5 b5')

setkey(myDT, colA)
myDT

setkeyrev(myDT, colA)
myDT
like image 480
Vasily A Avatar asked Feb 28 '26 08:02

Vasily A


1 Answers

I am 3 years late but this may help someone else. I was looking for a solution to this exact question, but as noted in the comments the the example in the OP doesn't preserve the keys. The comments made me think of a simple solution. Create a new column giving the desired ordering (reverse rank), then use it as the key...

myDT <- fread('
colA colB
1 b1
3 b3
8 b8
5 b5')

myDT[,revorder:=frankv(colA,order=-1,ties.method = "first")]
setkey(myDT,revorder)

If you need reverse ordering within groups (like I did)...

myDT <- fread('
colA grp 
1 a
2 a
3 a
4 b
8 b
5 b')

myDT[,revorder:=frankv(colA,order=-1,ties.method = "first"),by = grp]
setkey(myDT,grp,revorder)


like image 101
Skye Avatar answered Mar 02 '26 13:03

Skye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!