【问题标题】:Confusion about UseMethod search mechanism关于 UseMethod 搜索机制的困惑
【发布时间】: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.matrixnamespace: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 中的复杂程度有点令人沮丧。
  • 我想这是一个小世界 ;-) 如果你不反对,我会把它留给任何偶然发现这个的人。

标签: r dispatch


【解决方案1】:

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

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

【讨论】:

  • 酷!这是否取决于 xts 是附加还是加载?所以如果 xts 列在 MyPackage 的 Imports 中,并且我附加了 MyPackage(所以 xts 不在 search() 中),那么 as.matrix 是否仍然存储在泛型的环境中?
  • @SFun28:这取决于注册是在命名空间加载期间还是在附加到搜索路径期间发生。我不知道是哪种情况。
【解决方案2】:

除了 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") 

【讨论】:

  • 很高兴了解 getAnywhere(),这对我来说是新的。列出 as.matrix.xts 的搜索路径相当容易(参见 stackoverflow.com/questions/8637107/parent-env-x-confusion),但我还没有看到一个函数告诉你 R 如何获取任何给定的非- 导出函数。如果你能把它挖掘出来,那将是非常有用的。
  • 三点运算符是我所知道的最强大的搜索方法。它不需要加载函数,只需在库路径上的已安装包中找到它即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 2019-05-17
  • 2020-03-06
  • 2016-03-16
  • 2013-07-27
  • 1970-01-01
相关资源
最近更新 更多