I want to use a user-specified function and apply the function to a list of values. I envision that the user will give a 'formula' as a character string containing the names of variable and operators, e.g. "a * b %% c - d / e ^ f + g %/% h".
The following toy example works
prmlist <- list(a=1:10, b=21:30, c=31:40, d=4, e=5, f=6, g=7, h=8)
with(prmlist, a * b %% c - d / e ^ f + g %/% h)
The problem starts when I want to use this approach within a function. To do that I must get the 'formula' specified by the user inside the function. A character string seems the obvious route. The question is how to evaluate it inside the function. do.call() doesn't seem to be suited because the operators are each really a function. I hoped something simple like
my.formula <- "a * b %% c - d / e ^ f + g %/% h"
with(prmlist, eval(my.formula))
would work but it doesn't.
You can envoke your operators using substitute() instead:
my.formula <- substitute(a * b %% c - d / e ^ f + g %/% h)
with(prmlist, eval(my.formula))
[1] 20.99974 43.99974 68.99974 95.99974 124.99974 155.99974 188.99974
[8] 223.99974 260.99974 299.99974
Update: If the command is a string you can use parse:
myCmd <- "a * b %% c - d / e ^ f + g %/% h"
with(prmlist, eval( parse(text=myCmd) ))
[1] 20.99974 43.99974 68.99974 95.99974 124.99974 155.99974 188.99974
[8] 223.99974 260.99974 299.99974
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With