r - Returning anonymous functions from lapply - what is going wrong? -
when trying create list of similar functions using lapply
, find functions in list identical , equal final element should be.
consider following:
pow <- function(x,y) x^y pl <- lapply(1:3,function(y) function(x) pow(x,y)) pl [[1]] function (x) pow(x, y) <environment: 0x09ccd5f8> [[2]] function (x) pow(x, y) <environment: 0x09ccd6bc> [[3]] function (x) pow(x, y) <environment: 0x09ccd780>
when try evaluate these functions identical results:
pl[[1]](2) [1] 8 pl[[2]](2) [1] 8 pl[[3]](2) [1] 8
what going on here, , how can result desire (the correct functions in list)?
r passes promises, not values themselves. promise forced when first evaluated, not when passed, , time index has changed if 1 uses code in question. code can written follows force promise @ time outer anonymous function called , make clear reader:
pl <- lapply(1:3, function(y) { force(y); function(x) pow(x,y) } )
Comments
Post a Comment