[R] Can you recover default argument values of a function?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Dec 27 09:48:23 CET 2007


Talbot Katz wrote:
> Thank you, that's just what I wanted.  By the way, I found an interesting "gotcha" that can occur with expression arguments:
>
>   
>> x = 7
>> z = 2
>> mxy <- function( x = 4, y = x + z ) { return(x*y) }
>> eval( formals( mxy )[[1]] )
>>     
> [1] 4
>   
>> eval( formals( mxy )[[2]] )
>>     
> [1] 9
>   
>> mxy()
>>     
> [1] 24
>   
>> mxy( eval( formals( mxy )[[1]] ), eval( formals( mxy )[[2]] ) )
>>     
> [1] 36
>   
>
> The problem is "confusion" about whether the "x" in the second argument expression refers to the first argument, or the environment variable.  When the function is evaluated, the argument value of x is used, but when the argument is evaluated (using eval and formals) the environment value of x is used.  This is a reasonable choice, and mixing up arguments and environment variables in a function definition probably should be considered bad programming.
>
>   
Yes, argument expressions are always evaluated in the evaluation frame 
of the function. Sometimes they even refer to quantities computed well 
into the evaluation of the function, like "p" in

 > anova.mlm
function (object, ..., test = c("Pillai", "Wilks", "Hotelling-Lawley",
    "Roy", "Spherical"), Sigma = diag(nrow = p), T = Thin.row(proj(M) -
    proj(X)), M = diag(nrow = p), X = ~0, idata = data.frame(index = 
seq_len(p)))
.....
        p <- ncol(SSD(object)$SSD)
.....

(p is the dimension of the covariance matrix, aka the number of columns 
in the response matrix. It makes no sense to pass it as a separate 
parameter, and obtaining it via extraction from "object" is kludgy and 
inefficient as it is needed three times.)

Another gotcha is if you modify a variable referred to in a default 
expression before using the expression.

The upshot is that you pretty much cannot in general figure out what the 
argument defaults will evaluate to without actually running the function.


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list