【发布时间】:2012-05-09 15:10:05
【问题描述】:
我试图弄清楚 R 的 UseMethod 如何找到一个方法,一旦它弄清楚它在寻找什么(即函数 MyGeneric( x ) 用 MyClass: MyGeneric.MyClass 的 x 调用)
具体涉及哪些环境?
我已阅读 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.matrix 在namespace:base 中定义。如果 R 要使用该环境或调用环境 (R_GlobalEnv),它找不到 as.matrix.xts,因为它没有导出。如果 xts 中的函数调用 as.matrix,则调用环境似乎可以工作,因为 as.matrix.xts 将在调用环境中。我错过了什么?
【问题讨论】:
-
这可能也有帮助(对于直接的问题和对 R 语言手册的一般理解部分):obeautifulcode.com/R/How-R-Searches-And-Finds-Stuff
-
mweylandt - 很有趣,这是我的博客文章 =) 似乎我需要添加一个关于偏离通常搜索/查找机制的通用函数/方法的部分。这东西在 R 中的复杂程度有点令人沮丧。
-
我想这是一个小世界 ;-) 如果你不反对,我会把它留给任何偶然发现这个的人。