What does useMethod mean here?

2019-03-18 03:07发布

问题:

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.)

回答1:

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>


回答2:

align.time() is exported from the xts namespace, so xts::align.time and align.time are the same thing. You need to note that there is an align.time() method for objects of class "xts" provided in the package and that is not exported from the namespace (it is just registered as an S3 method):

> 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>

It is this method that is being called when you pass an "xts" object to align.time().

When you call align.time() UseMethod() sets up the search for and call of the appropriate "align.time" method, if available, for the class of object supplied as the first argument. UseMethod is doing exactly what you think it is doing, you have just confused yourself by looking at the same function (the generic) in two different ways.



标签: r xts