简体   繁体   中英

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].

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

For example

myplot(FUN = dnorm)

gives

在此处输入图片说明

How can I add arguments to FUN ? For example, let's say I want to plot the normal density with mean 5.

Following @akrun's comment, I can do something like that:

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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