因此,请考虑以下代码块,它不像大多数人所期望的那样工作
#cartoon example
a <- c(3,7,11)
f <- list()
#manual initialization
f[[1]]<-function(x) a[1]+x
f[[2]]<-function(x) a[2]+x
f[[3]]<-function(x) a[3]+x
#desired result for the rest of the examples
f[[1]](1)
# [1] 4
f[[3]](1)
# [1] 12
#attempted automation
for(i in 1:3) {
f[[i]] <- function(x) a[i]+x
}
f[[1]](1)
# [1] 12
f[[3]](1)
# [1] 12
Run Code Online (Sandbox Code Playgroud)
请注意,在我们尝试“自动化”之后,我们两次都得到了 12。当然,问题在于i它没有包含在函数的私有环境中。所有函数i在全局环境中都引用相同的(只能有一个值),因为 for 循环似乎不会为每次迭代创建不同的环境。
sapply(f, environment)
# [[1]]
# <environment: R_GlobalEnv>
# [[2]]
# <environment: R_GlobalEnv>
# [[3]]
# <environment: R_GlobalEnv>
Run Code Online (Sandbox Code Playgroud)
所以我虽然我可以解决使用local()和 …