R匿名函数:按值捕获变量 [英] R anonymous function: capture variables by value

查看:22
本文介绍了R匿名函数:按值捕获变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个匿名函数列表,这些函数使用在外部作用域中定义的变量.

I've defined a list of anonymous functions which use a variable defined in an outer scope.

funclist <- list()
for(i in 1:5)
{
  funclist[[i]] <- function(x) print(i)
}

funclist[[1]]('foo')

输出为:

[1] 5

似乎 i 是通过引用捕获的.我希望它被价值捕获,即输出应该是

It seems that i is captured by reference. I'd like it to be captured by value, i.e. the output should be

[1] 1

有没有办法告诉 R 通过值而不是引用来捕获 i?

Is there a way to tell R to capture i by value rather than by reference?

推荐答案

当您运行 for 循环时,这会在循环运行的环境中创建一个变量,并在循环中创建函数也从这个环境运行.因此,每当您运行以这种方式创建的使用循环中索引值的函数时,它们只能访问最终值,并且只有该变量仍然存在(尝试 rm(i) 和试图玩弄列表中的功能之一).

When you run a for loop, this creates a variable in the environment the loop is run in, and functions created in the loop are also run from this environment. So whenever you run the functions created in this way that use the index value from the loop, they only have access to the final value, and only as long as that varaible remains (try rm(i) and attempting to fun one of the functions in the list).

您需要做的是将索引值绑定到自己环境中的函数.lapply 会自动为你做这件事.然而,懒惰评估有一个问题.你还需要在创建匿名函数之前forcei的求值:

What you need to do is bind the index value to the function in their own environment. lapply will do this for you automatically. However, there is a gotcha with lazy evaluation. What you have to do is also force the evaluation of i before creating the anonymous function:

funclist <- lapply(1:5, function(i) {force(i); function(x) print(i)})
funclist[[1]]('foo')
[1] 1
funclist[[5]]('foo')
[1] 5

这篇关于R匿名函数:按值捕获变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆