我在循环中定义函数并试图强制评估循环变量而不必携带私有环境.
示例:一组函数handlers$h1,, handlers$h2...,handlers$h6只是通过1,2,...,6传递给另一个函数,如下所示:
handlers <- list()
for (i in 1:6) {
handlers[[paste0('h', i)]] <- function () {
message(i) # <-- example
}
}
Run Code Online (Sandbox Code Playgroud)
所以handlers$h1()应该消息1,handlers$h2()应该消息2,...
相反,所有函数返回6,当前值i.
为了解决这个问题,我可以使用此问题中指定的闭包
msg <- function(i) {
force(i)
function () { message(i) }
}
for (i in 1:6) {
handlers[[paste0('h', i)]] <- msg(i)
}
Run Code Online (Sandbox Code Playgroud)
现在每个函数都按预期工作,但每个函数都必须携带自己的环境:
handlers$h1
# function () { message(i) }
# <environment: 0x9342b80>
Run Code Online (Sandbox Code Playgroud)
我怎样才能使handlers$h1打印 …