在 R 中创建作用域表达式以清理中间变量

Creating scoped expressions in R to clean intermediate variables

在 R 中创建范围表达式的合适方法是封装命令,其变量在评估后被消除。

我现在使用的方式涉及使用 with():

> with(data.frame(), {foo <- 5; bar <- 6; foo + bar})
[1] 11
> foo
Error: object 'foo' not found

但这显然是一个黑客。

(顺便说一句,如果您将 c() 而不是 data.frame() 传递给 with(),新变量实际上最终会出现在父环境中;不知道为什么)

您可以使用 match.callexpressioneval:

> no_effect <- function(...){
+   .call <- match.call()
+   .call[[1]] <- as.symbol("expression")
+   expr <- eval(.call)
+   
+   eval(expr, list(), enclos = parent.frame())
+ }
> 
> no_effect({foo <- 5; bar <- 6; foo + bar})
[1] 11
> foo
Error: object 'foo' not found

解决方案与您已经写的接近。

local({foo <- 5; bar <- 6; foo + bar})

local({foo <- 5 bar <- 6 foo + bar})

来自?local(我的重点)

local evaluates an expression in a local environment. It is equivalent to evalq except that its default argument creates a new, empty environment. This is useful to create anonymous recursive functions and as a kind of limited namespace feature since variables defined in the environment are not visible from the outside.