Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

后端 未结 3 1724
悲哀的现实
悲哀的现实 2021-01-29 19:28

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)         


        
相关标签:
3条回答
  • 2021-01-29 20:13

    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
    
    0 讨论(0)
  • 2021-01-29 20:14

    Update

    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
    
    0 讨论(0)
  • 2021-01-29 20:29

    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

    0 讨论(0)
提交回复
热议问题