简体   繁体   English

将带有参数作为参数的函数传递给R中的另一个函数

[英]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) )? fx = dunif起作用时,但是如何为fx传递其他参数,例如dunif(min=-0.5, max-0.5) )? Is it possible to do it without specifying additional set of parameters to genfx ? 是否可以在不为genfx指定额外参数的情况下做到这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: 没有更多细节,我们可能不需要它们,最简单的情况是将...插入对fx的调用中,就好像...只是另一个参数:

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 这是pryr包的一种方法

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. partial只是准备一个带有部分完整参数列表的函数。 Handy in situations like this. 在这种情况下很方便。

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

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