Rev 46546 | 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 isno current function of this name, or if you want the genericfunction to have different arguments. 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.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 argumentsto the function, that canappear in the signature of methods for this function, in calls to\code{\link{setMethod}}. If \dots is one of theformal arguments, it is treated specially. Starting with version2.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 notpossible to mix \dots and other arguments in the signature (thisrestriction may be lifted in later versions).By default, the signature is inferred from the implicit genericfunction corresponding to a non-generic function. If no implicit generic function has been defined, the default is all theformal arguments except \dots, in the order they appear in thefunction definition. In the case that\dots is the only formal argument, that is also the default signature. To use \dots as the signaturein a function that has any other arguments, you must supply thesignature argument explicitly. See the \dQuote{ImplicitGeneric} section below 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 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{simpleInheritanceOnly}{Supply this argument as \code{TRUE} to require that methodsselected be inherited through simple inheritance only; that is,from superclasses specified in the \code{contains=} argument to\code{\link{setClass}}, or by simple inheritance to a classunion or other virtual class. Generic functions should requiresimple inheritance if they need to be assured that they get thecomplete original object, not one that has been transformed.Examples of functions requiring simple inheritance are\code{\link{initialize}}, because by definition it must returnan object from the same class as its argument, and\code{\link{show}}, because it claims to give a full descriptionof 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 aspreparation 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 to turn thisfunction into a generic. In this case you will most often supply only\code{name}, for example:\code{setGeneric("colSums")}There must be an existing function of this name, on some attached package (in this case package \code{"base"}).A generic version of this function will be created in the current package (or in the global environment if the call to \code{setGeneric()} is from an ordinary source file or is entered on the command line).The existing function becomes the default method, andthe package slot of the new generic function is set to the location of the original function (\code{"base"} in the example). It's an important feature that the same generic function definition is created each time, depending in the example only on the definition of \code{print} and where it is found.The \code{signature} of the generic function, defining which of the formal arguments can be used in specifying methods, is set by default to all the formal arguments except \dots.Note that calling \code{setGeneric()} in this form is not strictly necessary before calling \code{setMethod()} for the same function. If the 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 be considered better programming style; the only difference in the result, however, is that not doing so produces a message noting the creation of the generic function.You cannot (and never need to) create an explicit generic version of theprimitive functions in the base package. Those which can be treatedas generic functions have methods selected anddispatched from the internal C code, to satisfy concerns for efficiency, and the others cannot be madegeneric. See the section on Primitive Functions below.The description above is the effect when the package that owns the non-generic function has not created an implicit generic version. Otherwise, it is this implicit generic function that is used. See the section on Implicit Generic Functions below. Either way, the essential result is that the \emph{same} version of the generic function will be created each time.The second common use of \code{setGeneric()} is to create a new genericfunction, unrelated to any existing function, and frequently having no default method. 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. See the second and third examples below.The \code{useAsDefault} argument controls the default method for the new generic.If nottold otherwise, \code{setGeneric} will try to find a non-genericversion of the function to use as a default.So, if you do have a suitable default method, it is often simpler to first set this up as a non-generic function, and then use the one-argument call to \code{setGeneric} at the beginning of this section. See the first 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 argumentcan be the function you want to be the default method, or\code{FALSE} to force no default (i.e., to cause an error ifthere is no direct or inherited method 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 must supply arguments to \code{setGeneric} correspondingly.Whatever changes are made, the new generic function will be assigned with a package slot set to the \emph{current} package, not the one in which the non-generic version of the function is found.This step is required because the version you are creating is no longer the same as that implied by the function in the other package.A message will be printed to indicate that this has taken place and noting one of the differences between the two functions.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 may make the behavior ofyour function less easy to understand). 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 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 genericfunction contains information about the known members of the group,used to keep the members up to date when the group definitionchanges, through changes in the search list or direct specificationof 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 action has been taken, any function correspondsimplicitly to a generic function with the same arguments, in whichall argumentsother than \dots can be used. The signature of this genericfunction is the vector 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 twofunctions are identical, then the \code{package} slot of the createdgeneric will have the name of the package containing the implicitgeneric. Otherwise, the slot will be the name of the package in whichthe generic 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 genericfunction. Calling \code{setGeneric} with only \code{name} andpossibly \code{package} as arguments guarantees getting the implicitgeneric version, 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 Ccode rather 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 genericversion is not visible on the search list, in order that the Cversion continues to be called. Method selection will be initiatedin the C code. Note, however, that the result is to restrictmethods for primitive functions to signatures in which at least oneof the classes in 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.}\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)stopifnot(identical(authorNames(c("me", "you")), c("me", "you")),is(trySilent(authorNames(character())), "try-error"), # empty valueis(trySilent(authorNames(NULL)), "try-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 }