gpt4 book ai didi

r - 如何对 data.table 列重新排序?

转载 作者:行者123 更新时间:2023-12-02 00:08:29 26 4
gpt4 key购买 nike

如何排列 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? 的骗局.

最佳答案

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

关于r - 如何对 data.table 列重新排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16133678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com