user7064
user7064

Reputation: 217

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

enter image description here

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

Upvotes: 1

Views: 100

Answers (1)

baptiste
baptiste

Reputation: 77096

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.

Upvotes: 2

Related Questions