Search code examples
rdispatch

Confusion about UseMethod search mechanism


I'm trying to figure out how R's UseMethod finds a method once it figures out what its looking for (i.e. function MyGeneric( x ) called with x of class MyClass: MyGeneric.MyClass) Specifically, what environments are involved?

I have read section "5.3 Method Dispatching" and "5.4 UseMethod" of the R Language Manual which does not specify the search mechanism. The R-Help page for UseMethod provides a clue:

...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)

But this doesn't add up (in my head =). Here's a concrete example:

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 is defined in namespace:base. If R were to use that environment, or the calling environment (R_GlobalEnv), it could not find as.matrix.xts because its not exported. The calling environment would seem to work if a function within xts calls as.matrix because as.matrix.xts would be in the calling environment. What am I missing?


Solution

  • You're not reading that quite carefully enough. It says the "registration database" is stored in the environment (namespace) of the generic, not the method itself. In the case of base::as.matrix:

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