相当于 within(), attach() 等在一个环境中工作?

equivalent of within(), attach() etc. for working within an environment?

我想在搜索路径中添加一个环境,并在有限的代码块中修改该环境中的变量值,而不必在每次引用变量时都指定环境名称:对于例如,给定环境

ee <- list2env(list(x=1,y=2))

现在我想做一些事情

ee$x <- ee$x+1
ee$y <- ee$y*2
ee$z <- 6

但没有将 ee$ 附加到所有内容(或使用 assign("x", ee$x+1, ee) ... 等):类似于

in_environment(ee, {
    x <- x+1
    y <- y+2
    z <- 6
})

我能想到的大多数解决方案都是明确设计的而不是来修改环境,例如

我想我可以通过

使用 Introduction to R 第 10.7 节中描述的闭包
clfun <- function() {
   x <- 1
   y <- 2
   function(...) {
      x <<- x + 1   
      y <<- y * 2
   }
}
myfun <- clfun()

这看起来很复杂(但我想还不错?)但是:

我是不是遗漏了一些显而易见的惯用语?

感谢@Nuclear03020704!我认为 with() 是我一直想要的;我错误地假设它也会创建环境的本地副本,但只有当 data 参数 还不是环境 .

时才会这样做
ee <- list2env(list(x=1,y=2))
with(ee, {
    x <- x+1
    y <- y+2
    z <- 6
})

完全符合我的要求。


刚刚有了另一个想法,它似乎也有一些缺点:使用大的 eval 子句。我不会把我的问题列成一长串不令人满意的解决方案,而是将其添加到这里。

myfun <- function() {
    eval(quote( {
        x <- x+1
        y <- y*2
        z <- 3
    }), envir=ee)
}

这似乎确实有效,但也非常 weird/mysterious!我不想考虑向使用 R 不到 10 年的人解释它......我想我可以写一个 in_environment() 基于此,但我必须非常小心才能正确捕获表达式没有评估它...

with()呢?来自 here

with(data, expr)

data is the data to use for constructing an environment. For the default with method this may be an environment, a list, a data frame, or an integer.

expr is the expression to evaluate.

with is a generic function that evaluates expr in a local environment constructed from data. The environment has the caller's environment as its parent. This is useful for simplifying calls to modeling functions. (Note: if data is already an environment then this is used with its existing parent.)

Note that assignments within expr take place in the constructed environment and not in the user's workspace.

with() returns value of the evaluated expr.


ee <- list2env(list(x=1,y=2))
with(ee, {
    x <- x+1
    y <- y+2
    z <- 6
})