User defined function with operators in R

I want to use a user specified function and apply the function to a list of values. I am assuming that the user will provide a "formula" as a character string containing the names of variables and operators, for example. "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 inside a function. To do this, I have to get the "formula" specified by the user inside the function. The character string seems obvious. The question is how to evaluate it inside a function. do.call () doesn't seem to fit as operators are really a function. I was hoping for something simple like

my.formula <- "a * b %% c - d / e ^ f + g %/% h"
with(prmlist, eval(my.formula)) 

      

will work, but it doesn't.

+3


source to share


1 answer


Instead of operators, substitute()

you can declare your own operators:

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

      

+4


source







All Articles