[R] test for existance of a method for given class

William Valdar valdar at well.ox.ac.uk
Wed Nov 14 15:03:47 CET 2007


Thanks Brian, that helps a lot. For others interested, a few variants for 
testing existance of methods are below:

# modified sub/grep of BDR's example
hasS3method.1 <- function(f, x)
{
     if(is.object(x)) x <- oldClass(x)
     m <- methods(f)
     pattern <- paste("^", f, ".", sep="")
     cl <- sub(pattern, "", grep(pattern, m, value=TRUE))
     any(c("default", x) %in% cl)
}

# almost equivalently...
hasS3method.2 <- function(f, x, include.default=TRUE)
{
     if(is.object(x)) x <- oldClass(x)
     !is.null(getS3method(f, x, optional=TRUE))
}

hasS4method <- function(f, x)
{
     if (is.object(x)) x <- class(x)
     for (cl in x)
     {
         m <- selectMethod(f, signature(object=cl), optional=TRUE)
         if (!is.null(m)) return (TRUE)
     }
     FALSE
}

Will

On Wed, 14 Nov 2007, Prof Brian Ripley wrote:
> On Wed, 14 Nov 2007, William Valdar wrote:
>
>> Dear All,
>> 
>> I want to test whether a method exists for given object. For example,
>> whether a function "deviance" is defined for an object of the "lm" class.
>
> For an S3 generic 'f' and with an S3 object or an S3 class 'x', try
>
> hasS3method <- function(f, x)
> {
>    if(is.object(x)) x <- oldClass(x)
>    m <- methods(f)
>    cl <- sub(paste("^", f, ".", sep=""), "", m)
>    any(c("default", x) %in% cl)
> }
>
> (You can break this, e.g. by f="resid" or using implicit classes: it needs 
> inside knowledge to know if the latter would be invoked.  Also, the set of 
> available methods is in principle scope-specific.)
>
> For S4 generics and classes, look at selectMethod(optional=TRUE): this is 
> documented to return NULL if and only if there is no applicable method.
>
>
>> My imperfect understanding leads me to think something like
>>
>>  hasMethod("deviance", object)
>>  hasMethod("deviance", "lm")
>>  existsMethod("deviance", signature(class="lm"))
>> 
>> or similar might work (I don't fully understand how to manipulate
>> signatures), but all the variations on this I have tried return FALSE.
>> (Except, interestingly, when I first load library lme4, after which all
>> return TRUE even for non-existant classes and functions).
>> 
>> I realize there are several ways in which R implements function
>> polymorphism and that this is all documented somewhere but a hint would
>> save me considerable time. I would also prefer not to resort to the hack
>> solution of try()ing the function with the object and then catching the
>> error to determine whether it was defined.
>> 
>> Thanks,
>> 
>> Will
>>

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Dr William Valdar               ++44 (0)1865 287 589
Wellcome Trust Centre           valdar at well.ox.ac.uk
for Human Genetics, Oxford      www.well.ox.ac.uk/~valdar



More information about the R-help mailing list