で新しい環境を作成して使用できますlocal
。
f <- list()
for(i in 1:10) {
f[[i]] <- local({
j <- i # j is only visible in this local environment,
# and it is a different environment at each iteration.
function() j
})
}
f[[3]]()
# [1] 3
(function(){ ... })()
の代わりにと書くこともありますlocal
。
instead of `local({ ... })`.
f <- list()
for(i in 1:10) {
f[[i]] <-
(function(){
j <- i
function() j
})()
}
f[[3]]()
あなたの例は次のようになります。
f <- function(x) rep(0, length(x))
for(i in -1:2) {
f <- local({
# Copy the variables i and f
j <- i
g1 <- f
g2 <- function(x) j*x
# Define the new function
function(x) {
cat( "i=", j, " Adding ", paste0(g2(x),sep=","), "\n", sep="" )
g1(x) + g2(x)
}
})
}
# Check that result is correct
h <- function(x) 2*x
f(1:3)
# i=2 Adding 2,4,6,
# i=1 Adding 1,2,3,
# i=0 Adding 0,0,0,
# i=-1 Adding -1,-2,-3,
# [1] 2 4 6
h(1:3)
# [1] 2 4 6