Returning anonymous functions from lapply - what is going wrong?

前端 未结 2 501
北荒
北荒 2020-11-28 12:29

When trying to create a list of similar functions using lapply, I find that all the functions in the list are identical and equal to what the final element shou

2条回答
  •  被撕碎了的回忆
    2020-11-28 12:38

    R passes promises, not the values themselves. The promise is forced when it is first evaluated, not when it is passed, and by that time the index has changed if one uses the code in the question. The code can be written as follows to force the promise at the time the outer anonymous function is called and to make it clear to the reader:

    pl <- lapply(1:3, function(y) { force(y); function(x) pow(x,y) } )
    

提交回复
热议问题