2013-04-21 137 views
14

如何排列data.table中的列? 我能做到這一點的data.frame,但data.table覆蓋的方法:如何重新排列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

下面的答案提供瞭解決方案。 [FAQ 2.1.7](http://datatable.r-forge.r-project.org/datatable-faq.pdf)描述了'data.table'和'data.frame'之間的區別 – mnel 2013-04-21 23:24:24

回答

25

使用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

這是你如何在data.table做(而不需要修改原始表):

dt[, list(b, a)] 

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

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

或'setcolorder(copy (dt),c('b','a'))' – mnel 2013-04-21 23:55:26