gpt4 book ai didi

r - 关于 UseMethod 搜索机制的困惑

转载 作者:行者123 更新时间:2023-12-01 01:18:44 25 4
gpt4 key购买 nike

我想弄清楚 R 的 UseMethod找到一个方法,一旦它弄清楚它在寻找什么(即函数 MyGeneric( x ) 用类 MyClass: MyGeneric.MyClass 的 x 调用)
具体涉及哪些环境?

我已经阅读了 R 语言手册的“5.3 Method Dispatching”和“5.4 UseMethod”部分,其中没有指定搜索机制。 UseMethod 的 R 帮助页面提供了一个线索:

...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将在调用环境中。我错过了什么?

最佳答案

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

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

关于r - 关于 UseMethod 搜索机制的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10518901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com