简体   繁体   中英

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 ?

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
}

Eg:

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

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.

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