Not sure about how to ask the question clearly, but I would like to do some computation with a data table, using column names stored in variables.
Here is a MWE (except the last line of course) of what I want:
library(data.table)
dt = data.table(a = 1:5, b = letters[1:5])
myCol = "a"
dt[, ..myCol]
dt[, a := a - 3]
dt[, (myCol) := a - 3]
dt[, (myCol) := ..myCol - 3] # This will fail, is it because R is trying to compute "a" - 3 which makes no sense?
The only work around I found is by using eval
and parse
, such as:
dt[, (myCol) := eval(parse(text = myCol)) - 3]
Is there a simpler syntax?