使用函数和环境 [英] Using functions and environments

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

问题描述

根据最近的讨论(例如 12 ) 我现在在我的一些代码中使用环境.我的问题是,如何创建根据参数修改环境的函数?例如:

Following the recent discussions here (e.g. 1, 2 ) I am now using environments in some of my code. My question is, how do I create functions that modify environments according to its arguments? For example:

y <- new.env()
with(y, x <- 1)
f <- function(env,z) {
    with(env, x+z)
}
f(y,z=1)

投掷

Error in eval(expr, envir, enclos) : object 'z' not found

我正在使用环境同时将两组模拟分开(没有重构我为一组实验编写的代码).

I am using environments to keep concurrently two sets of simulations apart (without refactoring my code, which I wrote for a single set of experiments).

推荐答案

最简单的解决方案是在引用对象时使用环境:

The simplest solution is to use the environment when referencing the object:

y <- new.env()
y$x <- 1
f <- function(env,z) {
    env$x+z
}
f(y,z=1)

您还需要将 z 分配给您的环境.

You would need to assign z to your environment as well.

y <- new.env()
with(y, x <- 1)
f <- function(env,z) {
    assign("z", z, envir=env)
    with(env, x+z)
}
f(y,z=1)

另一种选择是附加您的环境,以便现在可以直接使用变量.

One other option would be to attach your environment so that the variables can now be used directly.

y <- new.env()
with(y, x <- 1)
f <- function(env,z) {
    attach(env)
    y <- x + z
    detach(env)
    y
}
f(y,z=1)

后一种解决方案很强大,因为这意味着您可以在新环境中使用任何附加环境中的任何对象,但这也意味着您需要非常小心已全局分配的内容.

This latter solution is powerful because it means you can use any object from any attached environment within your new environment, but it also means that you need to be very careful about what has been assigned globally.

编辑:

这很有趣,我并不完全理解这种行为(即为什么 z 不在 with 调用的范围内).它与最初导致它超出函数范围的环境的创建有关,因为此版本有效:

This is interesting, and I don't entirely understand the behavior (i.e. why z is not in the scope of the with call). It has something to do with the creation of the environment originally that is causing it to be outside the scope of the function, because this version works:

f <- function(z) {
    y <- new.env()
    with(y, x <- 1)
    with(y, x+z)
}
f(y,z=1)

这篇关于使用函数和环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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