如何重新排序data.table列?

时间:2013-04-21 16:52:36

标签: r data.table

如何在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

请注意,这不是 How does one reorder columns in R?的伪装。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

这是你在data.table中的方式(不修改原始表格):

dt[, list(b, a)]

dt[, c("b", "a"), with = F]

dt[, c(2, 1), with = F]