如何重新排序 data.table 列(不复制) [英] How to reorder data.table columns (without copying)
本文介绍了如何重新排序 data.table 列(不复制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想重新排序我的 data.table
x
中的列,给定列名的字符向量 neworder
:
I'd like to reorder columns in my data.table
x
, given a character vector of column names, neworder
:
library(data.table)
x <- data.table(a = 1:3, b = 3:1, c = runif(3))
neworder <- c("c", "b", "a")
显然我可以做到:
x[ , neworder, with = FALSE]
# or
x[ , ..neworder]
# c b a
# 1: 0.8476623 3 1
# 2: 0.4787768 2 2
# 3: 0.3570803 1 3
但这需要再次复制整个数据集.有没有其他方法可以做到这一点?
but that would require copying the entire dataset again. Is there another way to do this?
推荐答案
使用setcolorder()
:
library(data.table)
x <- data.table(a = 1:3, b = 3:1, c = runif(3))
x
# a b c
# [1,] 1 3 0.2880365
# [2,] 2 2 0.7785115
# [3,] 3 1 0.3297416
setcolorder(x, c("c", "b", "a"))
x
# c b a
# [1,] 0.2880365 3 1
# [2,] 0.7785115 2 2
# [3,] 0.3297416 1 3
来自?setcolorder
:
用 data.table
的说法,所有 set*
函数都通过引用改变它们的输入.也就是说,除了一列大小的临时工作内存之外,根本不进行任何复制.
In
data.table
parlance, allset*
functions change their input by reference. That is, no copy is made at all, other than temporary working memory, which is as large as one column.
所以应该非常有效.详见?setcolorder
.
so should be pretty efficient. See ?setcolorder
for details.
这篇关于如何重新排序 data.table 列(不复制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文