[R] 'mean' function

Duncan Murdoch murdoch at stats.uwo.ca
Fri Sep 30 22:58:26 CEST 2005


On 9/30/2005 5:57 PM, Lisa Wang wrote:
> Hello,
> 
> Could you please let me know how to see the "mean" function in R  . The
> following is what I see when type in "mean" and "enter"
> 
> mean
> function (x, ...)
> UseMethod("mean")
> <environment: namespace:base>
> 
> I would like to see how the function is writen.

The "UseMethod" part tells you that mean is a generic function.  There 
are lots of different implementations, depending on what sort of thing x 
is.

You can see the default one using "mean.default":

 > mean.default
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(as.numeric(NA))
     }
     if (na.rm)
         x <- x[!is.na(x)]
     trim <- trim[1]
     n <- length(x)
     if (trim > 0 && n > 0) {
         if (is.complex(x))
             stop("trimmed means are not defined for complex data")
         if (trim >= 0.5)
             return(median(x, na.rm = FALSE))
         lo <- floor(n * trim) + 1
         hi <- n + 1 - lo
         x <- sort(x, partial = unique(c(lo, hi)))[lo:hi]
         n <- hi - lo + 1
     }
     if (is.integer(x))
         sum(as.numeric(x))/n
     else sum(x)/n
}
<environment: namespace:base>


Duncan Murdoch




More information about the R-help mailing list