简体   繁体   English

在 function 定义期间评估并保存参数变量值?

[英]Evaluate and save Argument variable value during function definition?

Consider this function plus_x :考虑这个 function plus_x

y <- 1

plus_x <- function(input, x = y){
  return(input + x)
}

here the y default-value for x is evaluated during the function call.这里xy默认值是在 function 调用期间计算的。 If I change y later on, I am also changing the functions behaviour.如果我稍后更改y ,我也会更改函数行为。

y <- 1

plus_x <- function(input, x = y){
  return(input + x)
}

y <-10

plus_x(1)
# > 11

Is there a way to "cement" the value for y to the state it was during the function definition?有没有办法将y的值“固定”到 function 定义期间的 state?

Target:目标:

y <- 1

plus_x <- function(input, x = y){
  # y is now always 1
  return(input + x)
}

y <-10

plus_x(1)
# > 2

1) local Surround the function with a local that saves y locally: 1)本地local保存y的本地包围 function:

y <- 1

plus_x <- local({
  y <- y
  function(input, x = y) input + x
})

y <-10
plus_x(1)
## [1] 2

2) generator Another approach is to create a generator function. This has the advantage that multiple different functions with different y values could be easily defined. 2) 生成器另一种方法是创建一个生成器 function。这样做的好处是可以轻松定义具有不同 y 值的多个不同函数。 Look at demo("scoping", package = "base") for more examples of using scoping.查看demo("scoping", package = "base")以获取更多使用范围的示例。

gen <- function(y) {
  force(y)
  function(input, x = y) input + x
}

y <- 1
plus_1 <- gen(y)
y <-10
plus_1(1)
## [1] 2

y <- 2
plus_2 <- gen(y)
y <- 10
plus_2(1)
## [1] 3

You could define the function using as.function so that the default value is evaluated at the time of function construction.您可以使用as.function定义 function,以便在构造 function 时评估默认值。

y <- 1

plus_x <- as.function(list(input = NULL, x = y, quote({
  return(input + x)
  })))

plus_x(1)
#> [1] 2

y <-10

plus_x(1)
#> [1] 2

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

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