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

查看:123
本文介绍了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天全站免登陆