Reorder rows in data.table in a specific order

前端 未结 2 896
野趣味
野趣味 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: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.

提交回复
热议问题