Within my code, I would like to programmatically select some variables and select and rename some others in a hard coded way. I know that I could achieve this in two steps with setnames()
, yet I am curious how to do it in a single step.
I think I am quite close to it via .SDcols
. However, when I try to combine .SD
with the renamed column, the ".SDcols
columns" are prefixed with ".SD.". How can the prefix be avoided?
library(data.table)
dt <- as.data.table(mtcars)[1:5]
dt
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> 1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> 2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> 3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> 4: 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> 5: 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
my_vars <- c("cyl", "vs")
# with .SDcol
dt[, .(.SD, z = gear), .SDcol = my_vars]
#> .SD.cyl .SD.vs z # Note the prefix that had been added to the .SDcols
#> 1: 6 0 4
#> 2: 6 0 4
#> 3: 4 1 4
#> 4: 6 1 3
#> 5: 8 0 3
# with named vector
all_vars <- c(my_vars, z = "gear")
dt[, ..all_vars]
#> cyl vs gear
#> 1: 6 0 4
#> 2: 6 0 4
#> 3: 4 1 4
#> 4: 6 1 3
#> 5: 8 0 3
See Question&Answers more detail:os