Reputation: 4555
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
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?
Upvotes: 13
Views: 10706
Reputation: 11
I think the following syntax will work if you want x in the first column
DF <- cbind(x,DF)
Or if you want it in any column like n
DF.combine <- cbind(DF[,1:(n-1)], x, DF[,n:ncol(DF)])# n should >1
Upvotes: -1
Reputation: 193517
Maybe you can use 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
Using a modified version of your approach:
setcolorder(DT, c("X", names(DT)[1:(length(DT)-1)]))
or
setcolorder(DT, c(length(DT), 1:(length(DT)-1)))
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.
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
Upvotes: 32