Reorder rows in data.table in a specific order

前端 未结 2 907
野趣味
野趣味 2021-02-07 00:05

I have a data.table dumdt:

set.seed(123)
dumdt <- data.table(v1=sample(1:10, 5), v2=1:5)

whose rows I\'d like to r

相关标签:
2条回答
  • 2021-02-07 00:48

    If I understand correctly, you can just add a col and then order by it:

    setorder(dumdt[, .r := order(to_ord)], .r)[, .r := NULL]
    
       v1 v2
    1:  4  3
    2:  6  5
    3:  8  2
    4:  3  1
    5:  7  4
    
    0 讨论(0)
  • 2021-02-07 00:58

    This capability is not (yet) exported. After looking at the source of setorderv I was able to extract required call to C function which does what you need and supply it with custom order.

    library(data.table)
    set.seed(123)
    dumdt <- data.table(v1=sample(1:10, 5), v2=1:5)
    print(dumdt)
    #   v1 v2
    #1:  3  1
    #2:  8  2
    #3:  4  3
    #4:  7  4
    #5:  6  5
    setroworder <- function(x, neworder) {
        .Call(data.table:::Creorder, x, as.integer(neworder), PACKAGE = "data.table")
        invisible(x)
    }
    to_ord <- c(3, 5, 2, 1, 4)
    setroworder(x=dumdt, neworder=to_ord)
    print(dumdt)
    #   v1 v2
    #1:  4  3
    #2:  6  5
    #3:  8  2
    #4:  3  1
    #5:  7  4
    

    Yet the solution proposed by Frank looks a little bit nicer.

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