Finding the code for a ‘hidden’ function in R

If you want to understand what a certain function is doing, or you want to adapt it, you can type in the function without bracket on the command line. However, sometimes functions are ‘hidden’.

You can use methods(function), which will give you the methods for that function (see ?methods for more detailed information). Take for example the kruskal.test.

kruskal.test

function (x, ...)
UseMethod("kruskal.test")
<environment: namespace:stats>

Next, if we type:

methods(kruskal.test)

[1] kruskal.test.default* kruskal.test.formula*
Non-visible functions are asterisked

Thus, there are two methods, kruskal.test.default and kruskal.test.formula. Let’s try the first one:

stats:::kruskal.test.default

This gives the underlying code for the kruskal.test.default:

function (x, g, ...)
{
    if (is.list(x)) {
        if (length(x) < 2L)
            stop("'x' must be a list with at least 2 elements")
        DNAME <- deparse(substitute(x))
        x <- lapply(x, function(u) u <- u[complete.cases(u)])
.
.
.
}

I am just copying first lines of the code, that leaves something for you to find out ;-). See also this email threat on the R help mailing list, from which I got the example.

Advertisements

2 thoughts on “Finding the code for a ‘hidden’ function in R

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s