Rev 35751 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
\name{setGeneric}\alias{setGeneric}\alias{setGroupGeneric}\title{Define a New Generic Function}\description{Create a new generic function of the given name, for which formalmethods can then be defined. Typically, an existing non-genericfunction becomes the default method, but there is much optionalcontrol. See the details section.}\usage{setGeneric(name, def= , group=list(), valueClass=character(), where= ,package= , signature= , useAsDefault= , genericFunction= )setGroupGeneric(name, def= , group=list(), valueClass=character(),knownMembers=list(), package= , where= )}\arguments{\item{name}{ The character string name of the generic function. Inthe simplest and most common case, a function of this name isalready defined. The existing function may be non-generic oralready a generic (see the details).}\item{def}{ An optional function object, defining the generic. Thisargument is usually only needed (and is then required) if there isno current function of this name. In that case, the formal argumentsand default values for the generic are taken from \code{def}. Youcan also supply this argument if you want the generic function todo something other than just dispatch methods (an advanced topicbest left alone unless you are sure you want it).Note that \code{def} is \emph{not} the default method; use argument\code{useAsDefault} if you want to specify the default separately.}\item{group}{ Optionally, a character string giving the group ofgeneric functions to which this function belongs. Methods can bedefined for the corresponding group generic, and these will thendefine methods for this specific generic function, if no method hasbeen explicitly defined for the corresponding signature. See thereferences for more discussion.}\item{valueClass}{ An optional character vector or unevaluatedexpression. The value returned by the generic function musthave (or extend) this class, or one of the classes; otherwise,an error is generated. See thedetails section for supplying an expression.}\item{package}{ The name of the package with which this function isassociated. Usually determined automatically (as the packagecontaining the non-generic version if there is one, or else thepackage where this generic is to be saved).}\item{where}{ Where to store the resulting initial methods definition,and possibly the generic function; bydefault, stored into the top-level environment.}\item{signature}{Optionally, the signature of arguments in the function that canbe used in methods for this generic. By default, all argumentsother than \code{...} can be used. The signature argument canprohibit methods from using some arguments. The argument, ifprovided, is a vector of formal argument names.}\item{genericFunction}{ The object to be used as a (nonstandard)generic function definition. Supply this explicitly \emph{only} ifyou know what you are doing!}\item{useAsDefault}{Override the usual choice of default argument (an existingnon-generic function or no default if there is no such function).Argument \code{useAsDefault} can be supplied,either as a function to use for the default, or as a logical value.\code{FALSE} says not to have a default method at all, so that anerror occurs if there is not an explicit or inherited method for acall.\code{TRUE} says to use the existing function as default,unconditionally (hardly ever needed as an explicit argument).See the section on details.}\item{knownMembers}{(For \code{setGroupGeneric} only) The names of functions that are known to bemembers of this group. This information is used to reset cacheddefinitions of the member generics when information about the groupgeneric is changed.}}\details{The \code{setGeneric} function is called to initialize a genericfunction in an environment (usually the global environment), aspreparation for defining some methods for that function.The simplest and most common situation is that \code{name} is alreadyan ordinary non-generic function, and you now want to turn thisfunction into a generic.In thiscase you will most often supply only \code{name}. The existingfunction becomes the default method, and the special \code{group} and\code{valueClass} properties remain unspecified.A second situation is that you want to create a new, genericfunction, unrelated to any existing function. In this case, youneed to supply a skeleton of the function definition, to define thearguments for the function. The body of a generic function isusually a standard form, \code{standardGeneric(name)} where\code{name} is the quoted name of the generic function.When calling \code{setGeneric} in this form, you would normallysupply the \code{def} argument as a function of this form. If nottold otherwise, \code{setGeneric} will try to find a non-genericversion of the function to use as a default. If you don't want thisto happen, supply the argument \code{useAsDefault}. That argumentcan be the function you want to be the default method. You can supplythe argument as \code{FALSE} to force no default (i.e., to cause an error ifthere is not direct or inherited method on call to the function).The same no-default situation occurs if there is no non-generic form of the function, and\code{useAsDefault=FALSE}. Remember, though, you canalso just assign the default you want (even one that generates anerror) rather than relying on the prior situation.You cannot (and never need to) create an explicit generic for theprimitive functions in the base library. These are dispatched fromC code for efficiency and are not to be redefinedin any case.As mentioned, the body of a generic function usually does nothingexcept for dispatching methods by a call to \code{standardGeneric}.Under some circumstances you might just want to do some additionalcomputation in the generic function itself. As long as yourfunction eventually calls \code{standardGeneric} that is permissible(though perhaps not a good idea, in that it makes the behavior ofyour function different from the usual S model). If your explicitdefinition of the generic functiondoes \emph{not} call \code{standardGeneric} you are in trouble,because none of the methods for the function will ever bedispatched.By default, the generic function can return any object.If \code{valueClass} is supplied, it should be a vector ofclass names; the value returned by a method is then required tosatisfy \code{is(object, Class)} for one of the specified classes.An empty (i.e., zero length) vector of classes means anything isallowed.Note that more complicated requirements on the result can bespecified explicitly, by defining a non-standard generic function.The \code{setGroupGeneric} function behaves like \code{setGeneric} except thatit constructs a group generic function, differing in two ways from anordinary generic function. First,this function cannot be called directly, and the body of the functioncreated will contain a stop call with this information. Second, thegroup generic function contains information about the known members ofthe group, used to keep the members up to date when the groupdefinition changes, through changes in the search list or directspecification of methods, etc.}\section{Generic Functions and Primitive Functions}{A number of the basic R functions are specially implemented asprimitive functions, to be evaluated directly in the underlying Ccode rather than by evaluating an S language definition. Primitivefunctions are eligible to have methods, but are handled differentlyby \code{setGeneric} and \code{setGroupGeneric}. A call to\code{setGeneric} for a primitive function does not create a newdefinition of the function, and the call is allowed only to\dQuote{turn on} methods for that function.A call to \code{setGeneric} for a primitive causes the evaluator tolook for methods for that generic; a call to \code{setGroupGeneric}for any of the groups that include primitives (\code{"Arith", "Logic","Compare", "Ops", "Math", "Math2", "Summary",} and \code{"Complex"})does the same for each of the functions in that group.You usually only need to use either function if the methods arebeing defined only for the group generic. Defining a method for aprimitive function, say \code{"+"}, by a call to \code{setMethod}turns on method dispatch for that function. But in R defining amethod for the corresponding group generic, \code{"Arith"}, does notcurrently turn on method dispatch (for efficiency reasons). Ifthere are no non-group methods for the functions, you have twochoices.You can turn on method dispatch for \emph{all} the functions in thegroup by calling \code{setGroupGeneric("Arith")}, or you can turn onmethod dispatch for only some of the functions by calling\code{setGeneric("+")}, etc. Note that in either case you shouldgive the name of the generic function as the only argument.}\value{The \code{setGeneric} function exists for its side effect: saving thegeneric function to allow methods to be specified later. It returns\code{name}.}\references{The R package \pkg{methods} implements, with a few exceptions, theprogramming interface for classes and methods in the book\emph{Programming with Data} (John M. Chambers, Springer, 1998), inparticular sections 1.6, 2.7, 2.8, and chapters 7 and 8.While the programming interface for the \pkg{methods} package followsthe reference, the R software is an original implementation, sodetails in the reference that reflect the S4 implementation may appeardifferently in R. Also, there are extensions to the programminginterface developed more recently than the reference. For adiscussion of details and ongoing development, see the web page\url{http://developer.r-project.org/methodsPackage.html} and thepointers from that page.}\examples{\dontshow{setClass("track",representation(x="numeric", y="numeric"))}### A non-standard generic function. It insists that the methods### return a non-empty character vector (a stronger requirement than### valueClass = "character" in the call to setGeneric)setGeneric("authorNames",function(text) {value <- standardGeneric("authorNames")if(!(is(value, "character") && any(nchar(value)>0)))stop("authorNames methods must return non-empty strings")value})\dontshow{setMethod("authorNames", "character", function(text)text)stopifnot(identical(authorNames(c("me", "you")), c("me", "you")))stopifnot(is(trySilent(authorNames(character())), "try-error")) # empty valuestopifnot(is(trySilent(authorNames(NULL)), "try-error")) # no default methodstopifnot(is(trySilent(setGeneric("[", function(x,...)standardGeneric("["))),"try-error")) # trying setGeneric on a primitive}## An example of group generic methods, using the class## "track"; see the documentation of setClass for its definition#define a method for the Arith groupsetMethod("Arith", c("track", "numeric"),function(e1, e2){e1@y <- callGeneric(e1@y , e2)e1})setMethod("Arith", c("numeric", "track"),function(e1, e2){e2@y <- callGeneric(e1, e2@y)e2})# now arithmetic operators will dispatch methods:t1 <- new("track", x=1:10, y=sort(rnorm(10)))t1 - 1001/t1\dontshow{removeGeneric("authorNames")removeClass("track")removeMethods("Arith")}}\seealso{\code{\link{Methods}} for a discussion of other functions to specifyand manipulate the methods of generic functions.}\keyword{ programming }\keyword{ methods }