16

How do I permute columns in a data.table? I can do that for a data.frame, but data.table overrides the method:

> 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

Note that this is not a dupe for How does one reorder columns in R?.

Community
  • 1
  • 1
sds
  • 58,617
  • 29
  • 161
  • 278
  • 2
    The answers below provide the solution. [FAQ 2.1.7](http://datatable.r-forge.r-project.org/datatable-faq.pdf) describes this difference between `data.table` and `data.frame` – mnel Apr 21 '13 at 23:24

2 Answers2

28

Use 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
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
3

This is how you do it in data.table (without modifying original table):

dt[, list(b, a)]

or

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

or

dt[, c(2, 1)]
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
eddi
  • 49,088
  • 6
  • 104
  • 155