以特定顺序对data.table中的行进行重新排序 [英] Reorder rows in data.table in a specific order

查看:155
本文介绍了以特定顺序对data.table中的行进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.table dumdt:

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

我想按特定的索引顺序重新排列其行(因此首先是第三个观察值,然后是第五个观察值,然后是第二个,依此类推):

whose rows I'd like to reorder in this specific indices order (so first the third observation, then the fifth, then second, etc.):

to_ord <- c(3, 5, 2, 1, 4)

所以我希望dumdtdumdt[to_ord]的结果,但我也想通过引用来做到这一点,并避免执行dumdt <- dumdt[to_ord].

So I'd like dumdt to be the result of dumdt[to_ord] but I also would like to do it by reference and avoid doing dumdt <- dumdt[to_ord].

我知道我可以通过使用setorder(或setorderv)进行引用来对行进行重新排序,但只能根据一个或多个变量以升序或降序而不是自定义的顺序进行排序. 但是,如果我想按自定义顺序对列而不是行进行重新排序,则可以使用setcolorder.

I know I can reorder rows by reference with setorder (or setorderv) but only according to one or several variables, in ascending or descending order, not in a customised order.
However, if I wanted to reorder the columns, not the rows, in a customised order, I could use setcolorder.

所以我的问题来了:是否有一个功能像setcolorder一样但与行一起工作(或使用setorder进行相同操作的方式)?

So here comes my question : is there a function that would work like setcolorder but with the rows (or a way to use setorder to do the same) ?

我想要的输出将是

setroworder(x=dumdt, neworder=to_ord)
dumdt
   # v1 v2
# 1:  4  3
# 2:  6  5
# 3:  8  2
# 4:  3  1
# 5:  7  4

推荐答案

此功能尚未(尚未)导出.在查看setorderv的源代码之后,我能够提取对C函数的所需调用,该函数将执行您需要的操作并提供自定义顺序.

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

但是Frank提出的解决方案看起来要好一些.

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

这篇关于以特定顺序对data.table中的行进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆