Rev 50786 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/methods/man/setGeneric.Rd% Part of the R package, http://www.R-project.org% Copyright 1995-2007 R Core Development Team% Distributed under GPL 2 or later\name{setGeneric}\alias{setGeneric}\alias{setGroupGeneric}\title{Define a New Generic Function}\description{Create a new generic function of the given name, that is, a functionthat dispatches methods according to the classes of the arguments,from among the formal methods defined for this function.}\usage{setGeneric(name, def= , group=list(), valueClass=character(),where= , package= , signature= , useAsDefault= ,genericFunction= , simpleInheritanceOnly = )setGroupGeneric(name, def= , group=list(), valueClass=character(),knownMembers=list(), package= , where= )}\arguments{\item{name}{ The character string name of the generic function.The simplest (and recommended) call, \code{setGeneric(name)},looks for a function with this name and creates a correspondinggeneric function, if the function found was not generic.}\item{def}{An optional function object, defining the generic.Don't supply this argument if you want an existing non-genericfunction to supply the arguments. Do supply it if there is nocurrent function of this name, or if you want the generic functionto have different arguments. In that case, the formal arguments anddefault values for the generic are taken from \code{def}. You canalso supply this argument if you want the generic function to dosomething other than just dispatch methods.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 name of the groupgeneric function to which this function belongs. See\link{Methods} for details of group generic functions in method selection.}\item{valueClass}{ An optional character vector of one or more classnames. The value returned by the generic function musthave (or extend) this class, or one of the classes; otherwise,an error is generated.}\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 vector of names, from among the formal arguments tothe function, that can appear in the signature of methods for thisfunction, in calls to \code{\link{setMethod}}. If \dots is one ofthe formal arguments, it is treated specially. Starting withversion 2.8.0 of \R, \dots may be signature of the generic function.Methods will then be selected if their signature matches all the\dots arguments. See the documentation for topic \link{dotsMethods}for details. In the present version, it is not possible to mix\dots and other arguments in the signature (this restriction may belifted in later versions).By default, the signature is inferred from the implicit genericfunction corresponding to a non-generic function. If no implicitgeneric function has been defined, the default is all the formalarguments except \dots, in the order they appear in the functiondefinition. In the case that \dots is the only formal argument, thatis also the default signature. To use \dots as the signature in afunction that has any other arguments, you must supply the signatureargument explicitly. See the \dQuote{Implicit Generic} sectionbelow for more details.}\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 functionto 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). Seethe section on details.}\item{simpleInheritanceOnly}{Supply this argument as \code{TRUE} to require that methods selectedbe inherited through simple inheritance only; that is, fromsuperclasses specified in the \code{contains=} argument to\code{\link{setClass}}, or by simple inheritance to a class union orother virtual class. Generic functions should require simpleinheritance if they need to be assured that they get the completeoriginal object, not one that has been transformed. Examples offunctions requiring simple inheritance are \code{\link{initialize}},because by definition it must return an object from the same classas its argument, and \code{\link{show}}, because it claims to give afull description of the object provided as its argument.}\item{genericFunction}{Don't use; for (possible) internal use only.}\item{knownMembers}{(For \code{setGroupGeneric} only.) The names of functions that areknown to be members of this group. This information is used toreset cached definitions of the member generics when informationabout the group generic is changed.}}\section{Basic Use}{The \code{setGeneric} function is called to initialize a genericfunction as preparation for defining some methods for that function.The simplest and most common situation is that \code{name} is alreadyan ordinary non-generic non-primitive function, and you now want toturn this function into a generic. In this case you will most oftensupply only \code{name}, for example:\code{setGeneric("colSums")}There must be an existing function of this name, on some attachedpackage (in this case package \code{"base"}). A generic version ofthis function will be created in the current package (or in the globalenvironment if the call to \code{setGeneric()} is from an ordinarysource file or is entered on the command line). The existing functionbecomes the default method, and the package slot of the new genericfunction is set to the location of the original function(\code{"base"} in the example). It's an important feature that thesame generic function definition is created each time, depending inthe example only on the definition of \code{print} and where it isfound. The \code{signature} of the generic function, defining whichof the formal arguments can be used in specifying methods, is set bydefault to all the formal arguments except \dots.Note that calling \code{setGeneric()} in this form is not strictlynecessary before calling \code{setMethod()} for the same function. Ifthe function specified in the call to \code{setMethod} is not generic,\code{setMethod} will execute the call to \code{setGeneric} itself.Declaring explicitly that you want the function to be generic can beconsidered better programming style; the only difference in theresult, however, is that not doing so produces a message noting thecreation of the generic function.You cannot (and never need to) create an explicit generic version ofthe primitive functions in the base package. Those which can betreated as generic functions have methods selected and dispatched fromthe internal C code, to satisfy concerns for efficiency, and theothers cannot be made generic. See the section on Primitive Functionsbelow.The description above is the effect when the package that owns thenon-generic function has not created an implicit generic version.Otherwise, it is this implicit generic function that is used. See thesection on Implicit Generic Functions below. Either way, theessential result is that the \emph{same} version of the genericfunction will be created each time.The second common use of \code{setGeneric()} is to create a newgeneric function, unrelated to any existing function, and frequentlyhaving no default method. In this case, you need to supply a skeletonof the function definition, to define the arguments for the function.The body of a generic function is usually a standard form,\code{standardGeneric(name)} where \code{name} is the quoted name ofthe generic function. When calling \code{setGeneric} in this form,you would normally supply the \code{def} argument as a function ofthis form. See the second and third examples below.The \code{useAsDefault} argument controls the default method for thenew generic. If not told otherwise, \code{setGeneric} will try tofind a non-generic version of the function to use as a default. So,if you do have a suitable default method, it is often simpler to firstset this up as a non-generic function, and then use the one-argumentcall to \code{setGeneric} at the beginning of this section. See thefirst example in the Examples section below.If you \emph{don't} want the existing function to be taken as default,supply the argument \code{useAsDefault}. That argument can be thefunction you want to be the default method, or \code{FALSE} to forceno default (i.e., to cause an error if there is no direct or inheritedmethod selected for a call to the function).}\section{Details}{If you want to change the behavior of an existing function (typically,one in another package) when you create a generic version, you mustsupply arguments to \code{setGeneric} correspondingly. Whateverchanges are made, the new generic function will be assigned with apackage slot set to the \emph{current} package, not the one in whichthe non-generic version of the function is found. This step isrequired because the version you are creating is no longer the same asthat implied by the function in the other package. A message will beprinted to indicate that this has taken place and noting one of thedifferences between the two functions.The body of a generic function usually does nothing except fordispatching methods by a call to \code{standardGeneric}. Under somecircumstances you might just want to do some additional computation inthe generic function itself. As long as your function eventuallycalls \code{standardGeneric} that is permissible (though perhaps not agood idea, in that it may make the behavior of your function less easyto understand). If your explicit definition of the generic functiondoes \emph{not} call \code{standardGeneric} you are in trouble,because none of the methods for the function will ever be dispatched.By default, the generic function can return any object. If\code{valueClass} is supplied, it should be a vector of class names;the value returned by a method is then required to satisfy\code{is(object, Class)} for one of the specified classes. An empty(i.e., zero length) vector of classes means anything is allowed. Notethat more complicated requirements on the result can be specifiedexplicitly, by defining a non-standard generic function.The \code{setGroupGeneric} function behaves like \code{setGeneric}except that it constructs a group generic function, differing in twoways from an ordinary generic function. First, this function cannotbe called directly, and the body of the function created will containa stop call with this information. Second, the group generic functioncontains information about the known members of the group, used tokeep the members up to date when the group definition changes, throughchanges in the search list or direct specification of methods, etc.}\section{Implicit Generic Functions}{Saying that a non-generic function \dQuote{is converted to a generic}is more precisely state that the function is converted to thecorresponding \emph{implicit} generic function. If no special actionhas been taken, any function corresponds implicitly to a genericfunction with the same arguments, in which all arguments other than\dots can be used. The signature of this generic function is thevector of formal arguments, in order, except for \dots.The source code for a package can define an implicit generic functionversion of any function in that package (see \link{implicitGeneric}for the mechanism). You can not, generally, define an implicitgeneric function in someone else's package. The usual reason fordefining an implicit generic is to prevent certain arguments fromappearing in the signature, which you must do if you want thearguments to be used literally or if you want to enforce lazyevaluation for any reason. An implicit generic can also contain somemethods that you want to be predefined; in fact, the implicit genericcan be any generic version of the non-generic function. The implicitgeneric mechanism can also be used to prohibit a generic version (see\code{\link{prohibitGeneric}}).Whether defined or inferred automatically, the implicit generic willbe compared with the generic function that \code{setGeneric} creates,when the implicit generic is in another package. If the two functionsare identical, then the \code{package} slot of the created genericwill have the name of the package containing the implicit generic.Otherwise, the slot will be the name of the package in which thegeneric is assigned.The purpose of this rule is to ensure that all methods defined for aparticular combination of generic function and package namescorrespond to a single, consistent version of the generic function.Calling \code{setGeneric} with only \code{name} and possibly\code{package} as arguments guarantees getting the implicit genericversion, if one exists.Including any of the other arguments can force a new, local version ofthe generic function. If you don't want to create a new version,don't use the extra arguments.}\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 C coderather than by evaluating an \R language definition. Most haveimplicit generics (see \code{\link{implicitGeneric}}), and becomegeneric as soon as methods (including group methods) are defined onthem. Others cannot be made generic.Even when methods are defined for such functions, the generic versionis not visible on the search list, in order that the C versioncontinues to be called. Method selection will be initiated in the Ccode. Note, however, that the result is to restrict methods forprimitive functions to signatures in which at least one of the classesin the signature is a formal S4 class.To see the generic version of a primitive function, use\code{\link{getGeneric}(name)}. The function\code{\link{isGeneric}} will tell you whether methods are definedfor the function in the current session.Note that S4 methods can only be set on those primitives which are\sQuote{\link{internal generic}}, plus \code{\%*\%}.}\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{Chambers, John M. (2008)\emph{Software for Data Analysis: Programming with R}Springer. (For the R version.)Chambers, John M. (1998)\emph{Programming with Data}Springer (For the original S4 version.)}\examples{\dontshow{setClass("track", representation(x="numeric", y="numeric"))}## create a new generic function, with a default methodprops <- function(object) attributes(object)setGeneric("props")## A new generic function with no default methodsetGeneric("increment",function(object, step, ...)standardGeneric("increment"))### 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)tryIt <- function(expr) tryCatch(expr, error = function(e) e)stopifnot(identical(authorNames(c("me", "you")), c("me", "you")),is(tryIt(authorNames(character())), "error"), # empty valueis(tryIt(authorNames(NULL)), "error")) # no default method}## 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(stats::rnorm(10)))t1 - 1001/t1\dontshow{removeGeneric("authorNames")removeClass("track")removeMethods("Arith")removeGeneric("props")removeGeneric("increment")}}\seealso{\code{\link{Methods}} and the links there for a general discussion,\code{\link{dotsMethods}} for methods that dispatch on\dQuote{\dots}, and \code{\link{setMethod}} for method definitions.}\keyword{ programming }\keyword{ methods }