Reorder columns of a data.table (via setcolorder) so that particular columns appear first (or last), or in a particular order.

set_cols_first(DT, cols, intersection = TRUE)

set_cols_last(DT, cols, intersection = TRUE)

set_colsuborder(DT, cols, intersection = TRUE)

Arguments

DT

A data.table.

cols

Character vector of columns to put before (after) all others or, in the case of set_colsuborder, a vector of columns in the order requested.

intersection

Use the intersection of the names of DT and cols. If FALSE any cols are not the names of DT, the function may error on behalf of data.table. Not available for set_colsuborder.

Details

In the case of set_colsuborder the group of columns cols occupy the same positions in DT but in a different order. See examples.

Examples

library(data.table) DT <- data.table(y = 1:5, z = 11:15, x = letters[1:5]) set_cols_first(DT, "x")[]
#> x y z #> 1: a 1 11 #> 2: b 2 12 #> 3: c 3 13 #> 4: d 4 14 #> 5: e 5 15
set_cols_last(DT, "x")[]
#> y z x #> 1: 1 11 a #> 2: 2 12 b #> 3: 3 13 c #> 4: 4 14 d #> 5: 5 15 e
set_colsuborder(DT, c("x", "y"))[]
#> x z y #> 1: a 11 1 #> 2: b 12 2 #> 3: c 13 3 #> 4: d 14 4 #> 5: e 15 5