Returning anonymous functions from lapply - what is going wrong?

前端 未结 2 506
北荒
北荒 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:53

    This is no longer true as of R 3.2.0!

    The corresponding line in the change log reads:

    Higher order functions such as the apply functions and Reduce() now force arguments to the functions they apply in order to eliminate undesirable interactions between lazy evaluation and variable capture in closures.

    And indeed:

    pow <- function(x,y) x^y
    pl <- lapply(1:3,function(y) function(x) pow(x,y))
    pl[[1]](2)
    # [1] 2
    pl[[2]](2)
    # [1] 4
    pl[[3]](2)
    # [1] 8
    

提交回复
热议问题