In data.table
, one can use the with = FALSE
to select columns using a vector. For instance:
dt <- data.table(one = 1:3, two = 2:4, three = 3:5)
dt[, .(one, three)]
parlist <- c("one", "three")
dt[, parlist, with = FALSE]
One can also use the j
argument to add a new, constant column:
dt[, .(one, new = 10)]
But is it possible to combine the two? I.e., use a vector to select the columns, but such that it includes a new, constant column. Solutions like parlist <- c("one", "new" = 10)
do not seem to work.
CodePudding user response:
Combine .SDcols
with c(.SD, .(new=10))
:
dt <- data.table(one = 1:3, two = 2:4, three = 3:5)
parlist <- c("one", "three")
dt[, c(.SD, .(new = 10)), .SDcols = parlist]
# one three new
# <int> <int> <num>
# 1: 1 3 10
# 2: 2 4 10
# 3: 3 5 10