The R Project SVN R

Rev

Rev 71460 | Rev 88527 | Go to most recent revision | 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
 
38
  \code{valueClass}{ Obsolete. }
39
 
40
  \code{sealed}{ prevents the method being redefined, but should never
41
    be needed when the method is defined in the source code of a
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
98
in the \code{NAMESPACE} file for the package, with the arguments to
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
105
function that is not originally a generic function in its own package
106
(for example, \code{plot()} in the \code{graphics} package).  In this
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{
215
 Chambers, John M. (2016)
216
 \emph{Extending R},
217
  Chapman & Hall.
218
(Chapters 9 and 10.)
15357 jmc 219
}
220
 
221
\examples{
71460 jmc 222
 
223
## examples for a simple class with two numeric slots.
224
## (Run example(setMethod) to see the class and function definitions)
225
\dontshow{
71228 maechler 226
  setClass("track", slots = c(x="numeric", y = "numeric"))
71460 jmc 227
 
228
  cumdist <- function(x, y) c(0., cumsum(sqrt(diff(x)^2 + diff(y)^2)))
71228 maechler 229
  setClass("trackMultiCurve", slots = c(x="numeric", y="matrix", smooth="matrix"),
230
          prototype = list(x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0)))
71460 jmc 231
 
232
require(graphics)
15357 jmc 233
}
17376 jmc 234
 
71460 jmc 235
## methods for plotting track objects 
15357 jmc 236
##
71460 jmc 237
## First, with only one object as argument, plot the two slots
238
##  y must be included in the signature, it would default to "ANY"
17376 jmc 239
setMethod("plot", signature(x="track", y="missing"),
71460 jmc 240
  function(x,  y, ...) plot(x@x, x@y, ...)
15357 jmc 241
)
71460 jmc 242
 
243
## plot numeric data on either axis against a track object
244
## (reducing the track object to the cumulative distance along the track)
245
## Using a short form for the signature, which matches like formal arguments
246
setMethod("plot", c("track", "numeric"),
247
 function(x, y, ...) plot(cumdist(x@x, x@y), y,  xlab = "Distance",...)
15357 jmc 248
)
71460 jmc 249
 
250
## and similarly for the other axis
251
setMethod("plot", c("numeric", "track"),
252
 function(x, y, ...) plot(x, cumdist(y@x, y@y),  ylab = "Distance",...)
15357 jmc 253
)
71460 jmc 254
 
17239 jmc 255
t1 <- new("track", x=1:20, y=(1:20)^2)
17376 jmc 256
plot(t1)
257
plot(qnorm(ppoints(20)), t1)
71460 jmc 258
 
259
## Now a class that inherits from "track", with a vector for data at
260
## the points 
261
  setClass("trackData", contains = c("numeric", "track"))
262
 
263
 
264
tc1 <- new("trackData", t1, rnorm(20))
265
 
266
 
267
## a method for plotting the object
268
## This method has an extra argument, allowed because ... is an
269
## argument to the generic function.
270
setMethod("plot", c("trackData", "missing"),
271
function(x, y, maxRadius = max(par("cin")), ...) {
272
  plot(x@x, x@y, type = "n", ...)
273
  symbols(x@x, x@y, circles = abs(x), inches = maxRadius)
15357 jmc 274
  }
275
)
71460 jmc 276
plot(tc1)
277
 
278
## Without other methods for "trackData", methods for "track"
279
## will be selected by inheritance
280
 
17376 jmc 281
plot(qnorm(ppoints(20)), tc1)
16576 jmc 282
 
71460 jmc 283
## defining methods for primitive function.
16707 jmc 284
## Although "[" and "length" are not ordinary functions
285
## methods can be defined for them.
16576 jmc 286
setMethod("[", "track",
287
  function(x, i, j, ..., drop) {
288
    x@x <- x@x[i]; x@y <- x@y[i]
289
    x
290
  })
17376 jmc 291
plot(t1[1:15])
16576 jmc 292
 
16707 jmc 293
setMethod("length", "track", function(x)length(x@y))
294
length(t1)
295
 
71460 jmc 296
## Methods for binary operators
297
## A method for the group generic "Ops" will apply to all operators
298
## unless a method for a more specific operator has been defined.
17761 jmc 299
 
71460 jmc 300
## For one trackData argument, go on with just the data part
301
setMethod("Ops", signature(e1 = "trackData"),
302
    function(e1, e2) callGeneric(e1@.Data, e2))
17761 jmc 303
 
71460 jmc 304
setMethod("Ops", signature(e2 = "trackData"),
305
    function(e1, e2) callGeneric(e1, e2@.Data))
17761 jmc 306
 
71460 jmc 307
## At this point, the choice of a method for a call with BOTH
308
## arguments from "trackData" is ambiguous.  We must define a method.
17761 jmc 309
 
71460 jmc 310
setMethod("Ops", signature(e1 = "trackData", e2 = "trackData"),
311
    function(e1, e2) callGeneric(e1@.Data, e2@.Data))
312
## (well, really we should only do this if the "track" part
313
## of the two arguments matched)
17761 jmc 314
 
71460 jmc 315
tc1 +1
39016 jmc 316
 
71460 jmc 317
1/tc1
16707 jmc 318
 
71460 jmc 319
all(tc1 == tc1)
16707 jmc 320
 
71460 jmc 321
\dontshow{
322
removeClass("trackData")
323
removeClass("track")
21001 jmc 324
}
325
}
326
 
41429 ripley 327
\seealso{
15357 jmc 328
 
71366 jmc 329
\link{Methods_for_Nongenerics} discusses method definition for
330
functions that are not generic functions in their original package;
331
\link{Methods_for_S3} discusses the integration of formal methods with the
332
older S3 methods.
333
 
45824 jmc 334
\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 335
 
71366 jmc 336
\link{Methods_Details} and the links there for a general discussion, \code{\link{dotsMethods}} for methods that dispatch on
46315 jmc 337
  \dQuote{\dots}, and \code{\link{setGeneric}} for generic functions.
41429 ripley 338
}
40918 jmc 339
 
15357 jmc 340
\keyword{programming}
341
\keyword{classes}
342
\keyword{methods}