Wrangling data with data.table's, I find myself writing lines like this third line a lot:
DT = data.table(a = 1:10)
name = 'a'
DT[,eval(parse(text=sprintf('%s_plus_one := %s + 1',name,name)))]
which I had hoped to reduce to
DT[,s('%s_plus_one := %s + 1',name,name)]
using a function like:
# s is *very* short for substitute and evalute
s <- function(...)
eval(parse(text=sprintf(...)))
but then I get this error:
> DT[,s('%s_plus_one := %s + 1',name,name)]
Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").
I know I can do this:
# sp is short for substitute and parse
sp <- function(...)
parse(text=sprintf(...))
DT[,eval(sp('%s_plus_one := %s + 1',name,name))]
DT
#> a a_plus_one
#> 1: 1 2
#> 2: 2 3
#> 3: 3 4
#> 4: 4 5
but building strings to be evaluated in a data.table assignment is so common, that I'd hoped minimize typing as much as possible.