简体   繁体   English

Function 返回带参数的 function

[英]Function that returns function with argument

How should I go about when creating a function that should return a function that includes an argument of the original function?当创建一个 function 应该返回一个包含原始 function 的参数的 function 时,我应该如何 go?

Consider for instance this function:例如考虑这个 function:

a <- function(value){
  function(x) x + value
}

I'd like it to return the value I specify in the parameter in the resulting function, like this:我希望它在生成的 function 中返回我在参数中指定的值,如下所示:

b <- a(3)
#> b
#> function(x) x + 3

And be able to use the resulting function b thereafter:然后能够使用生成的 function b

b(2)
#[1] 5

Instead, I get:相反,我得到:

> b
function(x) x + value
<environment: 0x000002254f80a758>

I've tried using substitute , eval , parse ... but I'm a bit confused.我试过使用substituteevalparse ...但我有点困惑。 Preferably a base R solution.最好是基础 R 解决方案。

As I discussed in the comments the function shown in the question already works so the approaches below are not really needed but if you want to create a function with the value of value hard coded into it then one of these.正如我在评论中讨论的那样,问题中显示的 function 已经有效,因此实际上并不需要下面的方法,但如果您想创建一个 function 并将 value 的value硬编码到其中,那么可以使用其中一种方法。 No packages are used.没有使用包。

1) do.call/substitute 1) do.call/替换

a <- function(value, envir = parent.frame()) {
  f <- function(x) x + value
  body(f) <- do.call("substitute", list(body(f), list(value = value)))
  environment(f) <- envir
  f
}

b <- a(3)
b
## function (x) 
## x + 3

b(4)
## [1] 7

lapply(1:3, a, envir = environment())

giving:给予:

[[1]]
function (x) 
x + 1L

[[2]]
function (x) 
x + 2L

[[3]]
function (x) 
x + 3L

2) strings Another possibility is to use string substitution: 2) strings另一种可能性是使用字符串替换:

a2 <- function(value, envir = parent.frame()) {
  eval(parse(text = gsub("\\bvalue\\b", value, "function(x) x + value")), envir)
}

lapply(1:3, a2, envir = environment())

giving:给予:

[[1]]
function(x) x + 1

[[2]]
function(x) x + 2

[[3]]
function(x) x + 3

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

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