[R] Does anyone else think this might be worth a warning?!?

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Sun Aug 19 14:48:45 CEST 2007


First, note that functions in R match named arguments first, followed by 
the position of the arguments in the call.

Second, have a look at how mean and max are defined

    mean <- function (x, trim = 0, na.rm = FALSE, ...){

    max <- function (..., na.rm = FALSE){

It's the difference in the position of "..." argument or catchall 
argument (sorry, I don't know its formal name) that determines the 
different behaviour. The "..." is often converted to a list internally.

So when you type in mean(1,1,2), it is treated as
  "mean( x=1, trim=1, na.rm=2 )".

and when you type in max(1,1,2), it is treated as
  "max( as.list(1,1,2), na.rm = FALSE )"


However, you do raise a good point. Reading mean.default(), I do not see 
how and when the "..." argument in mean() comes to play. Perhaps 
redefine mean to be mean <- function (..., trim = 0, na.rm = FALSE) so 
that it is similar to max, sum, range etc.

But there might be a philosopphical counter argument for this as well. 
Functions like mean() and sd() are supposed to summarise a single vector 
whereas max, sum, range can work on several vectors by concatenating 
them into a single list. Consider max( c(1,2,3), c(2,3,4) ).

Regards, Adai



Matthew Walker wrote:
> Hi,
> 
> I was *very* surprised by this little trick for new players: mean() only 
> considers its first argument!
> 
>  > mean(1,1,2)
> [1] 1
>  > mean(2,1,1)
> [1] 2
> 
> 
> I found this very different behaviour to max():
> 
>  > max(1,1,2)
> [1] 2
>  > max(2,1,1)
> [1] 2
> 
> 
> 
> Perhaps this is the wrong list to ask, but does anyone else think this a 
> little on the interesting side?  Is it not possible to detect a first 
> argument of length one in the presence of other un-named arguments and 
> at least produce a warning?
> 
> 
> Cheers,
> 
> 
> Matthew
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 
>



More information about the R-help mailing list