R - 评估环境中的嵌套函数 [英] R - Evaluate a nested function in an environment
问题描述
我试图以沙盒编辑的方式运行大量R代码,方法是将所有必需的依赖项(函数和数据)加载到新环境中并评估该环境中的表达式。但是,我在调用环境中其他函数的函数时遇到了麻烦。这里有一个简单的例子:
I am trying to run a chunk of R code in a sandbox-ed fashion, by loading all the necessary dependencies (functions and data) into a new environment and evaluating an expression within that environment. However, I'm running into trouble with functions calling other functions in the environment. Here's a simple example:
jobenv <- new.env(parent=globalenv())
assign("f1", function(x) x*2, envir=jobenv)
assign("f2", function(y) f1(y) + 1, envir=jobenv)
expr <- quote(f2(3))
使用 eval
on expr
因为 f2
找不到 f1
Using eval
on expr
fails since f2
can't find f1
> eval(expr, envir=jobenv)
Error in f2(3) : could not find function "f1"
显式附加环境工作
> attach(jobenv)
> eval(expr)
[1] 7
我可能错过了一些明显的东西,但我无法找到可用的 eval
调用的任何排列组合。有没有一种方法可以在不附加环境的情况下获得相同的效果?
I'm probably missing something obvious, but I couldn't find any permutation of the eval
call that works. Is there a way to get the same effect without attaching the environment?
推荐答案
有很多方法可以做到这一点,但我有点像这样:
There are a number of ways of doing this, but I kind of like this one:
jobenv <- new.env(parent=globalenv())
local({
f1 <- function(x) x*2
f2 <- function(y) f1(y) + 1
}, envir=jobenv)
## Check that it works
ls(jobenv)
# [1] "f1" "f2"
local(f2(3), envir=jobenv)
# [1] 7
eval(quote(f2(3)), envir=jobenv)
# [1] 7
这篇关于R - 评估环境中的嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!