Therefore, consider the following piece of code that does not work, since most people can expect it
a <- c(3,7,11)
f <- list()
f[[1]]<-function(x) a[1]+x
f[[2]]<-function(x) a[2]+x
f[[3]]<-function(x) a[3]+x
f[[1]](1)
f[[3]](1)
for(i in 1:3) {
f[[i]] <- function(x) a[i]+x
}
f[[1]](1)
f[[3]](1)
Note that we get 12 times after trying to "automate". Of course, the problem is that ifunctions are not contained in the private environment. All functions relate to the same thing iin the global environment (which can have only one value), since the for loop does not create another environment for each iteration.
sapply(f, environment)
# [[1]]
# <environment: R_GlobalEnv>
# [[2]]
# <environment: R_GlobalEnv>
# [[3]]
# <environment: R_GlobalEnv>
Therefore, although I could do with using local()and force()to fix the valuei
for(i in 1:3) {
f[[i]] <- local({force(i); function(x) a[i]+x})
}
f[[1]](1)
f[[3]](1)
but it still does not work. I see that they all have different environments (through sapply(f, environment)), but they seem empty ( ls.str(envir=environment(f[[1]]))). Compare this to
for(i in 1:3) {
f[[i]] <- local({ai<-i; function(x) a[ai]+x})
}
f[[1]](1)
f[[3]](1)
ls.str(envir=environment(f[[1]]))
ls.str(envir=environment(f[[3]]))
, force() , . , i . ,
f <- lapply(1:3, function(i) function(x) a[i]+x)
f <- lapply(1:3, function(i) {force(i); function(x) a[i]+x})
i /, , for.
, : local() ? , force(), / ?