I have to write a long script (call it Script) doing various operations on a data.table, then apply this a few times for different subsets of rows. I would like to be able to do the following:
condition <- "X>10"
source(Script)
... where Script will contain many of the following:
dt[MAGIC(condition), .......]
This would allow me to keep Script and the condition in different files (the second a markdown showing the results only, and which I'd like to be as simple as possible in terms of code).
What I don't want is to copy paste the script for each of the conditions, and manually change it, since this is way too error prone.
I tried lots of combinations of parse, deparse, substitute, quote, as.expression, as.logical, etc. but I seem to be staggering in the dark. I'd be really grateful if somebody could help!
NB: I can easily do the above in dplyr:
df %>% filter_(condition)
and of course I can also turn this back into a data.table
df %>% filter_(condition) %>% data.table()
... but I'd rather work consistently with data.table (faster, prefer the syntax, etc.)
We use eval(parse
setdT(dt)[eval(parse(text=condition))]