我想以灵活的方式指定功能。当我在它之后创建另一个函数时,如何确保给定函数的环境不会改变。
为了说明,这可以正常工作:
make.fn2 <- function(a, b) {
fn2 <- function(x) {
return( x + a + b )
}
return( fn2 )
}
a <- 2; b <- 3
fn2.1 <- make.fn2(a, b)
fn2.1(3) # 8
fn2.1(4) # 9
a <- 4
fn2.2 <- make.fn2(a, b)
fn2.2(3) # 10
fn2.1(3) # 8
这不
make.fn2 <- function(a, b) {
fn2 <- function(x) {
return( x + a + b )
}
return( fn2 )
}
a <- 2; b <- 3
fn2.1 <- make.fn2(a, b)
a <- 4
fn2.2 <- make.fn2(a, b)
fn2.1(3) # 10
fn2.1(4) # 11
fn2.2(3) # 10
fn2.1(3) # 10