R - evaluate nested function call in a deserialized environment

守給你的承諾、 提交于 2020-01-14 02:53:10

问题


I am trying to run an already existing chunk of R code in a sandbox-ed fashion, by saving the global environment (containing functions and data) to a file, then loading it into a new environment (not the global environment) and evaluating a function call within that environment. However, I'm running into trouble with functions calling other functions in the environment. Here's an example:

f1 <- function(x) x*2
f2 <- function(y) f1(y) + 1
save(list=ls(), file="env.RData")
rm(list=ls())

jobenv <- new.env(parent=globalenv())
load("env.RData", envir=jobenv)
expr <- quote(f2(3))
eval(expr, envir=jobenv)

which fails:

Error in f2(3) : could not find function "f1"

whereas attaching the environment first works:

> attach(jobenv)
> eval(expr)
[1] 7

Is there a way to successfully evaluate a nested function call in the deserialized environment other than using attach?

(This question was forked from R - Evaluate a nested function in an environment based on commenter's suggestion)

来源:https://stackoverflow.com/questions/17733323/r-evaluate-nested-function-call-in-a-deserialized-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!