I’m trying to assign a function for each element in a loop.
I would like the functions use the value of the variable, but they use the last value of the variable:
assign.instrumentslist = function()
{
for(instList in lists.instruments)
{
assign(
paste("test", instList, sep="."),
function() {print(instList)},
envir = .GlobalEnv
)
}
}
lists.instruments = c("CL", "HO", "GC")
assign.instrumentslist()
test.CL()
# return "GC"
thx
Probably this is the easiest way:
The key is to create local objects (
i) on the function’s enclosing environment.In this example, the environment is generated by
local.And this is a really really bad hack: