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 [EMAIL PROTECTED] > for Human Genetics, Oxford www.well.ox.ac.uk/~valdar -- Brian D. Ripley, [EMAIL PROTECTED] 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 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.