[R] NULL or NA for missing function arguments?

Duncan Murdoch murdoch at stats.uwo.ca
Mon Oct 16 15:17:07 CEST 2006


On 10/16/2006 8:47 AM, Hans-Peter wrote:
> Hi,
> 
> I am troubled by the use of NULL or NA to indicate
> missing/non-specified function arguments.
> 
> In the R code that I have looked at, it seems that both forms are used
> (NULL seems to be used more often though). Sometimes both variants are
> in the same declaration, e.g.
> 
> format.default <-
>     function(x, trim = FALSE, digits = NULL, nsmall = 0,
> 	     justify = c("left", "right", "centre", "none"),
> 	     width = NULL, na.encode = TRUE, scientific = NA,
> 	     big.mark = "", big.interval = 3,
> 	     small.mark = "", small.interval = 5, decimal.mark = ".",
> 	     zero.print = NULL, ...)
> 
> Is there a right way? And if both forms are used, how do I know which
> one is right?

As Gabor said, the third way is to give no default, but test missing() 
in the code.

There are differences between the options, but I don't think there's a 
single "right way".  Some differences:

If you want to allow a vector of parameters, some of which are missing 
and some are not, then you'd probably want NA, so that something like 
c(1,2,NA) was possible.

The length of NA is 1, but the length of NULL is 0, so it would be 
harder to expand NULL to the same length as x.  Taking the length of a 
truly missing parameter, or trying to change it, will trigger an error. 
That is, rep(param, length(x)) will work for NA, but not the others. 
It's also convenient to declare an error if length(scientific) != 1.

Using NULL or NA is a little clearer to a user who just takes a quick 
look at the function header, rather than carefully reading the man page, 
to find what parameters are needed.

NA is logical, NULL is NULL.  So in format.default, there could be a 
test is.logical(scientific) which will default to TRUE.

So generally my advice would be:

- Be consistent with similar existing functions.
- Choose what you think will be convenient in current and predicted 
future versions of your function.

Duncan Murdoch



More information about the R-help mailing list