Reorder rows in data.table in a specific order
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
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.