将数学函数包装到R函数中
我想写一个函数,它接受任何用户提供的数学函数(例如x^2),并用它做不同的事情,例如:将数学函数包装到R函数中,r,function,R,Function,我想写一个函数,它接受任何用户提供的数学函数(例如x^2),并用它做不同的事情,例如: #-----------------nonworking code--------------------- foo <- function(FUN, var){ math_fun <- function(x){ FUN } curve(math_fun, -5, 5) #plot the mathematical function
#-----------------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)
但我不知道我到底该如何实现这一点。。。如果有人能帮我解决至少部分问题,那就太好了。谢谢 比这简单多了。用户定义函数的定义中应包含参数,例如
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)
foo呃,出于某种原因,我以前也做过类似的事情,但curve(Function,-5,5)一直给我一条错误消息。可能在什么地方出错了。但是谢谢你!!!
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)