更改data.table的列位置 [英] Change column position of data.table
问题描述
我正在学习使用data.table包。我想做的事情之一是将最后一列(x)移动到第一列。这是我如何做一个数据框架:
I am learning to use the data.table package. One of the things I am trying to do is move the last column ("x") to the first column. Here is how I do it for a data frame:
DF <- cbind(x, DF[1:ncol(DF)]) #Rearrange columns
我读了setcolorder并尝试这个,但我得到一个错误
I read up on setcolorder and tried this, but I get an error
setcolorder(DT, c("x", 1: (length(DT)-1) ) )
有人知道更好的解决方案吗?
Does anyone know a better solution?
推荐答案
选项1
也许您可以使用 setdiff
:
DT <- data.table(A = 1:2, B = 3:4, X = 5:6)
DT
# A B X
# 1: 1 3 5
# 2: 2 4 6
setcolorder(DT, c("X", setdiff(names(DT), "X")))
DT
# X A B
# 1: 5 1 3
# 2: 6 2 4
选项2
使用修改版本的方法:
Option 2
Using a modified version of your approach:
setcolorder(DT, c("X", names(DT)[1:(length(DT)-1)]))
或
setcolorder(DT, c(length(DT), 1:(length(DT)-1)))
$ b b
为什么你的方法中的错误?您试图包括列名称和数字列索引。
Why the error in your approach? You were trying to include both column names and numeric column indices. Use one or the other, but not both.
我写了一个函数 moveme
(暂时你可以找到在此Gist 或在我的博客)。您输入一个移动命令字符串,用分号分隔。这使得你可以灵活地在你的列周围移动:
I've written a function called moveme
(which for the time being you can find at this Gist or at my blog). You enter a string of "move" commands, separated by semicolons. This lets you shuffle around your columns pretty flexibly:
DT <- data.table(matrix(1:20, ncol = 10, dimnames = list(NULL, LETTERS[1:10])))
DT
# A B C D E F G H I J
# 1: 1 3 5 7 9 11 13 15 17 19
# 2: 2 4 6 8 10 12 14 16 18 20
setcolorder(DT, moveme(names(DT), "E, F first; B last; H, I before G"))
# DT
# E F A C D H I G J B
# 1: 9 11 1 5 7 15 17 13 19 3
# 2: 10 12 2 6 8 16 18 14 20 4
这篇关于更改data.table的列位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!