如何重新排序data.table列(不复制) [英] How to reorder data.table columns (without copying)

查看:87
本文介绍了如何重新排序data.table列(不复制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重新排序data.table对象中的列, x 给定列名的字符向量, neworder



显然我可以这样做



x < ,neworder,with = FALSE]



,但这将需要再次复制整个数据集。

使用 setcolorder()

  library(data.table)
x< - data.table(a = 1:3,b = 3:1,c = runif(3))
x
#abc
#[1,] 1 3 0.2880365
#[2,] 2 2 0.7785115
# [3,] 3 1 0.3297416
setcolorder(x,c(c,b,a))
x
#cba
#[1,] 0.2880365 3 1
#[2,] 0.7785115 2 2
#[3,] 0.3297416 1 3

帮助页面说明


表通过引用而改变。除了一列大的临时工作记忆外,没有任何副本。


所以应该是相当高效的。有关详细信息,请参阅?setcolorder


I'd like to reorder columns in my data.table object, x given a character vector of column names, neworder.

Obviously I could do this

x <- [,neworder,with=FALSE]

but that would require copying the entire dataset again. Is there another way to do this?

解决方案

Use 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

The help page says

The table is changed by reference. No copy is made at all, other than temporary working memory as large as one column.

so should be pretty efficient. See ?setcolorder for details.

这篇关于如何重新排序data.table列(不复制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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