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"
.
我希望使用用户指定的函数,并将该函数应用到值列表。我设想用户将给出一个“公式”作为一个字符串,其中包含变量和操作符的名称,例如。“a * b % % c f + g - d / e ^ % / % 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
当我想在函数中使用这种方法时,问题就出现了。要做到这一点,我必须得到用户在函数中指定的“公式”。字符串似乎是明显的路径。问题是如何在函数中求值。call()似乎不适合,因为操作符实际上都是函数。我希望有一些简单的东西
my.formula <- "a * b %% c - d / e ^ f + g %/% h"
with(prmlist, eval(my.formula))
would work but it doesn't.
可能行得通,但行不通。
1 个解决方案
#1
4
You can envoke your operators using substitute()
instead:
您可以使用substitute()替代您的操作符:
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
:
更新:如果命令是字符串,可以使用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
#1
4
You can envoke your operators using substitute()
instead:
您可以使用substitute()替代您的操作符:
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
:
更新:如果命令是字符串,可以使用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