I am having some trouble getting an eval within data.table in R to work with an expression. Here is some code:
dtb = data.table(a=1:100, b=100:1, id=1:10)
dtb[,`:=`(c=a+b, d=a/b),by=id] #this works fine
expr = expression({`:=`(c=a+b, d=a/b)}) #try to couch everything in an expression
dtb[,eval(expr),by=id] #this does not work
Error in `:=`(c = a + b, d = a/b) :
unused argument(s) (c = a + b, d = a/b)
expr = expression(`:=`(c=a+b, d=a/b)) #this works fine
dtb[,eval(expr),by=id]
Why does including {} break this?
See the definition of
:=:The assignment of a column doesn’t happen within a call of
:=–the function itself doesn’t do anything besides produce an error. The assignment happens when[.data.tabledetectsjis an expression of the form`:=`(...)and then sets everything up for a call to the C code. When you encloseexprin brackets, you’re making the first part of the expression{instead of:=, which passes by the above detection and eventually results in an evaluation of:=with argumentscandd.I guess that leads to the question, why do you need to enclose it in
{ }?