R:作为另一个函数的参数的函数

时间:2016-02-03 07:41:16

标签: r function

我编写了R函数myplot(),它在[-10,10]区间内绘制了与提供的函数FUN对应的曲线。

myplot <- function(FUN)
{
  curve(FUN(x), xlim = c(-10, 10))
}

例如

myplot(FUN = dnorm)

给出

enter image description here

如何向FUN添加参数?例如,假设我想用平均值5绘制正常密度。

按照@ akrun的评论,我可以这样做:

myplot <- function(FUN, ...)
{
  args <- list(...)
  curve(FUN(x, unlist(args)), xlim = c(-10, 10))
}
myplot(dnorm, mean = 5)

但是

   > myplot(FUN = dnorm)
    Error in FUN(x, unlist(args)) : 
      Argument non numérique pour une fonction mathématique

此外,myplot(FUN = dnorm, mean = 5, sd = 2)未提供预期的图片......

1 个答案:

答案 0 :(得分:2)

您的原始功能正常(但您的原始示例有拼写错误)

myplot <- function(FUN, ...)
{
    curve(FUN(x, ...), xlim = c(-10, 10))
}

myplot(dnorm)
myplot(dnorm, mean = 5)
myplot(dnorm, mean = 5, sd=2)
似乎一切正常。

相关问题