I am using lapply to make new functions and noticed that that sometimes it returns what is expected, and sometimes it returns only copies of the lastly created function.
Here is an example for the illustration, consider that I want to make the following simple list of functions
listFuncs = lapply( 1:3, function(X){
myfunc = function(y){X+y}
myfunc
})
Unfortunately, a simple evaluation shows that I am not getting what I hoped
listFuncs[[1]](10)
[1] 13
listFuncs[[2]](10)
[1] 13
Indeed, the list only contains the function
myfunc = function(y){3+y}
However, if I output something during the creation of the functions, for example
listFuncs = lapply( 1:3, function(X){
myfunc = function(y){X+y}
print(myfunc(0)) ## NEW LINE HERE !!!
myfunc
})
then my list of functions is "as expected"
[1] 1
[1] 2
[1] 3
> listFuncs[[1]](10)
[1] 11
> listFuncs[[2]](10)
[1] 12
Does anyone understand what is going on ? By advance, thank you.