setcolorder | R Documentation |
In data.table
parlance, all set*
functions change their input by reference. That is, no copy is made at all, other than temporary working memory, which is as large as one column. The only other data.table
operator that modifies input by reference is :=
. Check out the See Also
section below for other set*
function data.table
provides.
setcolorder
reorders the columns of data.table, by reference, to the new order provided.
setcolorder(x, neworder=key(x), before=NULL, after=NULL)
x |
A |
neworder |
Character vector of the new column name ordering. May also be column numbers. If |
before , after |
If one of them (not both) was provided with a column name or number, |
To reorder data.table
columns, the idiomatic way is to use setcolorder(x, neworder)
, instead of doing x <- x[, ..neworder]
(or x <- x[, neworder, with=FALSE]
). This is because the latter makes an entire copy of the data.table
, which maybe unnecessary in most situations. setcolorder
also allows column numbers instead of names for neworder
argument, although we recommend using names as a good programming practice.
The input is modified by reference, and returned (invisibly) so it can be used in compound statements. If you require a copy, take a copy first (using DT2 = copy(DT)
). See ?copy
.
setkey
, setorder
, setattr
, setnames
, set
, :=
, setDT
, setDF
, copy
, getNumericRounding
, setNumericRounding
set.seed(45L)
DT = data.table(A=sample(3, 10, TRUE),
B=sample(letters[1:3], 10, TRUE), C=sample(10))
setcolorder(DT, c("C", "A", "B"))
#incomplete specification
setcolorder(DT, "A")
# insert new column as first column
set(DT, j="D", value=sample(10))
setcolorder(DT, "D", before=1)
# move column to last column place
setcolorder(DT, "A", after=ncol(DT))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.