0

If I write a simple r function

foofunction<-function(x,y)
{
...
}

and call it like so with a "silly_option" argument that does not exist in the function definition:

foofunction(x=5,y=10,silly_option=6)

Then I get an error, as expected:

unused argument (silly_option = 6)

On the other hand, why doesn't this call return a similar error?

mean(c(1,2,3),silly_option=6)

Is mean() silently ignoring it or doing something with it?

curious_cat
  • 805
  • 2
  • 9
  • 24

1 Answers1

2

Typing getAnywhere("mean.default") from the R console reveals the source code for mean():

function (x, trim = 0, na.rm = FALSE, ...) 
{
    if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
        warning("argument is not numeric or logical: returning NA")
        return(NA_real_)
    }
    # ... more code
}

The mean.default() function in the base package has a signature which includes varargs, indicated by the ellipsis ... as the last parameter in the signature.

So, I think that mean() is silently ignoring your extra parameter.

Read here for more information on R's ellipsis function capability.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    Just and addition-- if one defines foofunction as `foofunction<-function(x,y,...)` it would stop throwing the unused argument error as well. – R.S. Mar 09 '17 at 07:22
  • @R.S. So as a matter of good design which is the best strategy? To throw an error or to silently ignore excess arguments? i.e. What advantage does the mean() function get by ignoring excess arguments? – curious_cat Mar 09 '17 at 07:37
  • @curious_cat Sometimes it isn't a matter of best strategy. If a function accepts variable arguments, then unused ones, or even bad ones, can be passed and the function won't roll over. In other words, an artifact of using varargs for a legitimate reason is that unused parameters can also be passed. – Tim Biegeleisen Mar 09 '17 at 07:43
  • @curious_cat the use of `...` is not to mute error messages, but to enable generic functions that are customised by different classes. When one calls an R function, different versions are called depending on the type of objects involved. With this scheme a `mean()` for Posixct can easily accept a `timezone` argument. And even when we don't use classes, I personally find it a great tool for prototyping. Using it in final code would look like not enough effort was put into design, and would also make documentation a mess – R.S. Mar 09 '17 at 09:51