3

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
smci
  • 32,567
  • 20
  • 113
  • 146
Vasily A
  • 8,256
  • 10
  • 42
  • 76
  • 2
    Maybe `setkeyv(dt, rev(key(dt)))`? – nrussell Oct 10 '16 at 18:39
  • I meant order of the records, not columns (it can be just one column). – Vasily A Oct 10 '16 at 18:43
  • 2
    Do you mean set the keys with descending sort? – nrussell Oct 10 '16 at 18:47
  • yes! I will add an example to make it more clear – Vasily A Oct 10 '16 at 18:47
  • LGTM. What problems are you encountering with the current approach? Probably just remove the semi-colons. – nrussell Oct 10 '16 at 18:49
  • Your way seems fine to me. – Frank Oct 10 '16 at 18:49
  • I didn't really encounter any problems, was just wondering if there is any shorter/nicer way. Thank you for confirming! – Vasily A Oct 10 '16 at 18:52
  • 3
    Oh, by the way, the end result does *not* have a key (though I guess you know this) -- it breaks when you reorder. Keys are only supported when data is in ascending order in memory, is my understanding. – Frank Oct 10 '16 at 18:55
  • ouch, I did not notice that, thank you for pointing out! If I understand correctly, there is no solution for this particular issue except creating new key column. – Vasily A Oct 10 '16 at 19:00
  • Yeah. These days, I only use keys for more convenient syntax (so I can skip writing `on=` during joins with tables where the key can easily be guessed, like my "eventDT" will be keyed by "event_id"). You might want to read the latest version of the answer here: http://stackoverflow.com/a/20057411/ – Frank Oct 10 '16 at 19:05
  • ok, got it! Very useful reading. – Vasily A Oct 10 '16 at 19:11

1 Answers1

1

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)


Skye
  • 13
  • 5