[R] The evaluation of optional function arguments

Sietse Brouwer sbbrouwer+r-help at gmail.com
Mon Oct 20 12:48:46 CEST 2008


Hullo all,

 [***recap of the question: passing bar=harry fails when bar is among
 the ... args.]
 callTimes <- function(tom, harry) {

    timesDefineInside(foo=tom, bar=harry
 }

timesDefineInside <- function(foo, ...) {
    foo * bar
 }
 callTimes(3, 4)
 # Error: object "bar" not found
 [***end recap]


 On 20/10/2008, hadley wickham <h.wickham at gmail.com> wrote:
 > Why don't you want to do this?
 >
 >  timesDefineInside <- function(foo, bar...) {
 >    foo * bar
 >  }


You're right that's it the obvious solution — the thing is, I'm
 hacking on somebody else's function, and in the interim I want to
 maintain backward compatibility. Part of that is expecting the same
 set of formals, so any extra arguments (in this case, 'bar' is
 actually 'experimentalMode') have to come throught the dots.


 Kaom Te wrote:
 > Try this for timesDefineInside:
 > timesDefineInside <- function(foo, ...) {
 >    extra.args <-   list(...)
 >    bar <- extra.args$bar
 >    foo * bar
 > }


Ah, that works! Apparently, there's a difference between
 list(...) and
 match.call(expand.dots=FALSE)$...   # wrapped in eval() or not.
 That makes sense, though, as the first will have evaluated bar=harry
 at the moment of calling, within the calling function, while the
 second will evaluated bar=harry within the called function. I think.

 Thank you both very much; and thanks, too, to Martin Morgan, who
 replied off-list pointing me at
 bar <- eval.parent(match.call()$bar)
 .

 Grateful regards,

 Sietse
 Sietse Brouwer


 --

Sietse Brouwer -- sbbrouwer at gmail.com -- +31 6 13456848
 Wildekamp 32 -- 6721 JD Bennekom -- the Netherlands
 MSN: sietse at gawab.com -- ICQ: 341232104



More information about the R-help mailing list