MJ30
MJ30

Reputation: 21

Passing a function with parameters as an argument to another function in R

Consider an example:

I want to pass a function with or without parameters to another function and use it in the following way:

genfx <- function(fx, fy, M, fs, ...){ 

  a <- 1
  b <- fx(a)
  ...
}

When fx = dunif it works, but how can I pass additional parameters for fx, for example, dunif(min=-0.5, max-0.5))? Is it possible to do it without specifying additional set of parameters to genfx?

Upvotes: 2

Views: 142

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174813

Without more specifics, and we may not need them, the simplest case is just to insert ... into the call to fx, as if the ... were just another argument:

genfx <- function(fx, fy, M, fs, ...){ 

  a <- 1
  b <- fx(a, ...)
  ## more code here
}

E.g.:

genfx <- function(fx, ...){ 

  a <- 1
  b <- fx(a, ...)
  b
}

> genfx(dunif)
[1] 1
> genfx(dunif, min = -0.5, max = 1.5)
[1] 0.5

(Note I removed the other arguments for simplicity in the example. This wasn't necessary though in this case.)

Upvotes: 5

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

Here is one way with pryr package

library(pryr)

genfx <- function(fx) { 
    a <- 1
    b <- fx(a)
    b
}

myDunif <- partial(dunif, min=-0.5, max=0.5)

genfx(dunif)
[1] 1
genfx(myDunif)
[1] 0

partial just prepares a function with partially complete list of arguments. Handy in situations like this.

Upvotes: 0

Related Questions