在R函数中包含数学函数

Ale*_*lex 2 r function

我想编写一个函数,它接受任何用户提供的数学函数(例如,x ^ 2)并用它做不同的事情,例如:

#-----------------nonworking code---------------------
foo <- function(FUN, var){
      math_fun <- function(x){
           FUN
      }
   curve(math_fun, -5, 5)     #plot the mathematical function
   y = math_func(var)         #compute the function based on a user provided x value.
   points(x=var, y=y)         #plot the value from the last step.
}

#A user can use the function defined above in a way as shown below:
Function <- x^2 + x
foo(FUN=Function, var = 2)
Run Code Online (Sandbox Code Playgroud)

但显然这个功能不起作用:首先,如果我运行这个功能,我得到Error in math_fun(x) : object 'x' not found.

其次,即使函数确实有效,我假设变量是x,但用户可以使用任何字母.

对于第二个问题,一个可能的解决方案是要求用户指定他们用作变量的字母.

foo <- function(FUN, var, variable){
      math_fun <- function(variable){
           FUN
      }
   curve(math_fun, -5, 5) 
   y = math_func(var)     
   points(x=var, y=y)     
}
Run Code Online (Sandbox Code Playgroud)

但我对于如何实现这一点感到很遗憾......如果有人能帮我解决至少部分问题,那就太棒了.谢谢!

flo*_*del 6

它比这简单得多.用户定义的函数应该在其定义中包含参数,例如,function(x) x^2 + x而不是x^2 + x.然后它可以直接传递和调用:

foo <- function(math_fun, var){

   curve(math_fun, -5, 5)  #plot the mathematical function
   y = math_fun(var)       #compute the function based on a user provided x value
   points(x=var, y=y)      #plot the value from the last step.
}

#A user can use the function defined above in a way as shown below:
Function <- function(x) x^2 + x
foo(Function, var = 2)
Run Code Online (Sandbox Code Playgroud)