I define functions in a loop and try to force a loop variable to be evaluated without having to migrate a private environment.
Example: a set of functions handlers$h1 , handlers$h2 , ..., handlers$h6 , which simply go through 1, 2, ..., 6 to the following function:
handlers <- list() for (i in 1:6) { handlers[[paste0('h', i)]] <- function () { message(i)
So handlers$h1() should be message 1, handlers$h2() should be message 2, ...
Instead, all functions return 6 , the current value of i .
To get around this, I can use closure as indicated in this question
msg <- function(i) { force(i) function () { message(i) } } for (i in 1:6) { handlers[[paste0('h', i)]] <- msg(i) }
Now each function works as expected, but each function should carry around its own environment:
handlers$h1
How can I make handlers$h1 print function () { message(1) } , i.e. evaluated i and substituted it directly into the definition, eliminating the need for an environment?
The only ways I can think of are:
- use
eval (something that I prefer not to do); - write down each definition manually with the replacement 1-6 directly (excellent in this case, when there are only 6 functions, but, generally speaking, are not scalable)
source share