[R] sub-function default arguments

Duncan Murdoch murdoch at stats.uwo.ca
Fri Jul 13 02:05:50 CEST 2007

On 12/07/2007 7:23 PM, Talbot Katz wrote:
> Hi.
> I have defined a function, f1, that calls another function, f2.  Inside f1 
> an intermediate variable called nm1 is created; it is a matrix.  f2 takes a 
> matrix argument, and I defined f2 (schematically) as follows:
> f2<-function(nmArg1=nm1,...){nC<-ncol(nmArg1); ... }
> so that it expects nm1 as the default value of its argument.  f1 is defined 
> (schematically) as:
> f1<-function(...){result1<-f2(); ... }
> When I ran f1 I got the following error message:
> Error in ncol(nmArg1) : object "nm1" not found.
> If I redefine f1 schematically as:
> f1<-function(...){result1<-f2(nmArg1=nm1); ... }
> it runs okay.  If I have nm1 defined outside of f1 and I run "result1<-f2()" 
> it also runs okay.  So f2 doesn't seem to pick up the default argument value 
> inside the function f1, even when the default argument is defined inside f1. 
>   Is there a way to have the subfunction default arguments recognized inside 
> of a function (perhaps a better protocol for using defaults than what I 
> did?), or do I just have to spell them out explicitly?

Defaults to arguments are evaluated in the evaluation frame of the 
function being called, f2 in your case.  Since nm1 is meaningless within 
f2, you get the error.

If you want nm1 to be meaningful within f2, you could define f2 within 
f1, e.g.

   nm1 <- something
   f2 <- function (...) {}

(which is the best way to do it), or you could explicitly manipulate the 
environment of f2 (which is an ugly way), or you could store nm1 in some 
place that's visible to both f1 and f2 and use <<- when you set it from 
within f1 (another ugly way, but sometimes less ugly than my second 

Duncan Murdoch

More information about the R-help mailing list