这里的useMethod是什么意思?
R 的一大优点是,如果我输入函数名称,我就可以看到其实现。但这让我递归地感到困惑:
> library(xts)
> align.time
function (x, ...)
{
UseMethod("align.time")
}
<environment: namespace:xts>
x是一个XTS对象,所以这是否意味着它将调用XTS的align.time方法...但这就是我正在看的! (输入 xts::align.time
会给出完全相同的响应。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,您正在寻找函数
xts:::align.time.xts
。更长的答案是,您可以通过调用
methods
来查找align.time
存在哪些方法:这告诉您有一个方法
align.time.xts< /code> 不是从命名空间导出的。此时您可能会猜测它可以在
xts
包中找到,但是您可以使用getAnywhere
来确认:您当然可以直接读取源代码,但是由于该函数未导出,因此您需要使用
package:::function
(即三个冒号):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 callingmethods
: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 packagexts
, but you can confirm that withgetAnywhere
: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):align.time()
是从 xts 命名空间导出的,因此xts::align.time
和align.time
是同一件事。您需要注意,包中提供了一个align.time()
方法,用于类"xts"
的对象,并且该方法不是从命名空间导出的(它是刚刚注册为 S3 方法):当您将
"xts"
对象传递给align.time()
时,就会调用此方法。当您调用
align.time()
时,UseMethod()
将搜索并调用适当的"align.time"
方法,如果对于作为第一个参数提供的对象类可用。UseMethod
正在做你认为它正在做的事情,你只是通过以两种不同的方式查看同一个函数(通用函数)而混淆了自己。align.time()
is exported from the xts namespace, soxts::align.time
andalign.time
are the same thing. You need to note that there is analign.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):It is this method that is being called when you pass an
"xts"
object toalign.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.