[英]R: Function as argument of another function
I have written the R function myplot()
which draws a curve corresponding to the supplied function FUN
over the interval [-10, 10]. 我编写了R函数
myplot()
,它在间隔[ myplot()
上绘制了一条与提供的函数FUN
相对应的曲线。
myplot <- function(FUN)
{
curve(FUN(x), xlim = c(-10, 10))
}
For example 例如
myplot(FUN = dnorm)
gives 给
How can I add arguments to FUN
? 如何向
FUN
添加参数? For example, let's say I want to plot the normal density with mean 5. 例如,假设我要用平均值5绘制法线密度。
Following @akrun's comment, I can do something like that: 遵循@akrun的评论,我可以执行以下操作:
myplot <- function(FUN, ...)
{
args <- list(...)
curve(FUN(x, unlist(args)), xlim = c(-10, 10))
}
myplot(dnorm, mean = 5)
But then 但是之后
> myplot(FUN = dnorm)
Error in FUN(x, unlist(args)) :
Argument non numérique pour une fonction mathématique
Also, myplot(FUN = dnorm, mean = 5, sd = 2)
does not give the expected picture... 另外,
myplot(FUN = dnorm, mean = 5, sd = 2)
不能给出预期的图像...
Your original function works fine (but your original example had a typo) 您的原始功能运行良好(但您的原始示例有错字)
myplot <- function(FUN, ...)
{
curve(FUN(x, ...), xlim = c(-10, 10))
}
myplot(dnorm)
myplot(dnorm, mean = 5)
myplot(dnorm, mean = 5, sd=2)
all seem to work. 一切似乎工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.