1

Why is the behavior different for the latter two? It seems to me they should all give identical output (1, 2).

myFunc = function(i) {
    return(function() { return(i) })
}
mF1 = myFunc(1);
mF1() #1
mF2 = myFunc(2);
mF1() #1
mF2() #2

myList = list()
for(i in 1:2) {
    myList[[i]] = myFunc(i)
}
myList[[1]]() #2
myList[[2]]() #2

applyList = lapply(c(1,2), myFunc)
applyList[[1]]() #2
applyList[[2]]() #2

Thanks.

Peter
  • 1,032
  • 1
  • 11
  • 26
  • 1
    I'm going to take a stab and suggest it has to do with this: [Explain a lazy evaluation quirk](http://stackoverflow.com/questions/16129902/explain-a-lazy-evaluation-quirk). Especially since adding `force(i)` as the first line of your `myFunc` solves it, as per the linked question. – thelatemail Mar 03 '15 at 04:17
  • Yep, that seems to be the answer. I didn't realize it was lazy evaluation--R seems to switch between lazy and eager in ways and for reasons that mere mortals are not meant to comprehend. Bah. – Peter Mar 03 '15 at 04:22

0 Answers0