2013-04-21 17 views
14

Jak mogę permutować kolumny w data.table? mogę zrobić dla data.frame, ale data.table przesłania metodę:Jak zmienić kolejność kolumn 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 

pamiętać, że jest nie dupe dla How does one reorder columns in R?.

+2

Poniższe odpowiedzi dostarczają rozwiązania. [FAQ 2.1.7] (http://datatable.r-forge.r-project.org/datatable-faq.pdf) opisuje tę różnicę między 'data.table' i' data.frame' – mnel

Odpowiedz

25

Zastosowanie 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

W ten sposób można zrobić to w data.table (bez modyfikowania oryginalnego tabela):

dt[, list(b, a)] 

lub

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

lub

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

lub 'setcolorder (copy (dt), c ("b", "a")) " – mnel

Powiązane problemy