当试图创建使用类似功能的列表lapply
,我发现列表中的所有功能都相同且为最终的元素应该是什么。
考虑以下:
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>
当您尝试评估这些功能,你会得到相同的结果:
pl[[1]](2)
[1] 8
pl[[2]](2)
[1] 8
pl[[3]](2)
[1] 8
这到底是怎么回事,我如何能得到我想要(在列表中选择正确的功能)的结果?
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) } )
这已不再是真正的为R 3.2.0的!
在相应线路更改日志记载:
高阶功能,如应用功能和减少()现在强制参数为他们申请的功能,以消除懒惰的评价和封闭的可变捕获之间不必要的相互作用。
事实上:
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