关于UseMethod搜索机制的困惑

时间:2012-05-09 15:10:05

标签: r dispatch

我试图找出R UseMethod一旦找出它寻找的方法(即函数MyGeneric(x)用类MyClass x调用的函数MyGeneric.MyClass) 具体来说,涉及哪些环境?

我已阅读R语言手册的“5.3 Method Dispatching”和“5.4 UseMethod”部分,该部分未指定搜索机制。 UseMethod的R-Help页面提供了一个线索:

...UseMethod and NextMethod search for methods in two places: 
first in the environment in which the generic function is called, 
and then in the registration data base for the environment 
in which the generic is defined (typically a namespace)

但这并没有加起来(在我脑海里=)。这是一个具体的例子:

library( xts )
as.matrix  # shows UseMethod("as.matrix")
methods("as.matrix") # shows as.matrix.xts.  * indicates non-visible
showMethods("as.matrix")  # says <not an S4 generic function>
data(sample_matrix)
as.matrix( as.xts(sample_matrix) ) # how does R find as.matrix.xts??  its not exported!

as.matrixnamespace:base中定义。如果R要使用该环境或调用环境(R_GlobalEnv),则无法找到as.matrix.xts,因为它未导出。如果xts中的函数调用as.matrix,则调用环境似乎有效,因为as.matrix.xts将在调用环境中。我错过了什么?

2 个答案:

答案 0 :(得分:3)

你不是那么仔细阅读。它说“注册数据库”存储在泛型的环境(命名空间)中,而不是方法本身。如果是base::as.matrix

> grep("as.matrix",ls(base:::.__S3MethodsTable__.), value=TRUE)
[1] "as.matrix.dist"   "as.matrix.raster" "as.matrix.xts"    "as.matrix.zoo"

答案 1 :(得分:1)

除了Joshua的洞察力,这增加了我的知识....在一个装载的NAMESPACE中与出口不同。您可以使用以下任一方法看到as.matrix.xts函数:

 getAnywhere(as.matrix.xts)
 xts:::as.matrix.xts

尝试输入

search()

我在SO或rhelp上也看到了一个函数,它会显示R解释器的函数调用搜索路径,但此刻我似乎无法找到它。这会产生一个相当长的函数名列表:

apropos("as", mode="function")

这个名单还有半个小时:

apropos("^as\\.", mode="function") 
相关问题