如何重新排列data.table的列?

16

如何对 data.table 中的列进行排列?我可以对 data.frame 进行排列,但是 data.table 覆盖了该方法:

> df <- data.frame(a=1:3,b=4:6)
> df
  a b
1 1 4
2 2 5
3 3 6
> df[c("b","a")]
  b a
1 4 1
2 5 2
3 6 3
> dt <- as.data.table(df)
> dt
   a b
1: 1 4
2: 2 5
3: 3 6
> dt[c("b","a")]
Error in `[.data.table`(dt, c("b", "a")) : 
  When i is a data.table (or character vector), x must be keyed (i.e. sorted, and, marked as sorted) so data.table knows which columns to join to and take advantage of x being sorted. Call setkey(x,...) first, see ?setkey.
Calls: [ -> [.data.table

请注意,这并不是如何在R中重新排序列?重复。


2
下面的答案提供了解决方案。FAQ 2.1.7描述了data.tabledata.frame之间的差异。 - mnel
2个回答

28

使用setcolorder函数:

> library(data.table)
> dt <- data.table(a=1:3,b=4:6)
> setcolorder(dt, c("b", "a"))
> dt
   b a
1: 4 1
2: 5 2
3: 6 3

3
这是在 data.table 中执行的方法(无需修改原始表):
dt[, list(b, a)]

或者

dt[, c("b", "a")]

或者

dt[, c(2, 1)]

4
将数据表dt中列'b'和'a'的顺序交换,并返回新的数据表副本。 - mnel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接