简体   繁体   English

将表达式评估为给定环境

[英]Evaluate an expression into a given environment

I would like to call a function inside a given environment so that the execution of the function does not mess the global environment. 我想在给定的环境中调用一个函数,以便函数的执行不会弄乱全局环境。 I have something like that: 我有这样的事情:

f <- function() { x <<- 5 }
e <- new.env()
evalq(f(), envir = e)

I want to evaluate f() inside the environment e , but it seems it does not work since the variable x is accessible from the global env instead of the env e . 我想在环境e内评估f() ,但是似乎不起作用,因为可以从全局env而不是env e访问变量x I mean I want to access x by typing e$x , not x . 我的意思是我要访问x通过输入e$x ,而不是x

I tried to build the function f inside e like this: 我试图像这样在e内部构建函数f

e <- new.env()
evalq(f <- function() { x <<- 5 }, envir = e) 
evalq(f(), envir = e)

But it still does not work, x is in the global env, not in e . 但是它仍然不起作用, x在全局env中,而不在e


EDIT with more informations: 编辑更多信息:

From the answers I received, I understand that <<- should not be used. 从我收到的答案中,我知道不应使用<<- The problem is that, in practice, I don't know what f is, since it is obtained by sourcing a file which is downloaded through a shiny app. 问题在于,实际上,我不知道f是什么,因为它是通过获取通过闪亮应用下载的文件而获得的。 The purpose of this app is to evaluate a classifier function f written by students. 该应用程序的目的是评估学生编写的分类器函数f So in case they used the <<- operator in their function, I don't want to pollute my global env (which seem to be impossible from the description of the <<- operator). 因此,如果他们在函数中使用了<<-运算符,我就不想污染我的全局环境(从<<-运算符的描述看来这是不可能的)。

I think I could remove the potentially created variables with something like 我想我可以用类似的方法删除潜在创建的变量

vars <- ls()
evalq(f(), envir = e)
new_vars <- ls()
rm(list = new_vars[!new_vars %in% vars])

But is there a better solution? 但是有更好的解决方案吗?

You can use assign to define the environment where the object should be created: 您可以使用assign定义应在其中创建对象的环境:

e <- new.env()
f <- function() {
    assign("x", 5, envir = e)
}
f()

x
# Error: object 'x' not found
e$x
# [1] 5

As @lmo says, the simplest way would be to not use <<- to do this. 正如@lmo所说,最简单的方法是不使用<<-来做到这一点。 Also, the function runs in its own environment so if you were to use <- you would need to assign the output of the function to a variable (otherwise it is only created in the f 's temporary environment. Something like this would work: 另外,该函数在其自己的环境中运行,因此,如果要使用<- ,则需要将函数的输出分配给变量(否则,它仅在f的临时环境中创建。类似这样的方法将起作用:

f <- function() { x <- 5 }
e <- new.env()
evalq(x <- f(), envir = e)

e$x
#[1] 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM