[R] do.call and environments

Liaw, Andy andy_liaw at merck.com
Wed Mar 10 19:03:14 CET 2004


Seems to me what you want is dynamic scoping: `x' is not defined in `fx'.
You want `x' to be found in the scope of the function(s) that calls `fx',
rather than the environment where `fx' is defined.  I was told (thanks,
Robert!) that that is a very bad idea:  as the author of `fx', you want some
assurance of what `x' might be.  This is done via R's lexical scope.  With
dynamic scope, there is absolutely no way to do that.  For example, I might
write a function `g' that define `x' as a character, or a data frame, or a
list, or an `lm' object, or a connection, ....  How would you write `fx' to
deal with that nightmare if you have dynamic scope?

Andy

> From: Thomas Petzoldt
> 
> 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
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}




More information about the R-help mailing list