Skip to content
Prev 325930 / 398503 Next

do.call environment misunderstanding

On 25/06/2013 9:32 AM, Dan Murphy wrote:
do.call will construct the expression f(), then evaluate it in e. It 
will try to look up f there, and not finding it, will go to the parent 
environment and find it.

When evaluating the function, the environment in which it was evaluated 
is used for looking up arguments, but f() has none, so e is not used at 
all.  R will use the environment attached to f, which is the global 
environment, since you created f by evaluating its definition there.

To get what you want, you could use the sequence

e <- new.env()
e$x <- 2
f <- function() x^2
environment(f) <- e
f()

An alternative way to do the 3rd and 4th lines is

f <- with(e, function() x^2)

because that would evaluate the creation of f within e.

A third approach (which might be the nicest one, depending on what else 
you are doing) is never to name e:

f <- local({
   x <- 2
   function() x^2
})

Duncan Murdoch