[R] do.call and environments

Gabor Grothendieck ggrothendieck at myway.com
Wed Mar 10 17:55:52 CET 2004



Try this:


x <- 7
fx <- function(y) print(x*y)
f <- function(fun, x) {
	myfx <- eval(parse(text=deparse(fun)))
	myfx(3)
}
f(fx,2)  # uses 2, not 7, for x

This creates a new function myfx which has the same functionality
as fx but is created in the body of f and therefore has that body
as its environment -- with the result that it finds the x arg
to f.  myfx is not fx (it just has the same functionality) so 
fx's environment is irrelevant.

Just one caveat.  If fx is recursive it should use Recall
to call itself.  See ?Recall 



---
Hello,

I want to call a function "fx" given by name, where some "global" 
variables (in the environment of fx) are passed to the function. For 
compatibility reasons I cannot modify the parameter list of fx and I 
want to avoid setting variables in the global environment (e.g. via <<-)

Is there a way, how to do this?

Thomas P.

The example:

fx <- function(y) print(x*y)

f <- function(fun, xx) {
   fxx <- function() {do.call(fun, list(y=3))}
   x <- x
   fxx()
}

f("fx", 13)

## does not work, because fx does not find x




More information about the R-help mailing list