Skip to content
Prev 175029 / 398506 Next

programming creating different functions in a loop

for() does not creae separete bindings for the index each iteration,
so the function bodies see the global binding of i, which in this case
will be the final value.  One possible solution is to use local(), e.g.

for(i  in 1:3){
     assign(paste("f",i,sep=""),
        local({
                k <- i  # create local binding with current loop index value
                function(x) x + k
             }))
}


luke
On Thu, 26 Mar 2009, Florin Maican wrote: