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))
Using eval
on expr
fails since f2
can't find f1
> eval(expr, envir=jobenv)
Error in f2(3) : could not find function "f1"
whereas explicitly attaching the environment works
> attach(jobenv)
> eval(expr)
[1] 7
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?