Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 关于UseMethod搜索机制的困惑_R_Dispatch - Fatal编程技术网

R 关于UseMethod搜索机制的困惑

R 关于UseMethod搜索机制的困惑,r,dispatch,R,Dispatch,我试图弄清楚R的UseMethod如何在找到它要找的东西后找到一个方法(即用类MyClass的x调用函数MyGeneric(x):MyGeneric.MyClass) 具体来说,涉及哪些环境 我已经阅读了R语言手册的“5.3方法调度”和“5.4使用方法”部分,其中没有指定搜索机制。UseMethod的R-Help页面提供了一条线索: ...UseMethod and NextMethod search for methods in two places: first in the enviro

我试图弄清楚R的
UseMethod
如何在找到它要找的东西后找到一个方法(即用类MyClass的x调用函数MyGeneric(x):MyGeneric.MyClass) 具体来说,涉及哪些环境

我已经阅读了R语言手册的“5.3方法调度”和“5.4使用方法”部分,其中没有指定搜索机制。
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!
库(xts)
as.matrix#显示UseMethod(“as.matrix”)
方法(“as.matrix”)#显示为as.matrix.xts。*表示不可见
showMethods(“as.matrix”)说
数据(样本矩阵)
as.matrix(as.xts(sample_matrix))#R如何找到as.matrix.xts??它不出口!

as.matrix
命名空间: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"

除了约书亚的洞察力,这增加了我的知识。。。。在加载的命名空间中与导出的命名空间不同。您可以看到as.matrix.xts函数具有以下任一功能:

 getAnywhere(as.matrix.xts)
 xts:::as.matrix.xts
试着打字

search()
我在SO或rhelp上也看到了一个函数,它将显示R解释器对函数调用的搜索路径,但目前我似乎找不到它。这将生成一个相当长的函数名列表:

apropos("as", mode="function")
这张单子还有一半长:

apropos("^as\\.", mode="function") 

酷!这是否取决于连接的xts与加载的xts?因此,如果xts列在MyPackage的导入中,并且我附加了MyPackage(因此xts不在search()中),那么as.matrix是否仍存储在泛型的环境中?@SFun28:这取决于注册是在命名空间加载期间还是在附加到搜索路径期间发生。我不知道是哪种情况。很高兴知道getAnywhere(),这对我来说是新的。列出as.matrix.xts的搜索路径相当容易(请参阅stackoverflow.com/questions/8637107/parent-env-x-conflusion),但我没有看到一个函数告诉您R如何到达任何给定的非导出函数。如果你能把它挖掘出来,它将非常有用。三点运算符是我所知道的最强的搜索方法。它不要求加载函数,只要求可以在库路径上的已安装包中找到它。这可能也会有帮助(对于直接的问题和一般理解R语言手册的那部分):mweylandt-足够有趣,这是我的博客帖子=)似乎我需要添加一个关于通用函数/方法的部分,这与通常的搜索/查找机制不同。在R中,这些东西是多么复杂,这有点令人沮丧。我想这是一个小世界;-)如果你不反对的话,我会把它留给任何一个偶然发现它的人。