What does useMethod mean here?

r xts
Darren Cook picture Darren Cook · Nov 25, 2011 · Viewed 10.3k times · Source

One of the kool things about R is if I type the function name I get to see the implementation. But this one is confusing me, recursively:

> library(xts)
> align.time
function (x, ...) 
{
    UseMethod("align.time")
}
<environment: namespace:xts>

x is an XTS object, so doesn't that mean it will call the XTS align.time method... but that is what I'm looking at! (Typing xts::align.time gives exactly the same response.)

Answer

Andrie picture Andrie · Nov 25, 2011

The short answer is that you are looking for the function xts:::align.time.xts.

The longer answer is that you can find which methods exist for align.time by calling methods:

> methods(align.time)
[1] align.time.POSIXct* align.time.POSIXlt* align.time.xts*    

   Non-visible functions are asterisked

This tells you that there is a method align.time.xts that is not exported from the namespace. At this point you can probably guess that it can be found in package xts, but you can confirm that with getAnywhere:

> getAnywhere("align.time.xts")
A single object matching 'align.time.xts' was found
It was found in the following places
  registered S3 method for align.time from namespace xts
  namespace:xts
with value

function (x, n = 60, ...) 
{
    if (n <= 0) 
        stop("'n' must be positive")
    .xts(x, .index(x) + (n - .index(x)%%n), tzone = indexTZ(x), 
        tclass = indexClass(x))
}
<environment: namespace:xts>

You can, of course, read the source directly, but since the function is not exported, you need to use package:::function (i.e. three colons):

> xts:::align.time.xts
function (x, n = 60, ...) 
{
    if (n <= 0) 
        stop("'n' must be positive")
    .xts(x, .index(x) + (n - .index(x)%%n), tzone = indexTZ(x), 
        tclass = indexClass(x))
}
<environment: namespace:xts>