Reputation: 439
So I need to subset and do calculations on a data.table. I need to subset by a dynamic variable but I keep getting a non-numeric to binary operator error.
data(mtcars)
mtcars=as.data.table(mtcars)
mtcars[vs!=am,qsec*-1] ##flip the qsec variable to negative if vs and am do not equal; this works because I directly call qsec
col_to_use='qsec'
mtcars[vs!=am,..col_to_use*-1] ##Error in col_to_use * -1 : non-numeric argument to binary operator
mtcars[vs!=am,..col_to_use] ##Shows the subset to change, everything looks okay.
What am I missing with this?
Upvotes: 2
Views: 59
Reputation: 887691
It is better to specify it in .SDcols
for consistency
mtcars[vs != am, .SD[[1]] * -1, .SDcols = col_to_use]
#[1] -16.46 -17.02 -19.44 -20.22 -20.00 -22.90 -18.30 -18.90 -20.01 -16.70 -14.50 -15.50 -14.60
Or another option is get
(which can be an issue with env)
mtcars[vs != am, get(col_to_use) * -1]
#[1] -16.46 -17.02 -19.44 -20.22 -20.00 -22.90 -18.30 -18.90 -20.01 -16.70 -14.50 -15.50 -14.60
Or convert to symbol
and eval
uate
mtcars[vs != am, eval(as.symbol(col_to_use)) * -1]
#[1] -16.46 -17.02 -19.44 -20.22 -20.00 -22.90 -18.30 -18.90 -20.01 -16.70 -14.50 -15.50 -14.60
Or make use of .SD
column names
mtcars[vs != am, .SD[[col_to_use]] * -1]
#[1] -16.46 -17.02 -19.44 -20.22 -20.00 -22.90 -18.30 -18.90 -20.01 -16.70 -14.50 -15.50 -14.60
Upvotes: 4