简体   繁体   中英

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?

Consider for instance this 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:

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

And be able to use the resulting function b thereafter:

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. Preferably a base R solution.

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. No packages are used.

1) do.call/substitute

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:

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

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