Evaluate an expression within an environment inside a function
r
Solution
Try this:
> foo <- function(env, fun) eval(substitute(args(fun)), env)
> foo(guy, stuff)
function (x, ...)
NULL
ADDED. Regarding the comment below here is an example where `zz` is not in `env` or its ancestors (but is in `foo2` and in `f`, the caller of `foo2`) and it does give a not found error as the comment wished:
> foo2 <- function(env, fun, zz = 1) eval(substitute(fun), env)
> f <- function() { zz <- 100; foo2(guy, zz+1) }
> f()
Error in eval(expr, envir, enclos) : object 'zz' not found
Problem
Consider: ``` guy <- new.env(FALSE) guy$stuff <- mean guy$lib <- library guy$stole_this_data <- mtcars ls(guy) ``` How can I evaluate an expression within an environment inside a function? For instance I can do `with(guy, args(stuff))` to the below and return: ``` > with(guy, args(stuff)) function (x, ...) NULL ``` But within a functon: ``` foo <- function(env, fun) { with(env, args(fun)) } foo(guy, stuff) ## > foo(guy, stuff) ## Error in args(fun) : could not find function "stuff" ```