1

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)

Community
  • 1
  • 1
ytsaig
  • 3,267
  • 3
  • 23
  • 27

0 Answers0