[英]Evaluate and save Argument variable value during function definition?
考虑这个 function plus_x
:
y <- 1
plus_x <- function(input, x = y){
return(input + x)
}
这里x
的y
默认值是在 function 调用期间计算的。 如果我稍后更改y
,我也会更改函数行为。
y <- 1
plus_x <- function(input, x = y){
return(input + x)
}
y <-10
plus_x(1)
# > 11
有没有办法将y
的值“固定”到 function 定义期间的 state?
目标:
y <- 1
plus_x <- function(input, x = y){
# y is now always 1
return(input + x)
}
y <-10
plus_x(1)
# > 2
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) 生成器另一种方法是创建一个生成器 function。这样做的好处是可以轻松定义具有不同 y 值的多个不同函数。 查看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
您可以使用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.