[R] passing a function as an argument using lazy loading

Duncan Murdoch murdoch at stats.uwo.ca
Sun Mar 14 22:09:51 CET 2010


On 14/03/2010 4:33 PM, Mark Heckmann wrote:
> Yes. I meant lazy evaluation :)
> I will try to clarify what I mean.
> 
> I have a function foo and in its arguments use a reference to another  
> argument, like:
> foo <- function(x=y, y=x)
> 
> I would like to specify the function in a way it is possible to change  
> the way the argument y is evaluated.
> e.g.:
> 
>   foo(x=3, y=2*x)   # this won't work
> 
> I want the above to be equivalent to
> 
> foo <- function(x=y, y=2*x)
> 
> But I to not want to respecify foo() but rather pass the a new  
> function during the call (here 2*x) that will be used to calculate y.
> This problem arised in the following situation:

There may be a way to do this, but it would involve very unreadable 
contortions.  Default values for parameters are evaluated in the context
of the function evaluation (since they are set by the function author, 
who knows what's going on there), whereas explicitly specified parameter 
values are evaluated in the context of the caller (since they are set by 
the caller, who knows what's going on *there*).  Subverting this 
sensible scheme might be possible, but it isn't sensible.

If you want to take over authorship of the function, you can change it, 
and then things will be evaluated where you say. For example, if you're 
given foo as above, you can create myfoo as follows:

myfoo <- foo
formals(myfoo)$y <- quote(2*x)


> 
> foo <- function(x=background, y=checkcolor(background))
> 
> Here a background color is given and checkcolor() will return a color  
> for the text that gives a good contrast to the background color.
> Now, I would like to change the function used for this step, like:
> 
> foo <- function(x=background, y=checkcolorNew(background))
> 
> but to do this within the call: The solution is use know is the  
> following:
> 
> foo <- function(x=y, y=fun(x), fun=function(x) x*2) cat (x,y)
> foo(2)
> and with modified funtion to calculate y:
> foo(2, , fun=function(x) 20*x)
> 
> So I use the extra argument fun. Before I tried to do it without the  
> extra argument, though I still do not know if it is possible.
> If it is basically was my question if it is.

I think you'll get what you want with

  foo <- function(x=background, y=checkcolor(background)) { ... }

myfoo <- foo
formals(myfoo)$y <- quote(checkcolorNew(background))

Duncan Murdoch



More information about the R-help mailing list