【问题标题】:How do I reorder data.table columns? [duplicate]如何重新排序 data.table 列? [复制]
【发布时间】:2013-04-14 13:29:26
【问题描述】:

如何置换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?的欺骗。

【问题讨论】:

  • 下面的答案提供了解决方案。 FAQ 2.1.7 描述了 data.tabledata.frame 之间的这种区别

标签: r data.table


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这就是你在data.table 中的做法(不修改原始表格):

    dt[, list(b, a)]
    

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

    dt[, c(2, 1)]
    

    【讨论】:

    • setcolorder(copy(dt), c('b','a'))
    猜你喜欢
    • 2012-08-27
    • 2021-11-21
    • 2020-10-14
    • 2019-09-18
    • 1970-01-01
    • 2018-06-01
    • 2016-12-20
    • 2011-03-04
    相关资源
    最近更新 更多