R指定功能环境 [英] R specify function environment

查看:103
本文介绍了R指定功能环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对R语言中的函数环境有疑问. 我知道每次在R中调用一个函数时,都会有一个新环境E 创建在其中执行功能主体的位置.的父链接 E指向创建函数的环境.

I have a question about function environments in the R language. I know that everytime a function is called in R, a new environment E is created in which the function body is executed. The parent link of E points to the environment in which the function was created.

我的问题:是否可以以某种方式指定环境E,即 提供应该执行功能的特定环境?

My question: Is it possible to specify the environment E somehow, i.e., can one provide a certain environment in which function execution should happen?

推荐答案

一个函数的环境可以从函数外部更改,但不能在函数内部更改.环境是函数的属性,可以使用environment()进行检索/设置.一个功能最多具有一个环境,但是您可以在不同的环境中复制该功能.

A function has an environment that can be changed from outside the function, but not inside the function itself. The environment is a property of the function and can be retrieved/set with environment(). A function has at most one environment, but you can make copies of that function with different environments.

让我们为x设置一些环境.

Let's set up some environments with values for x.

x <- 0
a <- new.env(); a$x <- 5
b <- new.env(); b$x <- 10

和使用环境中的x的函数foo

and a function foo that uses x from the environment

foo <- function(a) {
    a + x
}
foo(1)
# [1] 1

现在我们可以编写一个辅助函数,可以在任何环境下调用该函数.

Now we can write a helper function that we can use to call a function with any environment.

with_env <- function(f, e=parent.frame()) {
    stopifnot(is.function(f))
    environment(f) <- e
    f
}

这实际上返回一个分配了不同环境的新函数(或者,如果未指定,它将使用调用环境),我们可以通过传递参数来调用该函数.观察

This actually returns a new function with a different environment assigned (or it uses the calling environment if unspecified) and we can call that function by just passing parameters. Observe

with_env(foo, a)(1)
# [1] 6
with_env(foo, b)(1)
# [1] 11
foo(1)
# [1] 1

这篇关于R指定功能环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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