The R Project SVN R

Rev

Rev 56382 | Rev 69636 | 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
2
% Part of the R package, http://www.R-project.org
59039 ripley 3
% Copyright 1995-2007 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
15357 jmc 6
\name{setMethod}
56186 murdoch 7
\alias{setMethod}
17454 jmc 8
\alias{removeMethod}
15357 jmc 9
\title{ Create and Save a Method }
10
\description{
11
  Create and save a formal method for a given function and list of classes.
12
}
13
\usage{
30912 ripley 14
setMethod(f, signature=character(), definition,
15
          where = topenv(parent.frame()),
26530 maechler 16
          valueClass = NULL, sealed = FALSE)
17454 jmc 17
 
18
removeMethod(f, signature, where)
15357 jmc 19
}
20
\arguments{
39342 jmc 21
  \item{f}{ A generic function or the character-string name of the function. }
15357 jmc 22
  \item{signature}{ A match of formal argument names for \code{f} with
45824 jmc 23
    the character-string names of corresponding classes.  See the
24
    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 25
  \item{definition}{ A function definition, which will become the method
19029 hornik 26
    called when the arguments in a call to \code{f} match the
27
    classes in \code{signature}, directly or through inheritance. }
45824 jmc 28
  \item{where}{the environment in which to store the definition of the
29
    method.
30
For \code{setMethod}, it is recommended to omit this argument and to include the call in source code that is evaluated at the top level; that is, either in an R session by something equivalent to a call to \code{\link{source}}, or as part of the R source code for a package.
17454 jmc 31
 
19029 hornik 32
    For \code{removeMethod}, the default is the location of the (first)
33
    instance of the method for this signature.}
45824 jmc 34
  \item{valueClass}{ Obsolete and unused, but see the same argument for \code{\link{setGeneric}}. }
23493 jmc 35
  \item{sealed}{ If \code{TRUE}, the method so defined cannot be
36
      redefined by another call to \code{setMethod} (although it can
45824 jmc 37
      be removed and then re-assigned).}
15357 jmc 38
}
17454 jmc 39
\value{
19029 hornik 40
  These functions exist for their side-effect, in setting or removing a
41
  method in the object defining methods for the specified generic.
17454 jmc 42
 
19029 hornik 43
  The value returned by \code{removeMethod} is \code{TRUE} if a method
44
  was found to be removed.
17454 jmc 45
}
15357 jmc 46
\details{
45824 jmc 47
The call to \code{setMethod} stores the supplied method definition  in
48
the metadata table for this generic function in the environment,
56382 murdoch 49
typically the global environment or the namespace of a package.
50
In the case of a package, the table object becomes part of the namespace or environment of the
45824 jmc 51
package.
52
When the package is loaded into a later session, the
53
methods will be merged into the table of methods in the corresponding
54
generic function object.
15357 jmc 55
 
45824 jmc 56
Generic functions are referenced by the combination of the function name and
57
the package name;
58
for example, the function \code{"show"} from the package
59
\code{"methods"}.
60
Metadata for methods is identified by the two strings; in particular, the
61
generic function object itself has slots containing its name and its
62
package name.
63
The package name of a generic is set according to the package
64
from which it originally comes; in particular, and frequently, the
65
package where a non-generic version of the function originated.
49587 hornik 66
For example, generic functions for all the functions in package \pkg{base} will
45824 jmc 67
have \code{"base"} as the package name, although none of them is an
68
S4 generic on that package.
48062 jmc 69
These include most of the base functions that are primitives, rather than
70
true functions; see the section on primitive functions in the
71
documentation for \code{\link{setGeneric}} for details.
23678 jmc 72
 
45824 jmc 73
Multiple packages can have methods for the same generic function; that
74
is, for the same combination of generic function name and package
75
name.
76
Even though the methods are stored in separate tables in separate
77
environments, loading the corresponding packages adds the methods to
78
the table in the generic function itself, for the duration of the session.
79
 
23678 jmc 80
 The class
45824 jmc 81
  names in the signature can be any formal class, including basic
15357 jmc 82
  classes such as \code{"numeric"}, \code{"character"}, and
83
  \code{"matrix"}.  Two additional special class names can appear:
84
  \code{"ANY"}, meaning that this argument can have any class at all;
85
  and \code{"missing"}, meaning that this argument \emph{must not}
86
  appear in the call in order to match this signature.  Don't confuse
87
  these two:  if an argument isn't mentioned in a signature, it
88
  corresponds implicitly to class \code{"ANY"}, not to
42963 ripley 89
  \code{"missing"}.  See the example below.  Old-style (\sQuote{S3})
25118 hornik 90
  classes can also be used, if you need compatibility with these, but
91
  you should definitely declare these classes by calling
23678 jmc 92
  \code{\link{setOldClass}} if you want S3-style inheritance to work.
15357 jmc 93
 
23678 jmc 94
 
28652 jmc 95
  Method definitions can
45824 jmc 96
  have default expressions for arguments, but a current limitation is
97
  that the generic function must have \emph{some} default expression for the
98
  same argument in order for the method's defaults to be used.
99
  If so, and if the corresponding argument is
28652 jmc 100
  missing in the call to the generic function, the default expression
101
  in the method is used.  If the method definition has no default for
45824 jmc 102
  the argument, then the expression supplied in the definition of the
103
  generic function itself is used, but note that this expression will
104
  be evaluated using the enclosing environment of the method, not of
105
  the generic function.
106
  Note also that specifying class \code{"missing"} in the signature
107
  does not require any default expressions, and method selection does
108
  not evaluate default expressions.
109
  All actual (non-missing) arguments in the signature of the
110
  generic function will be evaluated when a method is selected---when
111
  the call to \code{standardGeneric(f)} occurs.
28652 jmc 112
 
113
  It is possible to have some differences between the
23678 jmc 114
  formal arguments to a method supplied to \code{setMethod} and those
115
  of the generic. Roughly, if the generic has \dots as one of its
116
  arguments, then the method may have extra formal arguments, which
117
  will be matched from the arguments matching \dots in the call to
118
  \code{f}.  (What actually happens is that a local function is
45824 jmc 119
  created inside the method, with the modified formal arguments, and the method
23678 jmc 120
  is re-defined to call that local function.)
26530 maechler 121
 
23678 jmc 122
  Method dispatch tries to match the class of the actual arguments in a
45824 jmc 123
  call to the available methods collected for \code{f}.  If there is a
124
  method defined for the exact same classes as in this call, that
125
  method is used.  Otherwise, all possible signatures are considered
126
  corresponding to the actual classes or to superclasses of the actual
127
  classes (including \code{"ANY"}).
128
  The method having the least distance from the actual classes is
129
  chosen; if more than one method has minimal distance, one is chosen
130
  (the lexicographically first in terms of superclasses) but a warning
131
  is issued.
132
  All inherited methods chosen are stored in another table, so that
133
  the inheritance calculations only need to be done once per session
134
  per sequence of actual classes.
135
  See
23678 jmc 136
  \link{Methods} for more details.
137
 
45824 jmc 138
The function \code{removeMethod} removes the specified method from the
139
metadata table in the corresponding environment.
140
It's not a function that is used much, since one normally wants to
141
redefine a method rather than leave no definition.
142
 
15357 jmc 143
}
144
\references{
45824 jmc 145
 Chambers, John M. (2008)
146
 \emph{Software for Data Analysis: Programming with R}
147
  Springer.  (For the R version.)
15357 jmc 148
 
45824 jmc 149
 Chambers, John M. (1998)
150
 \emph{Programming with Data}
151
 Springer (For the original S4 version.)
15357 jmc 152
}
153
\examples{
27464 ripley 154
\dontshow{  require(stats)
15357 jmc 155
  setClass("track",
156
    representation(x="numeric", y = "numeric"))
17454 jmc 157
  setClass("trackCurve", representation("track",
158
    smooth = "numeric"))
21001 jmc 159
  setClass("trackMultiCurve", representation(x="numeric", y="matrix", smooth="matrix"),
160
          prototype = list(x=numeric(), y=matrix(0,0,0), smooth=
161
  matrix(0,0,0)))
15357 jmc 162
}
17376 jmc 163
 
41508 ripley 164
require(graphics)
15357 jmc 165
## methods for plotting track objects (see the example for \link{setClass})
166
##
167
## First, with only one object as argument:
17376 jmc 168
setMethod("plot", signature(x="track", y="missing"),
169
  function(x,  y, ...) plot(slot(x, "x"), slot(x, "y"), ...)
15357 jmc 170
)
171
## Second, plot the data from the track on the y-axis against anything
172
## as the x data.
17376 jmc 173
setMethod("plot", signature(y = "track"),
174
 function(x, y, ...) plot(x, slot(y, "y"), ...)
15357 jmc 175
)
176
## and similarly with the track on the x-axis (using the short form of
177
## specification for signatures)
17376 jmc 178
setMethod("plot", "track",
179
 function(x, y, ...) plot(slot(x, "y"), y,  ...)
15357 jmc 180
)
17239 jmc 181
t1 <- new("track", x=1:20, y=(1:20)^2)
15357 jmc 182
tc1 <- new("trackCurve", t1)
16707 jmc 183
slot(tc1, "smooth") <- smooth.spline(slot(tc1, "x"), slot(tc1, "y"))$y #$
17376 jmc 184
plot(t1)
185
plot(qnorm(ppoints(20)), t1)
18151 jmc 186
## An example of inherited methods, and of conforming method arguments
187
## (note the dotCurve argument in the method, which will be pulled out
188
## of ... in the generic.
17376 jmc 189
setMethod("plot", c("trackCurve", "missing"),
18151 jmc 190
function(x, y, dotCurve = FALSE, ...) {
17376 jmc 191
  plot(as(x, "track"))
15357 jmc 192
  if(length(slot(x, "smooth") > 0))
18151 jmc 193
    lines(slot(x, "x"), slot(x, "smooth"),
194
         lty = if(dotCurve) 2 else 1)
15357 jmc 195
  }
196
)
197
## the plot of tc1 alone has an added curve; other uses of tc1
198
## are treated as if it were a "track" object.
18151 jmc 199
plot(tc1, dotCurve = TRUE)
17376 jmc 200
plot(qnorm(ppoints(20)), tc1)
16576 jmc 201
 
202
## defining methods for a special function.
16707 jmc 203
## Although "[" and "length" are not ordinary functions
204
## methods can be defined for them.
16576 jmc 205
setMethod("[", "track",
206
  function(x, i, j, ..., drop) {
207
    x@x <- x@x[i]; x@y <- x@y[i]
208
    x
209
  })
17376 jmc 210
plot(t1[1:15])
16576 jmc 211
 
16707 jmc 212
setMethod("length", "track", function(x)length(x@y))
213
length(t1)
214
 
17761 jmc 215
## methods can be defined for missing arguments as well
216
setGeneric("summary") ## make the function into a generic
217
 
218
## A method for summary()
219
## The method definition can include the arguments, but
220
## if they're omitted, class "missing" is assumed.
221
 
222
setMethod("summary", "missing", function() "<No Object>")
223
 
26000 ripley 224
\dontshow{
17761 jmc 225
 
226
stopifnot(identical(summary(), "<No Object>"))
227
 
39016 jmc 228
removeMethods("summary")
229
 
16707 jmc 230
## for the primitives
231
## inherited methods
232
 
233
length(tc1)
234
tc1[-1]
235
 
16576 jmc 236
## make sure old-style methods still work.
237
t11 <- t1[1:15]
238
identical(t1@y[1:15], t11@y)
239
 
240
## S3 methods, with nextMethod
241
form <- y ~ x
242
form[1]
16866 jmc 243
 
244
## S3 arithmetic methods
245
ISOdate(1990, 12, 1)- ISOdate(1980, 12, 1)
246
 
19473 jmc 247
## group methods
16866 jmc 248
 
19473 jmc 249
setMethod("Arith", c("track", "numeric"), function(e1, e2){e1@y <-
250
  callGeneric(e1@y , e2); e1})
16866 jmc 251
 
19473 jmc 252
 
16866 jmc 253
t1  - 100.
254
 
19473 jmc 255
t1/2
256
 
257
 
16866 jmc 258
## check it hasn't screwed up S3 methods
259
ISOdate(1990, 12, 1)- ISOdate(1980, 12, 1)
260
 
21865 jmc 261
## test the .Generic mechanism
262
 
263
setMethod("Compare", signature("track", "track"),
264
  function(e1,e2) {
265
  switch(.Generic,
266
   "==" = e1@y == e2@y,
267
  NA)
268
 })
269
 
270
#stopifnot(all(t1==t1))
271
#stopifnot(identical(t1<t1, NA))
272
 
273
 
21001 jmc 274
## A test of nested calls to "[" with matrix-style arguments
275
## applied to data.frames (S3 methods)
276
 
277
setMethod("[", c("trackMultiCurve", "numeric", "numeric"), function(x, i, j, ..., drop) {
278
### FIXME:  a better version has only 1st arg in signature
279
### and uses callNextMethod, when this works with primitives.
280
    x@y <- x@y[i, j, drop=FALSE]
281
    x@x <- x@x[i]
282
    x
283
})
284
 
285
 
286
"testFunc" <-
287
function(cur) {
288
    sorted <- cur[order(cur[,1]),]
289
    sorted[ !is.na(sorted[,1]), ]
290
}
291
 
292
Nrow <- 1000 # at one time, values this large triggered a bug in gc/protect
293
## the loop here was a trigger for the bug
294
Niter <- 10
295
for(i in 1:Niter)  {
41508 ripley 296
    yy <- matrix(stats::rnorm(10*Nrow), 10, Nrow)
21001 jmc 297
    tDF <- as.data.frame(yy)
298
    testFunc(tDF)
299
}
300
 
301
 
41621 ripley 302
tMC <- new("trackMultiCurve", x=seq_len(Nrow), y = yy)
21001 jmc 303
## not enough functions have methods for this class to use testFunc
304
 
305
stopifnot(identical(tMC[1:10, 1:10]@y, yy[1:10, 1:10]))
306
 
307
 
17454 jmc 308
## verify we can remove methods and generic
309
 
17761 jmc 310
removeMethods("-")
23305 ripley 311
removeMethod("length", "track")
21865 jmc 312
removeMethods("Arith")
313
removeMethods("Compare")
17454 jmc 314
 
17761 jmc 315
## repeat the test one more time on the primitives
316
 
317
length(ISOdate(1990, 12, 1)- ISOdate(1980, 12, 1))
318
 
39016 jmc 319
removeMethods("length")
320
 
46908 murdoch 321
## methods for \%*\%, which isn't done by the same C code as other ops
21875 jmc 322
 
323
setClass("foo", representation(m="matrix"))
324
m1 <- matrix(1:12,3,4)
325
f1 = new("foo", m=m1)
326
f2 = new("foo", m=t(m1))
327
 
328
setMethod("\%*\%", c("foo", "foo"),
329
 function(x,y)callGeneric(x@m, y@m))
330
 
331
stopifnot(identical(f1\%*\%f2, m1\%*\% t(m1)))
332
 
333
removeMethods("\%*\%")
334
 
17761 jmc 335
removeMethods("plot")
336
 
45720 jmc 337
## Hold until removeMethods revised: stopifnot(existsFunction("plot", FALSE) && !isGeneric("plot", 1))
17761 jmc 338
 
17454 jmc 339
## methods for plotData
340
plotData <- function(x, y, ...) plot(x, y, ...)
341
 
342
setGeneric("plotData")
343
 
344
setMethod("plotData", signature(x="track", y="missing"),
345
  function(x,  y, ...) plot(slot(x, "x"), slot(x, "y"), ...)
346
)
347
## and now remove the whole generic
17761 jmc 348
removeGeneric("plotData")
349
 
17454 jmc 350
stopifnot(!exists("plotData", 1))
351
 
18413 jmc 352
##  Tests of method inheritance & multiple dispatch
353
setClass("A0", representation(a0 = "numeric"))
18380 jmc 354
 
18413 jmc 355
setClass("A1", representation("A0", a1 = "character"))
356
 
357
setClass("B0" ,representation(b0 = "numeric"))
358
 
359
setClass("B1", "B0")
360
 
361
setClass("B2", representation("B1", b2 = "logical"))
362
 
363
setClass("AB0", representation("A1", "B2", ab0 = "matrix"))
364
 
365
f1 <- function(x,  y)"ANY"
366
 
367
setGeneric("f1")
368
 
369
setMethod("f1", c("A0", "B1"), function(x, y)"A0 B1")
370
setMethod("f1", c("B1", "A0"), function(x, y)"B1 A0")
371
 
372
a0 <- new("A0")
373
a1 <- new("A1")
374
b0 <- new("B0")
375
b1 <- new("B1")
376
b2 <- new("B2")
377
 
378
deparseText <- function(expr)
379
    paste(deparse(expr), collapse = "\\  ")
380
 
381
mustEqual <- function(e1, e2){
382
    if(!identical(e1, e2))
383
        stop(paste("!identical(", deparseText(substitute(e1)),
384
                   ", ", deparseText(substitute(e2)), ")", sep=""))
15357 jmc 385
}
18413 jmc 386
 
387
mustEqual(f1(a0, b0), "ANY")
388
mustEqual(f1(a1,b0), "ANY")
389
mustEqual(f1(a1,b1), "A0 B1")
390
mustEqual(f1(b1,a1), "B1 A0")
391
mustEqual(f1(b1,b1), "ANY")
392
 
20330 jmc 393
## remove classes:  order matters so as not to undefine earlier classes
394
for(.cl in c("AB0", "A1", "A0", "B2", "B1", "B0"))
18413 jmc 395
    removeClass(.cl)
396
 
397
removeGeneric("f1")
398
 
19670 jmc 399
## test of nonstandard generic definition
18413 jmc 400
 
19670 jmc 401
setGeneric("doubleAnything", function(x) {
402
  methodValue <- standardGeneric("doubleAnything")
403
  c(methodValue, methodValue)
404
})
18413 jmc 405
 
19670 jmc 406
setMethod("doubleAnything", "ANY", function(x)x)
407
 
408
setMethod("doubleAnything", "character",
409
function(x)paste("<",x,">",sep=""))
410
 
411
mustEqual(doubleAnything(1:10), c(1:10, 1:10))
412
mustEqual(doubleAnything("junk"), rep("<junk>",2))
413
 
414
removeGeneric("doubleAnything")
415
 
416
 
16576 jmc 417
}
18413 jmc 418
}
15357 jmc 419
 
41429 ripley 420
\seealso{
15357 jmc 421
 
45824 jmc 422
\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 423
 
46314 jmc 424
\link{Methods} and the links there for a general discussion, \code{\link{dotsMethods}} for methods that dispatch on
46315 jmc 425
  \dQuote{\dots}, and \code{\link{setGeneric}} for generic functions.
41429 ripley 426
}
40918 jmc 427
 
15357 jmc 428
\keyword{programming}
429
\keyword{classes}
430
\keyword{methods}