本文介绍了从lapply返回匿名函数 - 什么是错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 当尝试使用 lapply 创建类似函数的列表时,我发现列表中的所有函数都是相同的,等于最后一个元素。 / p> 请考虑以下内容: y)x ^ y pl 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 这里是怎么回事,如何获得我想要的结果(列表中的正确函数)?解决方案 p> R通过 promises ,而不是值本身。 promise在第一次求值时被强制,而不是当它被传递时被强制,并且到那时,如果使用问题中的代码,索引已经改变。代码可以编写如下,以强制承诺调用外部匿名函数的时间并向读者说明: pl 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 should be.Consider the following:pow <- function(x,y) x^ypl <- 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 you try to evaluate these functions you get identical results:pl[[1]](2)[1] 8pl[[2]](2)[1] 8pl[[3]](2)[1] 8What is going on here, and how can I get the result I desire (the correct functions in the list)? 解决方案 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) } ) 这篇关于从lapply返回匿名函数 - 什么是错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 14:12