| UseMethod {base} | R Documentation |
Class Methods
Description
R possesses a simple generic function mechanism which can be used foran object-oriented style of programming. Method dispatch takes placebased on the class(es) of the first argument to the generic function or ofthe object supplied as an argument toUseMethod orNextMethod.
Usage
UseMethod(generic, object)NextMethod(generic = NULL, object = NULL, ...)Arguments
generic | a character string naming a function (and not abuilt-in operator). Required for |
object | for |
... | further arguments to be passed to the next method. |
Details
AnR object is a data object which has aclassattribute (and this can be tested byis.object).A class attribute is a character vector giving the names ofthe classes from which the objectinherits.
If the object does not have a class attribute, it has animplicit class. Matrices and arrays have class"matrix"or"array" followed by the class of the underlying vector.Most vectors have class the result ofmode(x), exceptthat integer vectors have classc("integer", "numeric") andreal vectors have classc("double", "numeric").Function.class2(x) (sinceR 4.0.x) returns the fullimplicit (or explicit) class vector ofx.
When a function callingUseMethod("fun") is applied to anobject with class vectorc("first", "second"), the systemsearches for a function calledfun.first and, if it finds it,applies it to the object. If no such function is found a functioncalledfun.second is tried. If no class name produces asuitable function, the functionfun.default is used, if itexists, or an error results.
Functionmethods can be used to find out about themethods for a particular generic function or class.
UseMethod is a primitive function but uses standard argumentmatching. It is not the only means of dispatch of methods, for thereareinternal generic andgroup generic functions.UseMethod currently dispatches on the implicit class even forarguments that are not objects, but the other means of dispatch donot.
NextMethod invokes the next method (determined by theclass vector, either of the object supplied to the generic, or ofthe first argument to the function containingNextMethod if amethod was invoked directly). NormallyNextMethod is used withonly one argument,generic, but if further arguments aresupplied these modify the call to the next method.
NextMethod should not be called except in methods called byUseMethod or from internal generics (seeInternalGenerics). In particular it will not work insideanonymous calling functions (e.g.,get("print.ts")(AirPassengers)).
Namespaces can register methods for generic functions. To supportthis,UseMethod andNextMethod search for methods intwo places: in the environment in which the generic functionis called, and in the registration data base for theenvironment in which the generic is defined (typically a namespace).So methods for a generic function need to be available in theenvironment of the call to the generic, or they must be registered.(It does not matter whether they are visible in the environment inwhich the generic is defined.) As fromR 3.5.0, the registrationdata base is searched after the top level environment (seetopenv) of the calling environment (but before theparents of the top level environment).
Technical Details
Now for some obscure details that need to appear somewhere. Thesecomments will be slightly different than those inChambers (1992).(See also the draft ofThe R Language Definition.)UseMethod creates a new function call witharguments matched as they came in to the generic. [Previously localvariables defined before the call toUseMethod were retained;as ofR 4.4.0 this is no longer the case.] Anystatements after the call toUseMethod will not be evaluated asUseMethod does not return.UseMethod can be called withmore than two arguments: a warning will be given and additionalarguments ignored. (They are not completely ignored in S.) If it iscalled with just one argument, the class of the first argument of theenclosing function is used asobject: unlike S this is the firstactual argument passed and not the current value of the object of thatname.
NextMethod works by creating a special call frame for the nextmethod. If no new arguments are supplied, the arguments will be thesame in number, order and name as those to the current method buttheir values will be promises to evaluate their name in the currentmethod and environment. Any arguments matched to...are handled specially: named arguments either replace existing argumentsof the same name or are appended to the argument list, unnamed arguments areappended to the argument list. They are passed on asthe promise that was supplied as an argument to the currentenvironment. (S does this differently!) If they have been evaluatedin the current (or a previous environment) they remain evaluated.(This is a complex area, and subject to change: see the draft ofThe R Language Definition.)
The search for methods forNextMethod is slightly differentfrom that forUseMethod. Finding nofun.default is notnecessarily an error, as the search continues to the genericitself. This is to pick up aninternal generic like[which has no separate default method, and succeeds only if the genericis aprimitive function or a wrapper for a.Internal function of the same name. (When a primitiveis called as the default method, argument matching may not work asdescribed above due to the different semantics of primitives.)
You will see objects such as.Generic,.Method, and.Class used in methods. These are set in the environmentwithin which the method is evaluated by the dispatch mechanism, whichis as follows:
Find the context for the calling function (the generic): thisgives us the unevaluated arguments for the original call.
Evaluate the object (usually an argument) to be used fordispatch, and find a method (possibly the default method) or throwan error.
Create an environment for evaluating the method and insertspecial variables (see below) into that environment. Also copy anyvariables in the environment of the generic that are not formal (oractual) arguments.
Fix up the argument list to be the arguments of the callmatched to the formals of the method.
.Generic is a length-one character vector naming the generic function.
.Method is a character vector (normally of length one) namingthe method function. (For functions in the group genericOps it is of length two.)
.Class is a character vector of classes used to find the nextmethod.NextMethod adds an attribute"previous" to.Class giving the.Class last used for dispatch, andshifts.Class along to that used for dispatch.
.GenericCallEnv and.GenericDefEnv are the environmentsof the call to be generic and defining the generic respectively. (Thelatter is used to find methods registered for the generic.)
Note that.Class is set when the generic is called, and isunchanged if the class of the dispatching argument is changed in amethod. It is possible to change the method thatNextMethodwould dispatch by manipulating.Class, but ‘this is notrecommended unless you understand the inheritance mechanismthoroughly’ (Chambers 1992, page 469).
Note
This scheme is calledS3 (S version 3). For new projects,it is recommended to use the more flexible and robustS4 schemeprovided in themethods package.
References
Chambers J. M. (1992).“Classes and Methods: Object-Oriented Programming in S.”In Chambers J. M., Hastie T. J. (eds.),Statistical Models in S.Wadsworth & Brooks/Cole.Appendix A.
See Also
The draft ofThe R Language Definition.
methods,class incl..class2;getS3method,is.object.