The R Project SVN R

Rev

Rev 59039 | 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/Methods.Rd
2
% Part of the R package, http://www.R-project.org
59039 ripley 3
% Copyright 1995-2010 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
15357 jmc 6
\name{Methods}
56186 murdoch 7
\alias{Methods}
17000 jmc 8
\title{General Information on Methods}
15357 jmc 9
\description{
19029 hornik 10
  This documentation section covers some general topics on how methods
51712 ripley 11
  work and how the \pkg{methods} package interacts with the rest of \R.  The
19029 hornik 12
  information is usually not needed to get started with methods and
13
  classes, but may be helpful for moderately ambitious projects, or when
14
  something doesn't work as expected.
15357 jmc 15
 
45824 jmc 16
  The section \dQuote{How Methods Work} describes the underlying
52266 jmc 17
  mechanism; \dQuote{S3 Methods and Generic Functions} gives the rules applied when S4
48409 jmc 18
  classes and methods interact with older S3 methods; \dQuote{Method Selection and Dispatch} provides more
45824 jmc 19
  details on how class definitions determine which methods are used;
20
  \dQuote{Generic Functions} discusses generic functions as objects.
21
  For additional information specifically about class definitions, see \code{\link{Classes}}.
39016 jmc 22
}
16764 jmc 23
 
24
\section{How Methods Work}{
45824 jmc 25
  A generic function  has associated with it a
26
  collection of other functions (the methods), all of which have the same
27
  formal arguments as the generic.  See the \dQuote{Generic
28
    Functions} section below for more on generic functions themselves.
39016 jmc 29
 
51712 ripley 30
  Each \R package will include  methods metadata objects
39016 jmc 31
  corresponding to each generic function  for which methods have been
32
  defined in that package.
51712 ripley 33
  When the package is loaded into an \R session, the methods for each
39016 jmc 34
  generic function are \emph{cached}, that is, stored in the
35
  environment of the generic function along with the methods from
36
  previously loaded packages.  This merged table of methods is used to
37
  dispatch or select methods from the generic, using class inheritance
41161 maechler 38
  and possibly group generic functions (see
45824 jmc 39
  \code{\link{GroupGenericFunctions}}) to find an applicable method.
40
  See the \dQuote{Method Selection and Dispatch} section below.
39342 jmc 41
  The caching computations ensure that only one version of each
42
  generic function is visible globally; although different attached
45824 jmc 43
  packages may contain a copy of the generic function, these behave
44
  identically with respect to method selection.
45
  In contrast, it is possible for the same function name to refer to
46
  more than one generic function, when these have different
47
  \code{package} slots.  In the latter case, \R considers the
48
  functions unrelated:  A generic function is defined by the
49
  combination of name and package.  See the \dQuote{Generic Functions}
50
  section below.
16764 jmc 51
 
39016 jmc 52
  The methods for a generic are stored according to the
45824 jmc 53
  corresponding \code{signature} in the call to \code{\link{setMethod}}
54
 that defined  the method.  The signature associates one
39016 jmc 55
  class name with each of a subset of the formal arguments to the
56
  generic function.  Which formal arguments are available, and the
57
  order in which they appear, are determined by the \code{"signature"}
45824 jmc 58
  slot of the generic function itself.  By default, the signature of the
39342 jmc 59
  generic consists of all the formal arguments except \dots, in the
39016 jmc 60
  order they appear in the function definition.
16764 jmc 61
 
45824 jmc 62
  Trailing arguments in the signature of the generic will be \emph{inactive}  if no
63
  method has yet been specified that included those arguments in its signature.
39016 jmc 64
  Inactive arguments are not needed or used in labeling the cached
65
  methods.  (The distinction does not change which methods are
45824 jmc 66
  dispatched, but ignoring inactive arguments improves the
67
  efficiency of dispatch.)
16764 jmc 68
 
39342 jmc 69
  All arguments in the signature of the generic function will be evaluated when the
70
  function is called, rather than using the traditional lazy
39016 jmc 71
  evaluation rules of S.  Therefore, it's important to \emph{exclude}
72
  from the signature any arguments that need to be dealt with
73
  symbolically (such as the first argument to function
39342 jmc 74
  \code{\link{substitute}}).  Note that only actual arguments are
39016 jmc 75
  evaluated, not default expressions.
76
  A missing argument enters into the method selection as class
45824 jmc 77
  \code{"missing"}.
16764 jmc 78
 
45824 jmc 79
  The cached methods are stored in an
39016 jmc 80
  environment object.  The names used for assignment are a
45824 jmc 81
  concatenation of the class names for the active arguments in the method signature.
16764 jmc 82
 
39016 jmc 83
}
48117 jmc 84
 
52266 jmc 85
\section{Methods for S3 Generic Functions}{
48117 jmc 86
 
52266 jmc 87
S4 methods may be wanted for functions that also have S3 methods, corresponding to classes for the first
88
formal argument of an S3 generic function--either a regular R function in which there is a
89
call to the S3 dispatch function, \code{\link{UseMethod}},
90
or one of a fixed set of primitive
91
functions, which are not true functions but go directly to C code.
92
In either case S3 method dispatch looks at the class of the first
93
argument or the class of either
94
argument in a call to one of the primitive binary operators.
95
S3 methods are ordinary functions with the same arguments as the
96
generic function (for primitives the formal arguments are not actually
97
part of the object, but are simulated when the object is printed or
98
viewed by \code{\link{args}()}).
99
The \dQuote{signature} of an S3 method is identified  by the name to
100
which the method is assigned, composed of the name of the
101
generic function, followed by \code{"."}, followed by the name of the class.
102
For details, see \link{S3Methods}.
48117 jmc 103
 
52266 jmc 104
To implement a method for one of these functions corresponding to S4
105
classes, there are two possibilities: either an S4 method or an S3 method with the
106
S4 class name.
107
The S3 method is only possible if the intended signature has the
108
first argument and nothing else.
109
In this case,
110
the recommended approach is to define the S3 method and also supply the
111
identical function as the definition of the S4 method.
112
If the S3 generic function was \code{f3(x, ...)} and the S4 class for
61433 ripley 113
the new method was
52266 jmc 114
\code{"myClass"}:
48117 jmc 115
 
52266 jmc 116
 \code{f3.myClass <- function(x, ...) { ..... }}
48117 jmc 117
 
52267 jmc 118
 \code{setMethod("f3", "myClass", f3.myClass)}
48117 jmc 119
 
52266 jmc 120
The reasons for defining both S3 and S4 methods are as follows:
121
\enumerate{
122
  \item An S4 method alone will not be seen if the S3 generic function
123
    is called directly.  However, primitive functions and operators
124
    are exceptions:  The internal C code will look for S4 methods
125
    if and only if the object is an S4 object.  In the examples, the method
126
    for \code{`[`} for class \code{"myFrame"} will always be called
127
    for objects of this class.
48117 jmc 128
 
52266 jmc 129
    For the same reason, an S4 method defined for an S3 class will not be called from
130
    internal code for a non-S4 object. (See the example for function
131
    \code{Math} and
132
    class \code{"data.frame"} in the examples.)
133
  \item An S3 method alone will not be called if there is \emph{any}
134
    eligible non-default S4 method. (See the example for function
135
    \code{f3} and class \code{"classA"} in the examples.)
136
}
137
Details of the selection computations are given below.
48409 jmc 138
 
52266 jmc 139
When an S4 method is defined for an existing function that is not an
140
S4 generic function (whether or not the existing function is an S3 generic),
141
an S4 generic function will be created corresponding to the existing
142
function and the package in which it is found (more precisely,
143
according to the implicit generic function either specified or
144
inferred from the ordinary function; see \code{\link{implicitGeneric}}).
145
A message is printed after the initial call to
146
\code{\link{setMethod}}; this is not an error, just a reminder that
147
you have created the generic.
148
Creating the generic explicitly by the call
48409 jmc 149
 
52266 jmc 150
  \code{setGeneric("f3")}
48409 jmc 151
 
52266 jmc 152
avoids the message, but has the same effect.
153
The existing function becomes the default method for
154
the S4 generic function.
155
Primitive functions work the same way, but
156
the S4 generic function is not explicitly created (as discussed below).
48409 jmc 157
 
158
 
52266 jmc 159
S4 and S3 method selection are designed to follow compatible rules of
160
inheritance, as far as possible.
161
S3 classes can be used for any S4 method selection, provided that the
162
S3 classes have been registered by a call to
163
\code{\link{setOldClass}}, with that call specifying the correct S3
164
inheritance pattern.
165
S4 classes can be used for any S3 method selection; when an S4 object
166
is detected, S3 method selection uses the contents of
167
\code{\link{extends}(class(x))} as the equivalent of the S3
168
inheritance (the inheritance is cached after the first call).
48409 jmc 169
 
52266 jmc 170
An existing S3 method may not behave as desired for an S4 subclass, in
171
which case utilities such as \code{\link{asS3}} and
172
\code{\link{S3Part}} may be useful.  If the S3 method fails on the S4
173
object, \code{asS3(x)} may be passed instead; if the object returned
174
by the S3 method needs to be incorporated in the S4 object, the
175
replacement function for \code{S3Part} may be useful, as in the method
176
for class \code{"myFrame"} in the examples.
48409 jmc 177
 
52266 jmc 178
Here are details explaining the reasons for defining both S3 and S4 methods.
179
Calls still accessing the S3 generic function
180
directly will not see S4 methods, except in the case of primitive
181
functions.
182
This means that calls to the generic function from namespaces that
183
import the S3 generic but not the S4 version will only see S3
184
methods.
185
On the other hand, S3 methods will only be selected from the
186
S4 generic function as part of its default (\code{"ANY"}) method.
187
If there are inherited S4 non-default methods, these will be chosen in
188
preference to \emph{any} S3 method.
48409 jmc 189
 
52266 jmc 190
S3 generic functions implemented as primitive functions (including
191
binary operators) are an exception to recognizing only
192
S3 methods.
193
These functions dispatch both S4 and S3 methods from
194
the internal C code.
195
There is no explicit generic function, either S3 or S4.
196
The internal code looks for S4 methods if the first
197
argument, or either of the arguments in the case of a binary operator,
198
is an S4 object.
199
If no S4 method is found, a search is made for an S3 method.
48409 jmc 200
 
52266 jmc 201
S4 methods can be defined for an S3 generic function and an S3 class,
202
but if the function is a primitive, such methods will not be selected
203
if the object in question is not an S4 object.
204
In the examples below, for instance,  an S4 method for signature
205
\code{"data.frame"} for function \code{f3()} would be called for the
206
S3 object \code{df1}.
207
A similar S4 method for primitive function
208
\code{`[`} would be ignored for that object, but would be called for
209
the S4 object \code{mydf1} that inherits from \code{"data.frame"}.
210
Defining both an S3 and S4 method removes this inconsistency.
48409 jmc 211
 
212
 
48117 jmc 213
}
48409 jmc 214
\section{Method Selection and Dispatch: Details}{
16764 jmc 215
 
39016 jmc 216
When a call to a generic function is evaluated, a method is selected corresponding
217
to the classes of the actual arguments in the signature.
45824 jmc 218
First, the cached methods table is searched for an  exact match;
219
that is, a method stored under the signature defined by
220
the string value of \code{class(x)} for each non-missing
221
argument, and \code{"missing"} for each missing argument.
16764 jmc 222
If no method is found directly for the actual arguments in a call to a
223
generic function, an attempt is made to match the available methods to
45824 jmc 224
the arguments by using the superclass information about the actual classes.
16764 jmc 225
 
45824 jmc 226
Each class definition may include a list of  one or more
227
\emph{superclasses} of the new class.
228
The simplest and most common specification is by the \code{contains=} argument in
229
the  call to \code{\link{setClass}}.
230
Each class named in this argument is a superclass of the new class.
52266 jmc 231
Two additional mechanisms for defining
232
superclasses exist.
233
A call to \code{\link{setClassUnion}} creates a union class that
234
is a
235
superclass of each of the members of the union.
61433 ripley 236
 A call to
45824 jmc 237
\code{\link{setIs}} can create an inheritance relationship that is not the simple one of
238
containing the superclass representation in the new class.
52266 jmc 239
Arguments \code{coerce} and \code{replace} supply methods to convert
240
to the superclass and to replace the part corresponding to the superclass.
241
(In addition, a \code{test=} argument allows conditional inheritance;  conditional inheritance is not
242
recommended and is not used in method selection.)
39016 jmc 243
All three mechanisms are treated equivalently for purposes of
45824 jmc 244
method selection:  they define the \emph{direct} superclasses of a
39016 jmc 245
particular class.
45824 jmc 246
For more details on the mechanisms, see \code{\link{Classes}}.
23678 jmc 247
 
39016 jmc 248
The direct superclasses themselves may
45824 jmc 249
have superclasses, defined by any of the same mechanisms, and
52266 jmc 250
similarly through further generations.  Putting all this information together produces
41161 maechler 251
the full list of superclasses for this class.
39016 jmc 252
The superclass list is included in the definition of the class that is
51712 ripley 253
cached during the \R session.
39016 jmc 254
Each element of the list describes the nature of the relationship (see
45824 jmc 255
\code{\linkS4class{SClassExtension}} for details).
52266 jmc 256
Included in the element is a \code{distance} slot containing
257
the path length for the relationship:
39016 jmc 258
\code{1} for direct superclasses (regardless of which mechanism
259
defined them), then \code{2} for the direct superclasses of those
260
classes, and so on.
261
In addition, any class implicitly has class \code{"ANY"} as a superclass.  The
262
distance to \code{"ANY"} is treated as larger than the distance to any
263
actual class.
264
The special class \code{"missing"} corresponding to missing arguments
265
has only \code{"ANY"} as a superclass, while \code{"ANY"} has no
266
superclasses.
16764 jmc 267
 
47803 jmc 268
When a class definition is created or modified, the superclasses
269
are ordered, first by a stable sort of the all superclasses by
270
distance.
271
If the set of superclasses has duplicates (that is, if some class is
272
inherited through more than one relationship), these are removed, if
273
possible, so that the list of superclasses is consistent with the
274
superclasses of all direct superclasses.
275
See the reference on inheritance for details.
276
 
39016 jmc 277
The information about superclasses is summarized when a class
278
definition is printed.
16764 jmc 279
 
39016 jmc 280
When a method is to be selected by inheritance, a search is made in
281
the table for all methods directly corresponding to a combination of
282
either the direct class or one of its superclasses, for each argument
283
in the active signature.
39342 jmc 284
For an example, suppose there is only one argument in the signature and that the class of
48409 jmc 285
the corresponding object was \code{"dgeMatrix"} (from the recommended package
286
\code{Matrix}).
39257 jmc 287
This class has two direct superclasses and through these 4 additional superclasses.
39016 jmc 288
Method selection finds all the methods in the table of directly
39257 jmc 289
specified methods labeled by one of these classes, or by
39016 jmc 290
\code{"ANY"}.
16764 jmc 291
 
39016 jmc 292
When there are multiple arguments in the signature, each argument will
293
generate a similar  list of inherited classes.
39342 jmc 294
The possible matches are now all the combinations of classes from each
39016 jmc 295
argument (think of the function \code{outer} generating an array of
39342 jmc 296
all possible combinations).
297
The search now finds all the methods matching any of this combination
39016 jmc 298
of classes.
47803 jmc 299
For each argument, the position in the list of superclasses of that
300
argument's class defines which method or methods (if the same class
301
appears more than once) match best.
302
When there is only one argument, the best match is unambiguous.
303
With more than one argument, there may be zero or one match that is
304
among the best matches for \emph{all} arguments.
23678 jmc 305
 
47803 jmc 306
If there is no best match, the selection is ambiguous and a message is
307
printed noting which method was selected (the first method
52266 jmc 308
lexicographically in the ordering) and what other methods could have
47803 jmc 309
been selected.
310
Since the ambiguity is usually nothing the end user could control,
311
this is not a warning.
312
Package authors should examine their package for possible ambiguous
313
inheritance by calling \code{\link{testInheritedMethods}}.
23678 jmc 314
 
39016 jmc 315
When the inherited method has been selected, the selection is cached
316
in the generic function so that future calls with the same class will
45824 jmc 317
not require repeating the search.  Cached inherited selections are
318
not themselves used in future inheritance searches, since that could result
39016 jmc 319
in invalid selections.
45824 jmc 320
If you want inheritance computations to be done again (for example,
321
because a newly loaded package has a more direct method than one
322
that has already been used in this session), call
323
\code{\link{resetGeneric}}.  Because classes and methods involving
324
them tend to come from the same package, the current implementation
325
does not reset all generics every time a new package is loaded.
16559 jmc 326
 
39016 jmc 327
Besides being initiated through calls to the generic function, method
45824 jmc 328
selection can be done explicitly by calling the function
329
\code{\link{selectMethod}}.
16559 jmc 330
 
45824 jmc 331
Once a method has been selected, the evaluator creates a new context
332
in which a call to the method is evaluated.
333
The context is initialized with the arguments from the call to the
334
generic function.
335
These arguments are not rematched.  All the arguments in the signature
336
of the generic will have been evaluated (including any that are
337
currently inactive); arguments that are not in the signature will obey
338
the usual lazy evaluation rules of the language.
339
If an argument was missing in the call, its default expression if any
340
will \emph{not} have been evaluated, since method dispatch always uses
341
class \code{missing} for such arguments.
342
 
343
A call to a generic function therefore has two contexts:  one for the
344
function and a second for the method.
345
The argument objects will be copied to the second context, but not any
346
local objects created in a nonstandard generic function.
61433 ripley 347
The other important distinction is that the parent
45824 jmc 348
(\dQuote{enclosing}) environment of the second context is the environment
349
of the method as a function, so that all \R programming techniques
350
using such environments apply to method definitions as ordinary functions.
351
 
352
 
353
For further discussion of method selection and dispatch,  see the
354
first reference.
355
 
39016 jmc 356
}
16559 jmc 357
 
45824 jmc 358
\section{Generic Functions}{
359
In principle, a generic function could be any function that evaluates
360
a call to \code{standardGeneric()}, the internal function that selects
361
a method and evaluates a call to  the selected method.  In practice,
362
generic functions are special objects that in addition to being from a
363
subclass of class \code{"function"} also extend the class
364
\code{\linkS4class{genericFunction}}.  Such objects have slots to define
365
information needed to deal with their methods.  They also have
366
specialized environments, containing the tables used in method
367
selection.
368
 
369
The slots \code{"generic"} and  \code{"package"} in the object are the
370
character string names of the generic function itself and of the
371
package from which the  function is defined.
372
As with classes, generic functions are uniquely defined in \R by the
373
combination of the two names.
374
There can be generic functions of the same name associated with
375
different packages (although inevitably keeping such functions cleanly
376
distinguished is not always easy).
377
On the other hand, \R will enforce that only one definition of a
378
generic function can be associated with a particular combination of
379
function and package name, in the current session or other active
380
version of \R.
381
 
382
Tables of methods for a particular generic function, in this sense,
383
will often be spread over several other packages.
384
The total set of methods for a given generic function may change
385
during a session, as additional packages are loaded.
386
Each table must be consistent in the signature assumed for the generic
387
function.
388
 
389
\R distinguishes \emph{standard} and \emph{nonstandard} generic
390
functions, with the former having a function body that does nothing
391
but dispatch a method.
392
For the most part, the distinction is just one of simplicity:  knowing
393
that a generic function only dispatches a method call allows some
394
efficiencies and also removes some uncertainties.
395
 
396
In most cases, the generic function is the visible function
397
corresponding to that name, in the corresponding package.
398
There are two exceptions, \emph{implicit} generic
399
functions and the special computations required to deal with \R's
400
\emph{primitive} functions.
401
Packages can contain a table of implicit generic versions of functions
402
in the package, if the package wishes to leave a function non-generic
403
but to constrain what the function would be like if it were generic.
404
Such implicit generic functions are created during the installation of
405
the package, essentially by defining the generic function and
406
possibly methods for it, and then reverting the function to its
407
non-generic form. (See \link{implicitGeneric} for how this is done.)
408
The mechanism is mainly used for functions in the older packages in
409
\R, which may prefer to ignore S4 methods.
410
Even in this case, the actual mechanism is only needed if something
411
special has to be specified.
412
All functions have a corresponding implicit generic version defined
413
automatically (an implicit, implicit generic function one might say).
414
This function is a standard generic with the same arguments as the
415
non-generic function, with the non-generic version as the default (and only)
416
method, and with the generic signature being all the formal arguments
417
except \dots.
418
 
419
The implicit generic mechanism is needed only to override some aspect
420
of the default definition.
421
One reason to do so would be to remove some arguments from the
422
signature.
423
Arguments that may need to be interpreted literally, or for which the
424
lazy evaluation mechanism of the language is needed, must \emph{not}
425
be included in the signature of the generic function, since all
426
arguments in the signature will be evaluated in order to select a
427
method.
428
For example, the argument \code{expr} to the function
429
\code{\link{with}} is treated literally and must therefore be excluded
430
from the signature.
431
 
432
One would also need to define an implicit generic if the existing
433
non-generic function were not suitable as the default method.
434
Perhaps the function only applies to some classes of objects, and the
435
package designer prefers to have no general default method.
436
In the other direction, the package designer might have some ideas
437
about suitable methods for some classes, if the function were generic.
438
With reasonably modern packages, the simple approach in all these
439
cases is just to define the function as a generic.
440
The implicit generic mechanism is mainly attractive for older packages
441
that do not want to require the methods package to be available.
442
 
443
Generic functions will also be defined but not obviously visible for
444
functions implemented as \emph{primitive} functions in the base
445
package.
446
Primitive functions look like ordinary functions when printed but are
447
in fact not function objects but objects of two types interpreted by
448
the \R evaluator to call underlying C code directly.
449
Since their entire justification is efficiency, \R refuses to hide
450
primitives behind a generic function object.
451
Methods may be defined for most primitives, and corresponding metadata
452
objects will be created to store them.
453
Calls to the primitive still go directly to the C code, which will
454
sometimes check for applicable methods.
455
The definition of \dQuote{sometimes} is that methods must have been
456
detected for the function in some package loaded in the session and
457
\code{isS4(x)} is \code{TRUE} for  the first argument (or for the
458
second argument, in the case of binary operators).
459
You can test whether methods have been detected by calling
460
\code{\link{isGeneric}} for the relevant function and you can examine
461
the generic function by calling \code{\link{getGeneric}}, whether or
462
not methods have been detected.
463
For more on generic functions, see the first reference and also section 2 of \emph{R Internals}.
464
 
465
}
466
 
467
\section{Method Definitions}{
468
All method definitions are stored as objects from the
469
\code{\linkS4class{MethodDefinition}} class.
470
Like the class of generic functions, this class extends ordinary \R
471
functions with some additional slots: \code{"generic"}, containing the
472
name and package of the generic function, and two signature slots,
473
\code{"defined"} and \code{"target"}, the first being the signature supplied when
474
the method was defined by a call to \code{\link{setMethod}}.
475
The  \code{"target"} slot starts off equal to the \code{"defined"}
476
  slot.  When an inherited method is cached after being selected, as
477
  described above, a copy is made with the  appropriate \code{"target"}  signature.
478
  Output from \code{\link{showMethods}}, for example, includes both
479
  signatures.
480
 
481
  Method definitions are required to have the same formal arguments as
482
  the generic function, since the method dispatch mechanism does not
483
  rematch arguments, for reasons of both efficiency and consistency.
484
}
485
 
48117 jmc 486
\examples{
48409 jmc 487
## A class that extends a registered S3 class inherits that class' S3
52266 jmc 488
## methods.
48409 jmc 489
 
490
setClass("myFrame", contains = "data.frame",
52266 jmc 491
    representation(timestamps = "POSIXt"))
48409 jmc 492
 
493
df1 <- data.frame(x = 1:10, y = rnorm(10), z = sample(letters,10))
494
 
52266 jmc 495
mydf1 <- new("myFrame", df1, timestamps = Sys.time())
48409 jmc 496
 
497
## "myFrame" objects inherit "data.frame" S3 methods; e.g., for `[`
498
 
52266 jmc 499
mydf1[1:2, ] # a data frame object (with extra attributes)
48409 jmc 500
 
52266 jmc 501
## a method explicitly for "myFrame" class
48409 jmc 502
 
503
 
52266 jmc 504
setMethod("[",
505
    signature(x = "myFrame"),
61433 ripley 506
    function (x, i, j, ..., drop = TRUE)
52266 jmc 507
    {
508
        S3Part(x) <- callNextMethod()
509
        x@timestamps <- c(Sys.time(), as.POSIXct(x@timestamps))
510
        x
511
    }
512
)
513
 
53170 ripley 514
\donttest{mydf1[1:2, ]}
52266 jmc 515
 
516
 
48409 jmc 517
setClass("myDateTime", contains = "POSIXt")
518
 
51712 ripley 519
now <- Sys.time() # class(now) is c("POSIXct", "POSIXt")
520
nowLt <- as.POSIXlt(now)# class(nowLt) is c("POSIXlt", "POSIXt")
48409 jmc 521
 
522
mCt <- new("myDateTime", now)
523
mLt <- new("myDateTime", nowLt)
524
 
52266 jmc 525
## S3 methods for an S4 object will be selected using S4 inheritance
526
## Objects mCt and mLt have different S3Class() values, but this is
527
## not used.
528
f3 <- function(x)UseMethod("f3") # an S3 generic to illustrate inheritance
48409 jmc 529
 
530
f3.POSIXct <- function(x) "The POSIXct result"
531
f3.POSIXlt <- function(x) "The POSIXlt result"
52266 jmc 532
f3.POSIXt <- function(x) "The POSIXt result"
48409 jmc 533
 
52266 jmc 534
stopifnot(identical(f3(mCt), f3.POSIXt(mCt)))
535
stopifnot(identical(f3(mLt), f3.POSIXt(mLt)))
48409 jmc 536
 
537
 
538
 
52266 jmc 539
## An S4 object selects S3 methods according to its S4 "inheritance"
48409 jmc 540
 
52266 jmc 541
 
48724 jmc 542
setClass("classA", contains = "numeric",
52266 jmc 543
   representation(realData = "numeric"))
45824 jmc 544
 
48724 jmc 545
Math.classA <- function(x) {(getFunction(.Generic))(x@realData)}
52266 jmc 546
setMethod("Math", "classA", Math.classA)
48117 jmc 547
 
52266 jmc 548
 
48117 jmc 549
x <- new("classA", log(1:10), realData = 1:10)
550
 
48724 jmc 551
stopifnot(identical(abs(x), 1:10))
48117 jmc 552
 
553
setClass("classB", contains = "classA")
554
 
555
y <- new("classB", x)
556
 
48724 jmc 557
stopifnot(identical(abs(y), 1:10)) # (version 2.9.0 or earlier fails here)
48117 jmc 558
 
52266 jmc 559
## an S3 generic: just for demonstration purposes
560
f3 <- function(x, ...) UseMethod("f3")
48409 jmc 561
 
52266 jmc 562
f3.default <- function(x, ...) "Default f3"
48409 jmc 563
 
52266 jmc 564
## S3 method (only) for classA
565
f3.classA <- function(x, ...) "Class classA for f3"
48409 jmc 566
 
52266 jmc 567
## S3 and S4 method for numeric
568
f3.numeric <- function(x, ...) "Class numeric for f3"
569
setMethod("f3", "numeric", f3.numeric)
48409 jmc 570
 
52266 jmc 571
## The S3 method for classA and the closest inherited S3 method for classB
572
## are not found.
48409 jmc 573
 
52266 jmc 574
f3(x); f3(y) # both choose "numeric" method
48409 jmc 575
 
52266 jmc 576
## to obtain the natural inheritance, set identical S3 and S4 methods
577
setMethod("f3", "classA", f3.classA)
48409 jmc 578
 
52266 jmc 579
f3(x); f3(y) # now both choose "classA" method
580
 
581
## Need to define an S3 as well as S4 method to use on an S3 object
582
## or if called from a package without the S4 generic
583
 
584
MathFun <- function(x) { # a smarter "data.frame" method for Math group
585
  for (i in seq(length = ncol(x))[sapply(x, is.numeric)])
586
    x[, i] <- (getFunction(.Generic))(x[, i])
587
  x
588
}
589
setMethod("Math", "data.frame", MathFun)
590
 
591
## S4 method works for an S4 class containing data.frame,
592
## but not for data.frame objects (not S4 objects)
593
 
594
try(logIris <- log(iris)) #gets an error from the old method
595
 
596
## Define an S3 method with the same computation
597
 
598
Math.data.frame <- MathFun
599
 
600
logIris <- log(iris)
601
 
602
 
603
 
604
 
48117 jmc 605
\dontshow{
606
removeClass("classA"); removeClass("classB"); rm(x,y)
52266 jmc 607
removeGeneric("f3")
48409 jmc 608
removeClass("myDateTime")
52266 jmc 609
removeMethod("Math", "data.frame"); rm(Math.data.frame, MathFun, logIris)
48117 jmc 610
}
611
 
612
}
613
 
614
 
15357 jmc 615
\references{
45824 jmc 616
 Chambers, John M. (2008)
617
 \emph{Software for Data Analysis: Programming with R}
618
  Springer.  (For the R version: see section 10.6 for method
46316 jmc 619
  selection and section 10.5 for generic functions).
15357 jmc 620
 
47803 jmc 621
 Chambers, John M.(2009)
48409 jmc 622
 \emph{Developments in Class Inheritance and Method Selection}
623
 \url{http://stat.stanford.edu/~jmc4/classInheritance.pdf}.
47803 jmc 624
 
45824 jmc 625
 Chambers, John M. (1998)
626
 \emph{Programming with Data}
627
 Springer (For the original S4 version.)
39303 hornik 628
}
19029 hornik 629
\seealso{
46314 jmc 630
For more specific information, see
45824 jmc 631
  \code{\link{setGeneric}}, \code{\link{setMethod}}, and
632
  \code{\link{setClass}}.
46314 jmc 633
 
634
For the use of \dots in methods, see  \link{dotsMethods}.
19029 hornik 635
}
15357 jmc 636
\keyword{programming}
637
\keyword{classes}
638
\keyword{methods}