I want to make an R function that returns a list of functions that each operate on a different part of a list. However, because of R's rules on scope, this seems impossible. Here's an example:
functiontest = function() {
foo = list()
for(i in 1:3) {
fixer = function(s) { return(
function() {
return(s)
}
)}
foo[[i]] = fixer(i)
}
return(foo)
}
functiontest()[[2]]() #returns 3
Even killing off the named lambda "fixer" and using an immediate function doesn't save me:
functiontest = function() {
foo = list()
for(i in 1:3) {
foo[[i]]=(function(s) { return(
function() {
return(s)
}
)})(i)
}
return(foo)
}
functiontest()[[2]]() #returns 3
I want this to return 2. How can I refactor this code so that this will happen?
Thanks.
See Question&Answers more detail:os