useMethod在这里意味着什么?

时间:2011-11-25 09:45:47

标签: r xts

关于R的一个关键是,如果我输入函数名称,我会看到实现。但是这个让我感到困惑,递归地说:

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

x是一个XTS对象,所以这并不意味着它将调用XTS align.time方法......但这就是我正在看的东西! (键入xts::align.time会给出完全相同的响应。)

2 个答案:

答案 0 :(得分:24)

简短的回答是,您正在寻找功能xts:::align.time.xts

答案越长,您可以通过调用align.time找到methods存在哪些方法:

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

   Non-visible functions are asterisked

这告诉您没有从命名空间导出的方法align.time.xts。此时您可能会猜到它可以在包xts中找到,但您可以使用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>

当然,您可以直接阅读源代码,但由于未导出该函数,您需要使用package:::function(即三个冒号):

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

答案 1 :(得分:7)

align.time()是从 xts 命名空间导出的,因此xts::align.timealign.time是相同的。您需要注意,包中提供的类align.time()的对象有"xts"方法,并且不从命名空间导出(它只是注册为S3方法):

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

"xts"对象传递给align.time()时,正在调用此方法。

当您致电align.time()时,UseMethod()设置搜索和调用适当的"align.time"方法(如果可用),作为第一个参数提供的对象类。 UseMethod正在做你认为正在做的事情,你只是以两种不同的方式看待同一个函数(泛型)而让自己感到困惑。

相关问题