The R Project SVN R

Rev

Rev 88527 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/methods/man/setMethod.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
71228 maechler 3
% Copyright 1995-2016 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
15357 jmc 6
\name{setMethod}
56186 murdoch 7
\alias{setMethod}
15357 jmc 8
\title{ Create and Save a Method }
9
\description{
71366 jmc 10
Create a method for a generic function, corresponding to a signature of classes for the arguments. Standard usage will be of the form:
11
 
12
\code{setMethod(f, signature, definition)}
13
 
14
where \code{f} is the name of the function, \code{signature} specifies the argument classes for which the method applies and \code{definition} is the function definition for the method. 
15357 jmc 15
}
16
\usage{
30912 ripley 17
setMethod(f, signature=character(), definition,
18
          where = topenv(parent.frame()),
26530 maechler 19
          valueClass = NULL, sealed = FALSE)
15357 jmc 20
}
21
\arguments{
71366 jmc 22
  \item{f}{ The character-string name of the generic function. The unquoted name usually works as well (evaluating to the generic function), except for a few functions in the base package.}
23
  \item{signature}{ The classes required for some of the arguments. Most applications just require one or two character strings matching the first argument(s) in the signature. More complicated cases follow R's rule for argument matching. See the details below; however, if the signature is not trivial, you should use \code{\link{method.skeleton}} to generate a valid call to \code{setMethod}.}
15826 jmc 24
  \item{definition}{ A function definition, which will become the method
19029 hornik 25
    called when the arguments in a call to \code{f} match the
71366 jmc 26
    classes in \code{signature}, directly or through inheritance.
27
    The definition must be a function with the same formal arguments
28
    as the generic; however, \code{setMethod()} will handle methods
29
    that add arguments, if \code{\dots} is a formal argument to the generic.
30
  See the Details section.
31
  }
32
  \item{where, valueClass, sealed}{\emph{These arguments are allowed
33
        but either obsolete or rarely appropriate.}
17454 jmc 34
 
71366 jmc 35
      \code{where}: where to store the definition; should be the
36
      default, the namespace for the package.
37
 
81927 smeyer 38
  \code{valueClass}: obsolete.
71366 jmc 39
 
81927 smeyer 40
  \code{sealed}: prevents the method being redefined, but should never
71366 jmc 41
    be needed when the method is defined in the source code of a
81927 smeyer 42
    package.
15357 jmc 43
}
71366 jmc 44
}
17454 jmc 45
\value{
71366 jmc 46
  The function exists for its side-effect. The definition will be stored in a special metadata object and incorporated in the generic function when the corresponding package is loaded into an R session. 
47
 
17454 jmc 48
}
71460 jmc 49
\section{Method Selection: Avoiding Ambiguity}{
50
When defining methods, it's important to ensure that methods are
51
selected correctly; in particular, packages should be designed to
52
avoid ambiguous method selection.
53
 
54
To describe method selection, consider first the case where only one
55
formal argument is in the active signature; that is, there is only one
56
argument, \code{x} say, for which methods have been defined.
57
The generic function has a table of methods, indexed by the class for
58
the argument in the calls to \code{setMethod}.
59
If there is a method in the table for the class of \code{x} in the
60
call, this method is selected.
61
 
62
If not, the next best methods would correspond to the direct
63
superclasses of \code{class(x)}---those appearing in the
64
\code{contains=} argument when that class was defined.
65
If there is no method for any of these, the next best would correspond
66
to the direct superclasses of the first set of superclasses, and so
67
on.
68
 
69
The first possible source of ambiguity arises if the class has several
70
direct superclasses and methods have been defined for more than one of
71
those;
72
\R will consider these equally valid and report an ambiguous choice.
73
If your package has the class definition for \code{class(x)}, then you
74
need to define a method explicitly for this combination of generic
75
function and class.
76
 
77
When more than one formal argument appears in the method signature, \R
78
requires the \dQuote{best} method to be chosen  unambiguously for each
79
argument.
80
Ambiguities arise when one method is specific about one argument while
81
another is specific about a different argument.
82
A call that satisfies both requirements is then ambiguous:  The two
83
methods look equally valid, which should be chosen?
84
In such cases the package needs to add a third method requiring both
85
arguments to match.
86
 
87
The most common examples arise with binary operators.  Methods may be
88
defined for individual operators, for special groups of operators such as
89
\code{\link{Arith}} or for group \code{\link{Ops}}.
90
 
91
}
72027 jmc 92
\section{Exporting Methods}{
93
If a package defines methods for generic functions, those methods
94
should be exported if any of the classes involved are exported; in
95
other words, if someone using the package might expect these methods
96
to be called.
97
Methods are exported by including an \code{exportMethods()} directive
88527 smeyer 98
in the \file{NAMESPACE} file for the package, with the arguments to
72027 jmc 99
the directive being the names of the generic functions for which
100
methods have been defined.
101
 
102
Exporting methods is always desirable in the sense of declaring what
103
you want to happen, in that you do expect users to find such methods.
104
It can be essential in the case that the method was defined for a
88527 smeyer 105
function that is not originally a formal generic function in its own package
106
(for example, \code{plot()} in the \pkg{base} package).  In this
72027 jmc 107
case it may be that the version of the function in the \R session is
108
not generic, and your methods will not be called.
109
 
110
Exporting methods for a function also exports the generic version of
111
the function.
112
Keep in mind that this does \emph{not} conflict with the function as
113
it was originally defined in another package; on the contrary, it's
114
designed to ensure that the function in the \R session dispatches
115
methods correctly for your classes and continues to behave as expected
116
when no specific methods apply.  See \link{Methods_Details} for the actual mechanism.
117
}
71460 jmc 118
\section{Details}{
45824 jmc 119
The call to \code{setMethod} stores the supplied method definition  in
120
the metadata table for this generic function in the environment,
56382 murdoch 121
typically the global environment or the namespace of a package.
122
In the case of a package, the table object becomes part of the namespace or environment of the
45824 jmc 123
package.
124
When the package is loaded into a later session, the
125
methods will be merged into the table of methods in the corresponding
126
generic function object.
15357 jmc 127
 
45824 jmc 128
Generic functions are referenced by the combination of the function name and
129
the package name;
130
for example, the function \code{"show"} from the package
131
\code{"methods"}.
132
Metadata for methods is identified by the two strings; in particular, the
133
generic function object itself has slots containing its name and its
134
package name.
135
The package name of a generic is set according to the package
136
from which it originally comes; in particular, and frequently, the
137
package where a non-generic version of the function originated.
49587 hornik 138
For example, generic functions for all the functions in package \pkg{base} will
45824 jmc 139
have \code{"base"} as the package name, although none of them is an
140
S4 generic on that package.
48062 jmc 141
These include most of the base functions that are primitives, rather than
142
true functions; see the section on primitive functions in the
143
documentation for \code{\link{setGeneric}} for details.
23678 jmc 144
 
45824 jmc 145
Multiple packages can have methods for the same generic function; that
146
is, for the same combination of generic function name and package
147
name.
148
Even though the methods are stored in separate tables in separate
149
environments, loading the corresponding packages adds the methods to
150
the table in the generic function itself, for the duration of the session.
151
 
23678 jmc 152
 The class
45824 jmc 153
  names in the signature can be any formal class, including basic
15357 jmc 154
  classes such as \code{"numeric"}, \code{"character"}, and
155
  \code{"matrix"}.  Two additional special class names can appear:
156
  \code{"ANY"}, meaning that this argument can have any class at all;
157
  and \code{"missing"}, meaning that this argument \emph{must not}
158
  appear in the call in order to match this signature.  Don't confuse
159
  these two:  if an argument isn't mentioned in a signature, it
160
  corresponds implicitly to class \code{"ANY"}, not to
42963 ripley 161
  \code{"missing"}.  See the example below.  Old-style (\sQuote{S3})
25118 hornik 162
  classes can also be used, if you need compatibility with these, but
163
  you should definitely declare these classes by calling
23678 jmc 164
  \code{\link{setOldClass}} if you want S3-style inheritance to work.
15357 jmc 165
 
23678 jmc 166
 
28652 jmc 167
  Method definitions can
71366 jmc 168
  have default expressions for arguments, but only if
169
  the generic function must have \emph{some} default expression for the
170
  same argument. (This restriction is imposed by the way \R manages
171
  formal arguments.)
45824 jmc 172
  If so, and if the corresponding argument is
28652 jmc 173
  missing in the call to the generic function, the default expression
174
  in the method is used.  If the method definition has no default for
45824 jmc 175
  the argument, then the expression supplied in the definition of the
176
  generic function itself is used, but note that this expression will
177
  be evaluated using the enclosing environment of the method, not of
178
  the generic function.
71366 jmc 179
  Method selection does
45824 jmc 180
  not evaluate default expressions.
181
  All actual (non-missing) arguments in the signature of the
182
  generic function will be evaluated when a method is selected---when
183
  the call to \code{standardGeneric(f)} occurs.
71366 jmc 184
  Note that specifying class \code{"missing"} in the signature
185
  does not require any default expressions.
28652 jmc 186
 
187
  It is possible to have some differences between the
23678 jmc 188
  formal arguments to a method supplied to \code{setMethod} and those
189
  of the generic. Roughly, if the generic has \dots as one of its
190
  arguments, then the method may have extra formal arguments, which
191
  will be matched from the arguments matching \dots in the call to
192
  \code{f}.  (What actually happens is that a local function is
45824 jmc 193
  created inside the method, with the modified formal arguments, and the method
23678 jmc 194
  is re-defined to call that local function.)
26530 maechler 195
 
23678 jmc 196
  Method dispatch tries to match the class of the actual arguments in a
45824 jmc 197
  call to the available methods collected for \code{f}.  If there is a
198
  method defined for the exact same classes as in this call, that
199
  method is used.  Otherwise, all possible signatures are considered
200
  corresponding to the actual classes or to superclasses of the actual
201
  classes (including \code{"ANY"}).
202
  The method having the least distance from the actual classes is
203
  chosen; if more than one method has minimal distance, one is chosen
204
  (the lexicographically first in terms of superclasses) but a warning
205
  is issued.
206
  All inherited methods chosen are stored in another table, so that
207
  the inheritance calculations only need to be done once per session
208
  per sequence of actual classes.
209
  See
71366 jmc 210
  \link{Methods_Details} and Section 10.7 of the reference for more details.
23678 jmc 211
 
71366 jmc 212
}
45824 jmc 213
 
71366 jmc 214
\references{
88585 hornik 215
  \bibshow{R:Chambers:2016}
216
  (Chapters 9 and 10.)
15357 jmc 217
}
218
 
219
\examples{
71460 jmc 220
 
221
## examples for a simple class with two numeric slots.
222
## (Run example(setMethod) to see the class and function definitions)
223
\dontshow{
71228 maechler 224
  setClass("track", slots = c(x="numeric", y = "numeric"))
71460 jmc 225
 
226
  cumdist <- function(x, y) c(0., cumsum(sqrt(diff(x)^2 + diff(y)^2)))
71228 maechler 227
  setClass("trackMultiCurve", slots = c(x="numeric", y="matrix", smooth="matrix"),
228
          prototype = list(x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0)))
71460 jmc 229
 
230
require(graphics)
15357 jmc 231
}
17376 jmc 232
 
71460 jmc 233
## methods for plotting track objects 
15357 jmc 234
##
71460 jmc 235
## First, with only one object as argument, plot the two slots
236
##  y must be included in the signature, it would default to "ANY"
17376 jmc 237
setMethod("plot", signature(x="track", y="missing"),
71460 jmc 238
  function(x,  y, ...) plot(x@x, x@y, ...)
15357 jmc 239
)
71460 jmc 240
 
241
## plot numeric data on either axis against a track object
242
## (reducing the track object to the cumulative distance along the track)
243
## Using a short form for the signature, which matches like formal arguments
244
setMethod("plot", c("track", "numeric"),
245
 function(x, y, ...) plot(cumdist(x@x, x@y), y,  xlab = "Distance",...)
15357 jmc 246
)
71460 jmc 247
 
248
## and similarly for the other axis
249
setMethod("plot", c("numeric", "track"),
250
 function(x, y, ...) plot(x, cumdist(y@x, y@y),  ylab = "Distance",...)
15357 jmc 251
)
71460 jmc 252
 
17239 jmc 253
t1 <- new("track", x=1:20, y=(1:20)^2)
17376 jmc 254
plot(t1)
255
plot(qnorm(ppoints(20)), t1)
71460 jmc 256
 
257
## Now a class that inherits from "track", with a vector for data at
258
## the points 
259
  setClass("trackData", contains = c("numeric", "track"))
260
 
261
 
262
tc1 <- new("trackData", t1, rnorm(20))
263
 
264
 
265
## a method for plotting the object
266
## This method has an extra argument, allowed because ... is an
267
## argument to the generic function.
268
setMethod("plot", c("trackData", "missing"),
269
function(x, y, maxRadius = max(par("cin")), ...) {
270
  plot(x@x, x@y, type = "n", ...)
271
  symbols(x@x, x@y, circles = abs(x), inches = maxRadius)
15357 jmc 272
  }
273
)
71460 jmc 274
plot(tc1)
275
 
276
## Without other methods for "trackData", methods for "track"
277
## will be selected by inheritance
278
 
17376 jmc 279
plot(qnorm(ppoints(20)), tc1)
16576 jmc 280
 
71460 jmc 281
## defining methods for primitive function.
16707 jmc 282
## Although "[" and "length" are not ordinary functions
283
## methods can be defined for them.
16576 jmc 284
setMethod("[", "track",
285
  function(x, i, j, ..., drop) {
286
    x@x <- x@x[i]; x@y <- x@y[i]
287
    x
288
  })
17376 jmc 289
plot(t1[1:15])
16576 jmc 290
 
16707 jmc 291
setMethod("length", "track", function(x)length(x@y))
292
length(t1)
293
 
71460 jmc 294
## Methods for binary operators
295
## A method for the group generic "Ops" will apply to all operators
296
## unless a method for a more specific operator has been defined.
17761 jmc 297
 
71460 jmc 298
## For one trackData argument, go on with just the data part
299
setMethod("Ops", signature(e1 = "trackData"),
300
    function(e1, e2) callGeneric(e1@.Data, e2))
17761 jmc 301
 
71460 jmc 302
setMethod("Ops", signature(e2 = "trackData"),
303
    function(e1, e2) callGeneric(e1, e2@.Data))
17761 jmc 304
 
71460 jmc 305
## At this point, the choice of a method for a call with BOTH
306
## arguments from "trackData" is ambiguous.  We must define a method.
17761 jmc 307
 
71460 jmc 308
setMethod("Ops", signature(e1 = "trackData", e2 = "trackData"),
309
    function(e1, e2) callGeneric(e1@.Data, e2@.Data))
310
## (well, really we should only do this if the "track" part
311
## of the two arguments matched)
17761 jmc 312
 
71460 jmc 313
tc1 +1
39016 jmc 314
 
71460 jmc 315
1/tc1
16707 jmc 316
 
71460 jmc 317
all(tc1 == tc1)
16707 jmc 318
 
71460 jmc 319
\dontshow{
320
removeClass("trackData")
321
removeClass("track")
21001 jmc 322
}
323
}
324
 
41429 ripley 325
\seealso{
15357 jmc 326
 
71366 jmc 327
\link{Methods_for_Nongenerics} discusses method definition for
328
functions that are not generic functions in their original package;
329
\link{Methods_for_S3} discusses the integration of formal methods with the
330
older S3 methods.
331
 
45824 jmc 332
\code{\link{method.skeleton}}, which is the recommended way to generate a skeleton of the call to \code{setMethod}, with the correct formal arguments and other details.
41429 ripley 333
 
71366 jmc 334
\link{Methods_Details} and the links there for a general discussion, \code{\link{dotsMethods}} for methods that dispatch on
46315 jmc 335
  \dQuote{\dots}, and \code{\link{setGeneric}} for generic functions.
41429 ripley 336
}
40918 jmc 337
 
15357 jmc 338
\keyword{programming}
339
\keyword{classes}
340
\keyword{methods}