[Rd] UseMethod infelicity

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri May 19 17:01:21 CEST 2006


If I do

> example(lm)
...
> mycoef <- function(object, ...) UseMethod("coef", object)
> mycoef(lm.D9)
Error in mycoef(lm.D9) : no applicable method for "coef"

which is pretty surprising, as coef has a default method.

After a bit of digging, this comes from do_usemethod having

        defenv = environment where the generic was defined */
     defenv = ENCLOS(env);

so it is assuming that UseMethod() is called within the defining generic 
for its first argument.  That plainly does not need to be true, e.g.

> coefficients
function (object, ...)
UseMethod("coef")
<environment: namespace:stats>

It is clear to me that we need to search for 'generic' and find its 
defining environment rather than that of the current caller.  It is not 
entirely clear where to search from as I think we need to avoid

mycoef <- function(x)
{
    mycoef <- function(x) stop("not this one")
    UseMethod("mycoef")
}

so I used ENCLOS(env).

This adds some overhead, hopefully no more than searching for methods.

BTW, I noticed that R_LookupMethod uses findVar, that is looks for any 
object not for functions: that must be another infelicity.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list