[datatable-help] best way of eval-ing a list of quoted expressions
Frank Erickson
fperickson at wisc.edu
Wed Jan 14 23:06:36 CET 2015
Hi,
I'm wondering what the most idiomatic or efficient approach is...? Here's
my example:
expr_nonlin = list(
early = quote(tt/TT*(tt/TT < .2)),
late = quote(tt/TT*(tt/TT > .8))
)
# eval on a single expr works
data.table(tt=1,TT=100)[,early:=eval(expr_nonlin$early)][]
# lapply eval does not work
data.table(tt=1,TT=100)[,names(expr_nonlin):=lapply(expr_nonlin,eval)][]
# (1) envir fixes it
DT <- data.table(tt=1,TT=100)
DT[,names(expr_nonlin):=lapply(expr_nonlin,eval,envir=DT)][]
# (2) or a for loop
DT <- data.table(tt=1,TT=100)
for (i in names(expr_nonlin)) DT[,(i):=eval(expr_nonlin[[i]])]
(1) and (2) both work. Is either preferable?
(1) calls [.data.table fewer times, but messes around with environments,
which always seem fragile.
------------------
One more quick question: In approach (1), is there a way to skip the
names(zzz):= part? I see that this doesn't work:
DT <- data.table(tt=1,TT=100)
DT[,do.call(`:=`,lapply(expr_nonlin,eval,envir=DT))][]
Thanks,
Frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20150114/035b1682/attachment.html>
More information about the datatable-help
mailing list