Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate an expression within an environment inside a function

Tags:

r

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"
like image 517
Tyler Rinker Avatar asked Jan 06 '14 21:01

Tyler Rinker


2 Answers

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
like image 160
G. Grothendieck Avatar answered Oct 07 '22 13:10

G. Grothendieck


If you want to continue to use the with construct, this is an alternative:

foo <- function(env, fun) {
      fun <- substitute(fun)
      eval(bquote(with(env, {
        .(fun)
      })))
}
like image 29
Matthew Plourde Avatar answered Oct 07 '22 14:10

Matthew Plourde