[R] do.call and environments

Tony Plate tplate at blackmesacapital.com
Wed Mar 10 18:56:28 CET 2004


The reason in your example that fx() doesn't find 'x' is that the lexical 
scope of fx() does not include 'x'.  So, this is what must be fixed, in one 
way or another.

One simple way to make your example work is to define fx() in a place where 
its lexical scope includes the variables you want it to see:

 > f <- function(fun, xx) {
+   x <- xx
+   fxx <- function() do.call(fun, list(y=3))
+   fx <- function(y) print(x*y)
+   fxx()
+ }
 > x # verify that x is not a global variable!
Error: Object "x" not found
 > f("fx", 13)
[1] 39
 >

Another way, that is probably more suited to what you want (since it sounds 
like you don't have control over where fx() is defined), is to make a local 
copy of fx(), and change its environment:

 > fx <- function(y) print(x*y)
 >
 > f <- function(fun, xx) {
+   x <- xx
+   fxx <- function() do.call(fun, list(y=3))
+   fx <- fx
+   environment(fx) <- environment()
+   fxx()
+ }
 > x # verify that x is not a global variable!
Error: Object "x" not found
 > f("fx", 13)
[1] 39
 >

I suspect there is also some way to do this using eval() and its envir= 
and/or enclos= arguments, but I couldn't get anything like this to work.

The above solutions were generated by manual genetic programming (i.e., 
trial and error), so they may not be particularly good or 
elegant.  However, I'm sure that others will point out both any problems 
with these suggestions and some better solutions!

hope this helps,

Tony Plate

At Wednesday 09:05 AM 3/10/2004, Thomas Petzoldt wrote:
>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
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list