繁体   English   中英

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

[英]R: Function as argument of another function

我编写了R函数myplot() ,它在间隔[ myplot()上绘制了一条与提供的函数FUN相对应的曲线。

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

例如

myplot(FUN = dnorm)

在此处输入图片说明

如何向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)不能给出预期的图像...

您的原始功能运行良好(但您的原始示例有错字)

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

myplot(dnorm)
myplot(dnorm, mean = 5)
myplot(dnorm, mean = 5, sd=2)

一切似乎工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM