Desktop Survival Guide
by Graham Williams


Sometimes you may want to know how a function is implemented. R is also an object oriented functional language and so what method is called depends on the type of the argument. This can be illustrated with the mean function. We can try to determine its implementation:

> mean
function (x, ...)
<environment: namespace:base>

The UseMethod part indicates that mean is a generic function, possibly with many different implementations. So to find out what function our call might actually be dispatched to we can use the methods function:

> methods(mean)
[1] mean.Date       mean.default    mean.difftime  
[5] mean.POSIXct    mean.POSIXlt

In there we see mean.default which will be dispatched to if no other methods are appropriate. So we might be interested in its definition:

> 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")
    if (na.rm)
        x <- x[!]
    trim <- trim[1]
    n <- length(x)
    if (is.integer(x))
    else sum(x)/n
<environment: namespace:base>

We might also be interested in the function which will be dispatched to if the argument is a data.frame:

function (x, ...) 
sapply(x, mean, ...)
<environment: namespace:base>

So this function does no more than to apply the mean function to the columns of the data frame, but is quite useful.

Note that the function getAnywhere may also be useful in obtaining the definition of objects.

Copyright © Togaware Pty Ltd
Support further development through the purchase of the PDF version of the book.
The PDF version is a formatted comprehensive draft book (with over 800 pages).
Brought to you by Togaware. This page generated: Sunday, 22 August 2010