Formal Methods and Classes

Formal Methods and Classes [R logo]

Help pages for package `methods' version 2.4.1

A B C D E F G H I L M N O P R S T V W misc

-- --

methods-package Formal Methods and Classes

-- --

(-class | Classes to Represent Unevaluated Language Objects
.BasicFunsList | List of Builtin and Special Functions
.doTracePrint | Classes Used Internally to Control Tracing
.InitTraceFunctions | Classes Used Internally to Control Tracing
.makeTracedFunction | Classes Used Internally to Control Tracing
.OldClassesList | Specify Names for Old-Style Classes
.setOldIs | Specify Names for Old-Style Classes
.slotNames | The Slots in an Object from a Formal Class
.untracedFunction | Classes Used Internally to Control Tracing
<--class | Classes to Represent Unevaluated Language Objects

-- A --

allGenerics | Tools for Managing Generic Functions
anova-class | Specify Names for Old-Style Classes
anova.glm-class | Specify Names for Old-Style Classes
anova.glm.null-class | Specify Names for Old-Style Classes
ANY-class | Classes Corresponding to Basic Data Types
aov-class | Specify Names for Old-Style Classes
Arith | S4 Group Generic Functions
array-class | Classes Corresponding to Basic Structures
as | Force an Object to Belong to a Class

-- B --

body<-,MethodDefinition-method Class MethodsList, Representation of Methods for a Generic Function

-- C --

call-class | Classes to Represent Unevaluated Language Objects
callGeneric | Tools for Managing Generic Functions
callNextMethod | Call an Inherited Method
canCoerce | Can an Object be Coerced to a Certain S4 Class?
cbind2 | Combine two Objects by Columns or Rows
cbind2,ANY,ANY-method | Combine two Objects by Columns or Rows
cbind2,ANY,missing-method | Combine two Objects by Columns or Rows
cbind2-methods | Combine two Objects by Columns or Rows
character-class | Classes Corresponding to Basic Data Types
Classes | Class Definitions
classRepresentation-class | Class Objects
ClassUnionRepresentation-class | Classes Defined as the Union of Other Classes
coerce | Force an Object to Belong to a Class
coerce,ANY,array-method | Force an Object to Belong to a Class
coerce,ANY,call-method | Force an Object to Belong to a Class
coerce,ANY,character-method | Force an Object to Belong to a Class
coerce,ANY,complex-method | Force an Object to Belong to a Class
coerce,ANY,environment-method | Force an Object to Belong to a Class
coerce,ANY,expression-method | Force an Object to Belong to a Class
coerce,ANY,function-method | Force an Object to Belong to a Class
coerce,ANY,integer-method | Force an Object to Belong to a Class
coerce,ANY,list-method | Force an Object to Belong to a Class
coerce,ANY,logical-method | Force an Object to Belong to a Class
coerce,ANY,matrix-method | Force an Object to Belong to a Class
coerce,ANY,name-method | Force an Object to Belong to a Class
coerce,ANY,NULL-method | Force an Object to Belong to a Class
coerce,ANY,numeric-method | Force an Object to Belong to a Class
coerce,ANY,single-method | Force an Object to Belong to a Class
coerce,ANY,ts-method | Force an Object to Belong to a Class
coerce,ANY,vector-method | Force an Object to Belong to a Class
coerce-methods | Force an Object to Belong to a Class
Compare | S4 Group Generic Functions
Complex | S4 Group Generic Functions
complex-class | Classes Corresponding to Basic Data Types

-- D --

data.frame-class | Specify Names for Old-Style Classes
density-class | Specify Names for Old-Style Classes
Documentation | Using and Creating On-line Documentation for Classes and Methods
Documentation-class | Using and Creating On-line Documentation for Classes and Methods
Documentation-methods | Using and Creating On-line Documentation for Classes and Methods
double-class | Classes Corresponding to Basic Data Types
dump.frames-class | Specify Names for Old-Style Classes
dumpMethod | Tools for Managing Generic Functions
dumpMethods | Tools for Managing Generic Functions

-- E --

environment-class | Class "environment"
existsMethod | Get or Test for the Definition of a Method
expression-class | Classes Corresponding to Basic Data Types
extends | Is an Object from a Class
externalptr-class | Classes Corresponding to Basic Data Types

-- F --

factor-class | Specify Names for Old-Style Classes
findClass | Create a Class Definition
findFunction | Tools for Managing Generic Functions
findMethod | Get or Test for the Definition of a Method
fixPre1.8 | Fix Objects Saved from R Versions Previous to 1.8
for-class | Classes to Represent Unevaluated Language Objects
formula-class | Specify Names for Old-Style Classes
function-class | Classes Corresponding to Basic Data Types
functionWithTrace-class | Classes Used Internally to Control Tracing

-- G --

genericFunction-class | Generic Function Objects
GenericFunctions | Tools for Managing Generic Functions
genericFunctionWithTrace-class | Classes Used Internally to Control Tracing
getClass | Get Class Definition
getClassDef | Get Class Definition
getClasses | Create a Class Definition
getGenerics | Tools for Managing Generic Functions
getMethod | Get or Test for the Definition of a Method
getMethods | Get or Test for the Definition of a Method
getPackageName | The Name associated with a Given Package
glm-class | Specify Names for Old-Style Classes
glm.null-class | Specify Names for Old-Style Classes
groupGenericFunction-class | Generic Function Objects
groupGenericFunctionWithTrace-class | Classes Used Internally to Control Tracing

-- H --

hasArg | Look for an Argument in the Call
hasMethod | Get or Test for the Definition of a Method
hsearch-class | Specify Names for Old-Style Classes

-- I --

if-class | Classes to Represent Unevaluated Language Objects
initialize | Generate an Object from a Class
initialize,ANY-method | Methods to Initialize New Objects from a Class
initialize,data.frame-method | Specify Names for Old-Style Classes
initialize,environment-method | Methods to Initialize New Objects from a Class
initialize,factor-method | Specify Names for Old-Style Classes
initialize,ordered-method | Specify Names for Old-Style Classes
initialize,signature-method | Methods to Initialize New Objects from a Class
initialize,summary.table-method | Specify Names for Old-Style Classes
initialize,table-method | Specify Names for Old-Style Classes
initialize,traceable-method | Methods to Initialize New Objects from a Class
initialize-methods | Methods to Initialize New Objects from a Class
integer-class | Classes Corresponding to Basic Data Types
integrate-class | Specify Names for Old-Style Classes
is | Is an Object from a Class
isClass | Create a Class Definition
isClassUnion | Classes Defined as the Union of Other Classes
isGeneric | Tools for Managing Generic Functions
isGroup | Tools for Managing Generic Functions
isSealedClass | Check for a Sealed Method or Class
isSealedMethod | Check for a Sealed Method or Class

-- L --

language-class | Classes to Represent Unevaluated Language Objects
libraryIQR-class | Specify Names for Old-Style Classes
LinearMethodsList-class | Class "LinearMethodsList"
list-class | Classes Corresponding to Basic Data Types
lm-class | Specify Names for Old-Style Classes
Logic | S4 Group Generic Functions
logical-class | Classes Corresponding to Basic Data Types
logLik-class | Specify Names for Old-Style Classes

-- M --

makeClassRepresentation | Create a Class Definition
maov-class | Specify Names for Old-Style Classes
Math | S4 Group Generic Functions
Math2 | S4 Group Generic Functions
matrix-class | Classes Corresponding to Basic Structures
MethodDefinition-class | Classes to Represent Method Definitions
MethodDefinitionWithTrace-class | Classes Used Internally to Control Tracing
Methods | General Information on Methods
MethodsList-class | Class MethodsList, Representation of Methods for a Generic Function
MethodsListSelect | Get or Test for the Definition of a Method
MethodWithNext-class | Class MethodWithNext
MethodWithNextWithTrace-class | Classes Used Internally to Control Tracing
missing-class | Classes Corresponding to Basic Data Types
mlm-class | Specify Names for Old-Style Classes
mtable-class | Specify Names for Old-Style Classes
mts-class | Specify Names for Old-Style Classes

-- N --

name-class | Classes to Represent Unevaluated Language Objects
new | Generate an Object from a Class
NULL-class | Classes Corresponding to Basic Data Types
numeric-class | Classes Corresponding to Basic Data Types

-- O --

ObjectsWithPackage-class | A Vector of Object Names, with associated Package Names
oldClass-class | Specify Names for Old-Style Classes
Ops | S4 Group Generic Functions
ordered-class | Specify Names for Old-Style Classes

-- P --

packageInfo-class | Specify Names for Old-Style Classes
packageIQR-class | Specify Names for Old-Style Classes
packageSlot | The Name associated with a Given Package
POSIXct-class | Specify Names for Old-Style Classes
POSIXlt-class | Specify Names for Old-Style Classes
POSIXt-class | Specify Names for Old-Style Classes
promptClass | Generate a Shell for Documentation of a Formal Class
promptMethods | Generate a Shell for Documentation of Formal Methods
prototype | Construct a Representation or a Prototype for a Class Definition

-- R --

raw-class | Classes Corresponding to Basic Data Types
rbind2 | Combine two Objects by Columns or Rows
rbind2,ANY,ANY-method | Combine two Objects by Columns or Rows
rbind2,ANY,missing-method | Combine two Objects by Columns or Rows
rbind2-methods | Combine two Objects by Columns or Rows
recordedplot-class | Specify Names for Old-Style Classes
removeClass | Create a Class Definition
removeGeneric | Tools for Managing Generic Functions
removeMethod | Create and Save a Method
removeMethods | Tools for Managing Generic Functions
repeat-class | Classes to Represent Unevaluated Language Objects
representation | Construct a Representation or a Prototype for a Class Definition
resetClass | Create a Class Definition
rle-class | Specify Names for Old-Style Classes

-- S --

S4groupGeneric | S4 Group Generic Functions
SClassExtension-class | Class to Represent Inheritance (Extension) Relations
sealClass | Create a Class Definition
SealedMethodDefinition-class | Classes to Represent Method Definitions
seemsS4Object | Heuristic test for an object from an S4 class
selectMethod | Get or Test for the Definition of a Method
setAs | Force an Object to Belong to a Class
setClass | Create a Class Definition
setClassUnion | Classes Defined as the Union of Other Classes
setGeneric | Define a New Generic Function
setGroupGeneric | Define a New Generic Function
setIs | Is an Object from a Class
setMethod | Create and Save a Method
setOldClass | Specify Names for Old-Style Classes
setPackageName | The Name associated with a Given Package
setReplaceMethod | Tools for Managing Generic Functions
setValidity | Test the Validity of an Object
show | Show an Object
show,ANY-method | Show an Object
show,classRepresentation-method | Show an Object
show,genericFunction-method | Show an Object
show,MethodDefinition-method | Show an Object
show,MethodWithNext-method | Show an Object
show,ObjectsWithPackage-method | Show an Object
show,signature-method | Class "signature" For Method Definitions
show,traceable-method | Show an Object
show-methods | Show an Object
showMethods | Show all the methods for the specified function(s)
signature | Tools for Managing Generic Functions
signature-class | Class "signature" For Method Definitions
single-class | Classes Corresponding to Basic Data Types
slot | The Slots in an Object from a Formal Class
slotNames | The Slots in an Object from a Formal Class
socket-class | Specify Names for Old-Style Classes
structure-class | Classes Corresponding to Basic Structures
Summary | S4 Group Generic Functions
summary.table-class | Specify Names for Old-Style Classes

-- T --

table-class | Specify Names for Old-Style Classes
traceable-class | Classes Used Internally to Control Tracing
ts-class | Classes Corresponding to Basic Structures

-- V --

validObject | Test the Validity of an Object
vector-class | Classes Corresponding to Basic Data Types
VIRTUAL-class | Classes Corresponding to Basic Data Types

-- W --

while-class Classes to Represent Unevaluated Language Objects

-- misc --

__ClassMetaData | Class Definitions
{-class | Classes to Represent Unevaluated Language Objects


Force an Object to Belong to a Class

Description

These functions manage the relations that allow coercing an object to a given class.

Usage

as(object, Class, strict=TRUE, ext)

as(object, Class) <- value

setAs(from, to, def, replace, where = topenv(parent.frame()))

Arguments

object | any R object.
Class | the name of the class to which object should be coerced.
strict | logical flag. If TRUE, the returned object must be strictly from the target class (unless that class is a virtual class, in which case the object will be from the closest actual class (often the original object, if that class extends the virtual class directly). If strict = FALSE, any simple extension of the target class will be returned, without further change. A simple extension is, roughly, one that just adds slots to an existing class.
value | The value to use to modify object (see the discussion below). You should supply an object with class Class; some coercion is done, but you're unwise to rely on it.
from, to | The classes between which def performs coercion. (In the case of the coerce function these are objects from the classes, not the names of the classes, but you're not expected to call coerce directly.)
def | function of one argument. It will get an object from class from and had better return an object of class to. (If you want to save setAs a little work, make the name of the argument from, but don't worry about it, setAs will do the conversion.)
replace | if supplied, the function to use as a replacement method.
where | the position or environment in which to store the resulting method for coerce.
ext | the optional object defining how Class is extended by the class of the object (as returned by possibleExtends). This argument is used internally (to provide essential information for non-public classes), but you are unlikely to want to use it directly.

Summary of Functions

as:
Returns the version of this object coerced to be the given Class.

If the corresponding is(object, Class) relation is true, it will be used. In particular, if the relation has a coerce method, the method will be invoked on object. However, if the object's class extends Class in a simple way (e.g, by including the superclass in the definition, then the actual coercion will be done only if strict is TRUE (non-strict coercion, is used in passing objects to methods).

Coerce methods are pre-defined for basic classes (including all the types of vectors, functions and a few others). See showMethods(coerce) for a list of these.

Beyond these two sources of methods, further methods are defined by calls to the setAs function.

coerce:
Coerce from to be of the same class as to.

Not a function you should usually call explicitly. The function setAs creates methods for coerce for the as function to use.

setAs:
The function supplied as the third argument is to be called to implement as(x, to) when x has class from. Need we add that the function should return a suitable object with class to.

How Functions 'as' and 'setAs' Work

The function as contrives to turn object into an object with class Class. In doing so, it uses information about classes and methods, but in a somewhat special way. Keep in mind that objects from one class can turn into objects from another class either automatically or by an explicit call to the as function. Automatic conversion is special, and comes from the designer of one class of objects asserting that this class extends another class (see setClass and setIs).

Because inheritance is a powerful assertion, it should be used sparingly (otherwise your computations may produce unexpected, and perhaps incorrect, results). But objects can also be converted explicitly, by calling as, and that conversion is designed to use any inheritance information, as well as explicit methods.

As a first step in conversion, the as function determines whether is(object, Class) is TRUE. This can be the case either because the class definition of object includes Class as a “super class” (directly or indirectly), or because a call to setIs established the relationship.

Either way, the inheritance relation defines a method to coerce object to Class. In the most common case, the method is just to extract from object the slots needed for Class, but it's also possible to specify a method explicitly in a setIs call.

So, if inheritance applies, the as function calls the appropriate method. If inheritance does not apply, and coerceFlag is FALSE, NULL is returned.

By default, coerceFlag is TRUE. In this case the as function goes on to look for a method for the function coerce for the signature c(from = class(object), to = Class).

Method selection is used in the as function in two special ways. First, inheritance is applied for the argument from but not for the argument to (if you think about it, you'll probably agree that you wouldn't want the result to be from some class other than the Class specified). Second, the function tries to use inheritance information to convert the object indirectly, by first converting it to an inherited class. It does this by examining the classes that the from class extends, to see if any of them has an explicit conversion method. Suppose class "by" does: Then the as function implicitly computes as(as(object, "by"), Class).

With this explanation as background, the function setAs does a fairly obvious computation: It constructs and sets a method for the function coerce with signature c(from, to), using the def argument to define the body of the method. The function supplied as def can have one argument (interpreted as an object to be coerced) or two arguments (the from object and the to class). Either way, setAs constructs a function of two arguments, with the second defaulting to the name of the to class. The method will be called from as with the object as the only argument: The default for the second argument is provided so the method can know the intended to class.

The function coerce exists almost entirely as a repository for such methods, to be selected as described above by the as function. In fact, it would usually be a bad idea to call coerce directly, since then you would get inheritance on the to argument; as mentioned, this is not likely to be what you want.

The Function 'as' Used in Replacements

When as appears on the left of an assignment, the intuitive meaning is “Replace the part of object that was inherited from Class by the value on the right of the assignment.”

This usually has a straightforward interpretation, but you can control explicitly what happens, and sometimes you should to avoid possible corruption of objects.

When object inherits from Class in the usual way, by including the slots of Class, the default as method is to set the corresponding slots in object to those in value.

The default computation may be reasonable, but usually only if all other slots in object are unrelated to the slots being changed. Often, however, this is not the case. The class of object may have extended Class with a new slot whose value depends on the inherited slots. In this case, you may want to define a method for replacing the inherited information that recomputes all the dependent information. Or, you may just want to prohibit replacing the inherited information directly .

The way to control such replacements is through the replace argument to function setIs. This argument is a method that function as calls when used for replacement. It can do whatever you like, including calling stop if you want to prohibit replacements. It should return a modified object with the same class as the object argument to as.

In R, you can also explicitly supply a replacement method, even in the case that inheritance does not apply, through the replace argument to setAs. It works essentially the same way, but in this case by constructing a method for "coerce<-". (Replace methods for coercion without inheritance are not in the original description and so may not be compatible with S-Plus, at least not yet.)

When inheritance does apply, coerce and replace methods can be specified through either setIs or setAs; the effect is essentially the same.

Basic Coercion Methods

Methods are pre-defined for coercing any object to one of the basic datatypes. For example, as(x, "numeric") uses the existing as.numeric function. These built-in methods can be listed by showMethods("coerce").

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

If you think of using try(as(x, cl)), consider canCoerce(x, cl) instead.

Examples

## using the definition of class "track" from Classes

setAs("track", "numeric", function(from) from@y)

t1 <- new("track", x=1:20, y=(1:20)^2)

as(t1, "numeric")

## The next example shows:
##  1. A virtual class to define setAs for several classes at once.
##  2. as() using inherited information

setClass("ca", representation(a = "character", id = "numeric"))

setClass("cb", representation(b = "character", id = "numeric"))

setClass("id")
setIs("ca", "id")
setIs("cb", "id")

setAs("id", "numeric", function(from) from@id)

CA <- new("ca", a = "A", id = 1)
CB <- new("cb", b = "B", id = 2)

setAs("cb", "ca", function(from, to )new(to, a=from@b, id = from@id))

as(CB, "numeric")
[Package methods version 2.4.1 Index]


Classes Corresponding to Basic Data Types

Description

Formal classes exist corresponding to the basic R data types, allowing these types to be used in method signatures, as slots in class definitions, and to be extended by new classes.

Usage

### The following are all basic vector classes.
### They can appear as class names in method signatures,
### in calls to as(), is(), and new().
"character"
"complex"
"double"
"expression"
"integer"
"list"
"logical"
"numeric"
"single"
"raw"

### the class
"vector"
### is a virtual class, extended by all the above

### The following are additional basic classes
"NULL"     #  NULL objects
"function" #  function objects, including primitives
"externalptr" # raw external pointers for use in C code

"ANY"  # virtual classes used by the methods package itself
"VIRTUAL"
"missing"

Objects from the Classes

Objects can be created by calls of the form new(Class, ...), where Class is the quoted class name, and the remaining arguments if any are objects to be interpreted as vectors of this class. Multiple arguments will be concatenated.

The class "expression" is slightly odd, in that the ... arguments will not be evaluated; therefore, don't enclose them in a call to quote().

Extends

Class "vector", directly.

Methods

coerce
Methods are defined to coerce arbitrary objects to these classes, by calling the corresponding basic function, for example, as(x, "numeric") calls as.numeric(x).


Can an Object be Coerced to a Certain S4 Class?

Description

Test if an object can be coerced to a given S4 class. Maybe useful inside if() to ensure that calling as(object, Class) will find a method.

Usage

canCoerce(object, Class)

Arguments

object | any R object, typically of a formal S4 class.
Class | an S4 class (see isClass

.

Value

a scalar logical, TRUE if there is a coerce method (as defined by setAs, e.g.) for the signature (from = class(object), to = Class).

See Also

as, setAs, selectMethod, setClass,

Examples

m <- matrix(pi, 2,3)
canCoerce(m, "numeric") # TRUE
canCoerce(m, "array")   # TRUE


Combine two Objects by Columns or Rows

Description

Combine two “matrix-like” R objects by columns (cbind2) or rows (rbind2). These are (S4) generic functions with default methods.

Usage

cbind2(x, y)
rbind2(x, y)

Arguments

x | any R object, typically “matrix-like”.
y | any R object, typically similar to x, or missing completely.

Details

The main use of cbind2 (rbind2) is to be called by cbind() (rbind()) if these are activated. This allows cbind (rbind) to “work” for formally classed (aka ‘S4’) objects by providing S4 methods for these objects. Currently, a call
methods:::bind_activation(TRUE)
is needed to install a “cbind2-calling” version of cbind (into the base namespace) and the same for rbind.
methods:::bind_activation(FALSE) reverts to the previous internal version of cbind which does not build on cbind2, see the examples.

Value

A matrix (or matrix like object) combining the columns (or rows) of x and y.

Methods

x = "ANY", y = "ANY"
the default method using R's internal code.
x = "ANY", y = "missing"
the default method for one argument using R's internal code.

See Also

cbind, rbind.

Examples

cbind2(1:3, 4)
m <- matrix(3:8, 2,3, dimnames=list(c("a","b"), LETTERS[1:3]))
cbind2(1:2, m) # keeps dimnames from m

### Note: Use the following activation if you want cbind() to work
### ----  on S4 objects -- be careful otherwise!

methods:::bind_activation(on = TRUE)
trace("cbind2")
cbind(a=1:3)# no call to cbind2()
cbind(a=1:3, four=4, 7:9)# calling cbind2() twice
untrace("cbind2")

## The following fails currently,
## since cbind() works recursively from the tail:
try( cbind(m, a=1, b=3) )

## turn off the `special cbind()' :
methods:::bind_activation(FALSE)


Class Definitions

Description

Class definitions are objects that contain the formal definition of a class of R objects, usually referred to as an S4 class, to distinguish them from the informal S3 classes. This document gives an overview of S4 classes; for details of the class representation objects themselves, see class?classRepresentation (classRepresentation-class).

Details

When a class is defined, an object is stored that contains the information about that class, including:

Slots:

The data contained in an object from an S4 class is defined by the slots in the class definition.

Each slot in an object is a component of the object; like components (that is, elements) of a list, these may be extracted and set, using the function slot() or more often the operator "@". However, they differ from list components in important ways. First, slots can only be referred to by name, not by position, and there is no partial matching of names as with list elements.

All the objects from a particular class have the same set of slot names; specifically, the slot names that are contained in the class definition. Each slot in each object always has the same class; again, this is defined by the overall class definition. The phrase “has the same class” means that the class of the object in the slot must be the same as the class specified in the definition, or some class that extends the one in the definition.

One class name is special, .Data. This stands for the “data part” of the object. Any class that contains one of the basic data types in R{}, has implicitly a corresponding .Data slot of that type, allowing computations to extract or replace the data part while leaving other slots unchanged. The .Data slot also determines the type of the object; if x has a .Data slot, the type of the slot is the type of the object (that is, the value of typeof(x). Otherwise the type of the object is "S4". Extending a basic type this way allows objects to use old-style code for the corresponding type as well as S4 methods. Any basic type can be used for .Data, with the exception of a few that do not behave like ordinary objects; namely, "NULL", environments, and external pointers.

Classes exist for which there are no actual objects, the virtual classes, in fact a very important programming tool. They are used to group together ordinary classes that want to share some programming behavior, without necessarily restricting how the behavior is implemented. Virtual class definitions may if you want include slots (to provide some common behavior without fully defining the object—see traceable-class for an example).

A simple and useful form of virtual class is the class union, a virtual class that is defined in a call to setClassUnion by listing one or more of subclasses (classes that extend the class union). Class unions can include as subclasses basic data types (whose definition is otherwise sealed).

Superclasses:

The definition of a class includes the superclasses —the classes that this class extends. A class Fancy, say, extends a class Simple if an object from the Fancy class has all the capabilities of the Simple class (and probably some more as well). In particular, and very usefully, any method defined to work for a Simple object can be applied to a Fancy object as well.

This relationship is expressed equivalently by saying that Simple is a superclass of Fancy, or that Fancy is a subclass of Simple.

The direct superclasses of a class are those superclasses explicitly defined. Direct superclasses can be defined in three ways. Most commonly, the superclasses are listed in the contains= argument in the call to setClass that creates the subclass. In this case the subclass will contain all the slots of the superclass, and the relation between the class is called simple, as it in fact is. Superclasses can also be defined explicitly by a call to setIs; in this case, the relation requires methods to be specified to go from subclass to superclass. Thirdly, a class union is a superclass of all the members of the union. In this case too the relation is simple, but notice that the relation is defined when the superclass is created, not when the subclass is created as with the contains= mechanism.

The definition of a superclass will also potentially contain its own direct superclasses. These are considered (and shown) as superclasses at distance 2 from the original class; their direct superclasses are at distance 3, and so on. All these are legitimate superclasses for purposes such as method selection.

When superclasses are defined by including the names of superclasses in the contains= argument to setClass, an object from the class will have all the slots defined for its own class and all the slots defined for all its superclasses as well.

The information about the relation between a class and a particular superclass is encoded as an object of class "SClassExtension" (see SClassExtension-class). A list of such objects for the superclasses (and sometimes for the subclasses) is included in the metadata object defining the class. If you need to compute with these objects (for example, to compare the distances), call the function extends with argument fullInfo=TRUE.

Objects:

The objects from a class, typically created by a call to new or by assigning another object from the class, are defined by the prototype object for the class and by additional arguments in the call to new, which are passed to a method for that class for the function initialize.

Each class definition contains a prototype object for the class. This must have values for all the slots defined by the class definition. By default, these are the prototypes of all the slot classes, if those are not virtual classes. However, the definition of the class can specify any valid object for any of the slots.

There are a number of “basic” classes, corresponding to the ordinary kinds of data occurring in R. For example, "numeric" is a class corresponding to numeric vectors. There are also basic classes corresponding to objects in the language, such as "function" and "call", and for specialized objects, such as "environment" These classes are predefined and can then be used as slots or as superclasses for any other class definitions. The prototypes for the vector classes are vectors of length 0 of the corresponding type. Notice that basic classes are unusual in that the prototype object is from the class itself.

There are also a few basic virtual classes, the most important being "vector", grouping together all the vector classes; and "language", grouping together all the types of objects making up the R language.

References

The functions in this package emulate the facility for classes and methods described in Programming with Data (John M. Chambers, Springer, 1998). See this book for further details and examples.

See Also

Methods, setClass, is, as, new, slot


Class Objects

Description

These are the objects that hold the definition of classes of objects. They are constructed and stored as meta-data by calls to the function setClass. Don't manipulate them directly, except perhaps to look at individual slots.

Details

Class definitions are stored as metadata in various packages. Additional metadata supplies information on inheritance (the result of calls to setIs). Inheritance information implied by the class definition itself (because the class contains one or more other classes) is also constructed automatically.

When a class is to be used in an R session, this information is assembled to complete the class definition. The completion is a second object of class "classRepresentation", cached for the session or until something happens to change the information. A call to getClass returns the completed definition of a class; a call to getClassDef returns the stored definition (uncompleted).

In particular, completion fills in the upward- and downward-pointing inheritance information for the class, in slots contains and subclasses respectively. It's in principle important to note that this information can depend on which packages are installed, since these may define additional subclasses or superclasses.

Slots

slots:
A named list of the slots in this class; the elements of the list are the classes to which the slots must belong (or extend), and the names of the list gives the corresponding slot names.
contains:
A named list of the classes this class “contains”; the elements of the list are objects of SClassExtension-class. The list may be only the direct extensions or all the currently known extensions (see the details).
virtual:
Logical flag, set to TRUE if this is a virtual class.
prototype:
The object that represents the standard prototype for this class; i.e., the data and slots returned by a call to new for this class with no special arguments. Don't mess with the prototype object directly.
validity:
Optionally, a function to be used to test the validity of objects from this class. See validObject.
access:
Access control information. Not currently used.
className:
The character string name of the class.
package:
The character string name of the package to which the class belongs. Nearly always the package on which the metadata for the class is stored, but in operations such as constructing inheritance information, the internal package name rules.
subclasses:
A named list of the classes known to extend this class'; the elements of the list are objects of SClassExtension-class. The list is currently only filled in when completing the class definition (see the details).
versionKey:
Object of class "externalptr"; eventually will perhaps hold some versioning information, but not currently used.
sealed:
Object of class "logical"; is this class sealed? If so, no modifications are allowed.

See Also

See function setClass to supply the information in the class definition. See Classes for a more basic discussion of class information.


Using and Creating On-line Documentation for Classes and Methods

Description

Special documentation can be supplied to describe the classes and methods that are created by the software in the methods package. Techniques to access this documentation and to create it in R help files are described here.

Getting documentation on classes and methods

You can ask for on-line help for class definitions, for specific methods for a generic function, and for general discussion of methods for a generic function. These requests use the ? operator (see help for a general description of the operator). Of course, you are at the mercy of the implementer as to whether there is any documentation on the corresponding topics.

Documentation on a class uses the argument class on the left of the ?, and the name of the class on the right; for example,

class ? genericFunction

to ask for documentation on the class "genericFunction".

When you want documentation for the methods defined for a particular function, you can ask either for a general discussion of the methods or for documentation of a particular method (that is, the method that would be selected for a particular set of actual arguments).

Overall methods documentation is requested by calling the ? operator with methods as the left-side argument and the name of the function as the right-side argument. For example,

methods ? initialize

asks for documentation on the methods for the initialize function.

Asking for documentation on a particular method is done by giving a function call expression as the right-hand argument to the "?" operator. There are two forms, depending on whether you prefer to give the class names for the arguments or expressions that you intend to use in the actual call.

If you planned to evaluate a function call, say myFun(x, sqrt(wt)) and wanted to find out something about the method that would be used for this call, put the call on the right of the "?" operator:

?myFun(x, sqrt(wt))

A method will be selected, as it would be for the call itself, and documentation for that method will be requested. If myFun is not a generic function, ordinary documentation for the function will be requested.

If you know the actual classes for which you would like method documentation, you can supply these explicitly in place of the argument expressions. In the example above, if you want method documentation for the first argument having class "maybeNumber" and the second "logical", call the "?" operator, this time with a left-side argument method, and with a function call on the right using the class names as arguments:

method ? myFun("maybeNumber", "logical")

Once again, a method will be selected, this time corresponding to the specified classes, and method documentation will be requested. This version only works with generic functions.

The two forms each have advantages. The version with actual arguments doesn't require you to figure out (or guess at) the classes of the arguments. On the other hand, evaluating the arguments may take some time, depending on the example. The version with class names does require you to pick classes, but it's otherwise unambiguous. It has a subtler advantage, in that the classes supplied may be virtual classes, in which case no actual argument will have specifically this class. The class "maybeNumber", for example, might be a class union (see the example for setClassUnion).

In either form, methods will be selected as they would be in actual computation, including use of inheritance and group generic functions. See selectMethod for the details, since it is the function used to find the appropriate method.

Writing Documentation for Methods

The on-line documentation for methods and classes uses some extensions to the R documentation format to implement the requests for class and method documentation described above. See the document Writing R Extensions for the available markup commands (you should have consulted this document already if you are at the stage of documenting your software).

In addition to the specific markup commands to be described, you can create an initial, overall file with a skeleton of documentation for the methods defined for a particular generic function:

promptMethods("myFun")

will create a file, ‘myFun-methods.Rd’ with a skeleton of documentation for the methods defined for function myFun. The output from promptMethods is suitable if you want to describe all or most of the methods for the function in one file, separate from the documentation of the generic function itself. Once the file has been filled in and moved to the ‘man’ subdirectory of your source package, requests for methods documentation will use that file, both for specific methods documentation as described above, and for overall documentation requested by

methods ? myFun

You are not required to use promptMethods, and if you do, you may not want to use the entire file created:

  • If you want to document the methods in the file containing the documentation for the generic function itself, you can cut-and-paste to move the \alias lines and the Methods section from the file created by promptMethods to the existing file.
  • On the other hand, if these are auxiliary methods, and you only want to document the added or modified software, you should strip out all but the relevant \alias lines for the methods of interest, and remove all but the corresponding \item entries in the Methods section. Note that in this case you will usually remove the first \alias line as well, since that is the marker for general methods documentation on this function (in the example, \alias{myfun-methods}).

If you simply want to direct documentation for one or more methods to a particular R documentation file, insert the appropriate alias.


Internal Class representing Empty Methods List

Description

Objects from class "EmptyMethodsList" are generated during method selection to indicate failed search (forcing backtracking). Other classes described here are used internally in method dispatch. All these are for internal use.

Usage

## class described below
"EmptyMethodsList"

### Other, virtual classes used in method dispatch
"OptionalMethods"
"PossibleMethod"

Slots

argument:
Object of class "name" the argument names being selected on.
sublist:
Object of class "list" (unused, and perhaps to be dropped in a later version.)

Methods

No methods defined with class "EmptyMethodsList" in the signature.

See Also

Function MethodsListSelect uses the objects; see MethodsList-class for the non-empty methods list objects.


Class "environment"

environment-class(methods) R Documentation

Class 'environment'

Description

A formal class for R environments.

Objects from the Class

Objects can be created by calls of the form new("environment", ...). The arguments in ..., if any, should be named and will be assigned to the newly created environment.

Methods

coerce
signature(from = "ANY", to = "environment"): calls as.environment.
initialize
signature(object = "environment"): Implements the assignments in the new environment. Note that the object argument is ignored; a new environment is always created, since environments are not protected by copying.

See Also

new.env


Fix Objects Saved from R Versions Previous to 1.8

Description

Beginning with R version 1.8.0, the class of an object contains the identification of the package in which the class is defined. The function fixPre1.8 fixes and re-assigns objects missing that information (typically because they were loaded from a file saved with a previous version of R.)

Usage

fixPre1.8(names, where)

Arguments

names | Character vector of the names of all the objects to be fixed and re-assigned.
where | The environment from which to look for the objects, and for class definitions. Defaults to the top environment of the call to fixPre1.8, the global environment if the function is used interactively.

Details

The named object will be saved where it was found. Its class attribute will be changed to the full form required by R 1.8; otherwise, the contents of the object should be unchanged.

Objects will be fixed and re-assigned only if all the following conditions hold:

  1. The named object exists.
  2. It is from a defined class (not a basic datatype which has no actual class attribute).
  3. The object appears to be from an earlier version of R.
  4. The class is currently defined.
  5. The object is consistent with the current class definition.

If any condition except the second fails, a warning message is generated.

Note that fixPre1.8 currently fixes only the change in class attributes. In particular, it will not fix binary versions of packages installed with earlier versions of R if these use incompatible features. Such packages must be re-installed from source, which is the wise approach always when major version changes occur in R.

Value

The names of all the objects that were in fact re-assigned.


Generic Function Objects

Description

Generic functions (objects from or extending class genericFunction) are extended function objects, containing information used in creating and dispatching methods for this function. They also identify the package associated with the function and its methods.

Objects from the Class

Generic functions are created and assigned by setGeneric or setGroupGeneric and, indirectly, by setMethod.

As you might expect setGeneric and setGroupGeneric create objects of class "genericFunction" and "groupGenericFunction" respectively.

Slots

.Data:
Object of class "function", the function definition of the generic, usually created automatically as a call to standardGeneric.
generic:
Object of class "character", the name of the generic function.
package:
Object of class "character", the name of the package to which the function definition belongs (and not necessarily where the generic function is stored). If the package is not specified explicitly in the call to setGeneric, it is usually the package on which the corresponding non-generic function exists.
group:
Object of class "list", the group or groups to which this generic function belongs. Empty by default.
valueClass:
Object of class "character"; if not an empty character vector, identifies one or more classes. It is asserted that all methods for this function return objects from these class (or from classes that extend them).
signature:
Object of class "character", the vector of formal argument names that can appear in the signature of methods for this generic function. By default, it is all the formal arguments, except for .... Order matters for efficiency: the most commonly used arguments in specifying methods should come first.
default:
Object of class "OptionalMethods", the default method for this function. Generated automatically and used to initialize method dispatch.
skeleton:
Object of class "call", a slot used internally in method dispatch. Don't expect to use it directly.

Extends

Class "function", from data part.
Class "OptionalMethods", by class "function".
Class "PossibleMethod", by class "function".

Methods

Generic function objects are used in the creation and dispatch of formal methods; information from the object is used to create methods list objects and to merge or update the existing methods for this generic.


Tools for Managing Generic Functions

Description

The functions documented here manage collections of methods associated with a generic function, as well as providing information about the generic functions themselves.

Usage

isGeneric(f, where, fdef, getName = FALSE)
isGroup(f, where, fdef)
removeGeneric(f, where)

dumpMethod(f, signature, file, where, def)
findFunction(f, generic = TRUE, where = topenv(parent.frame()))
dumpMethods(f, file, signature, methods, where)
signature(...)

removeMethods(f, where = topenv(parent.frame()), all = TRUE)
setReplaceMethod(f, ..., where = topenv(parent.frame()))

getGenerics(where, searchForm = FALSE)
allGenerics(where, searchForm = FALSE)
callGeneric(...)

Arguments

f | The character string naming the function.
where | The environment, namespace, or search-list position from which to search for objects. By default, start at the top-level environment of the calling function, typically the global environment (i.e., use the search list), or the namespace of a package from which the call came. It is important to supply this argument when calling any of these functions indirectly. With package namespaces, the default is likely to be wrong in such calls.
signature | The class signature of the relevant method. A signature is a named or unnamed vector of character strings. If named, the names must be formal argument names for the generic function. If signature is unnamed, the default is to use the first length(signature) formal arguments of the function.
file | The file on which to dump method definitions.
def | The function object defining the method; if omitted, the current method definition corresponding to the signature.
... | Named or unnamed arguments to form a signature.
generic | In testing or finding functions, should generic functions be included. Supply as FALSE to get only non-generic functions.
fdef | Optional, the generic function definition. Usually omitted in calls to isGeneric
getName | If TRUE, isGeneric returns the name of the generic. By default, it returns TRUE.
methods | The methods object containing the methods to be dumped. By default, the methods defined for this generic (optionally on the specified where location).
all | in removeMethods, logical indicating if all (default) or only the first method found should be removed.
searchForm | In getGenerics, if TRUE, the package slot of the returned result is in the form used by search(), otherwise as the simple package name (e.g, "package:base" vs "base").

Summary of Functions

isGeneric:
Is there a function named f, and if so, is it a generic?

The getName argument allows a function to find the name from a function definition. If it is TRUE then the name of the generic is returned, or FALSE if this is not a generic function definition.

The behavior of isGeneric and getGeneric for primitive functions is slightly different. These functions don't exist as formal function objects (for efficiency and historical reasons), regardless of whether methods have been defined for them. A call to isGeneric tells you whether methods have been defined for this primitive function, anywhere in the current search list, or in the specified position where. In contrast, a call to getGeneric will return what the generic for that function would be, even if no methods have been currently defined for it.

removeGeneric, removeMethods:
Remove all the methods for the generic function of this name. In addition, removeGeneric removes the function itself; removeMethods restores the non-generic function which was the default method. If there was no default method, removeMethods leaves a generic function with no methods.
standardGeneric:
Dispatches a method from the current function call for the generic function f. It is an error to call standardGeneric anywhere except in the body of the corresponding generic function.

Note that standardGeneric is a primitive function in the base package for efficiency reasons, but rather documented here where it belongs naturally.

dumpMethod:
Dump the method for this generic function and signature.
findFunction:
return a list of either the positions on the search list, or the current top-level environment, on which a function object for name exists. The returned value is always a list, use the first element to access the first visible version of the function. See the example.

NOTE: Use this rather than find with mode="function", which is not as meaningful, and has a few subtle bugs from its use of regular expressions. Also, findFunction works correctly in the code for a package when attaching the package via a call to library.

dumpMethods:
Dump all the methods for this generic.
signature:
Returns a named list of classes to be matched to arguments of a generic function.
getGenerics:
Returns the names of the generic functions that have methods defined on where; this argument can be an environment or an index into the search list. By default, the whole search list is used.

The methods definitions are stored with package qualifiers; for example, methods for function "initialize" might refer to two different functions of that name, on different packages. The package names corresponding to the method list object are contained in the slot package of the returned object. The form of the returned name can be plain (e.g., "base"), or in the form used in the search list ("package:base") according to the value of searchForm

callGeneric:
In the body of a method, this function will make a call to the current generic function. If no arguments are passed to callGeneric, the arguments to the current call are passed down; otherwise, the arguments are interpreted as in a call to the generic function.

Details

setGeneric:
If there is already a non-generic function of this name, it will be used to define the generic unless def is supplied, and the current function will become the default method for the generic.

If def is supplied, this defines the generic function, and no default method will exist (often a good feature, if the function should only be available for a meaningful subset of all objects).

Arguments group and valueClass are retained for consistency with S-Plus, but are currently not used.

isGeneric:
If the fdef argument is supplied, take this as the definition of the generic, and test whether it is really a generic, with f as the name of the generic. (This argument is not available in S-Plus.)
removeGeneric:
If where supplied, just remove the version on this element of the search list; otherwise, removes the first version encountered.
standardGeneric:
Generic functions should usually have a call to standardGeneric as their entire body. They can, however, do any other computations as well.

The usual setGeneric (directly or through calling setMethod) creates a function with a call to standardGeneric.

dumpMethod:
The resulting source file will recreate the method.
findFunction:
If generic is FALSE, ignore generic functions.
dumpMethods:
If signature is supplied only the methods matching this initial signature are dumped. (This feature is not found in S-Plus: don't use it if you want compatibility.)
signature:
The advantage of using signature is to provide a check on which arguments you meant, as well as clearer documentation in your method specification. In addition, signature checks that each of the elements is a single character string.
removeMethods:
Returns TRUE if f was a generic function, FALSE (silently) otherwise.

If there is a default method, the function will be re-assigned as a simple function with this definition. Otherwise, the generic function remains but with no methods (so any call to it will generate an error). In either case, a following call to setMethod will consistently re-establish the same generic function as before.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

getMethod (also for selectMethod), setGeneric, setClass, showMethods

Examples

## get the function "myFun" -- throw an error if 0 or > 1 versions visible:
findFuncStrict <- function(fName) {
  allF <- findFunction(fName)
  if(length(allF) == 0)
    stop("No versions of ",fName," visible")
  else if(length(allF) > 1)
    stop(fName," is ambiguous: ", length(allF), " versions")
  else
    get(fName, allF[[1]])
}

try(findFuncStrict("myFun"))# Error: no version
lm <- function(x) x+1
try(findFuncStrict("lm"))#    Error: 2 versions
findFuncStrict("findFuncStrict")# just 1 version
rm(lm)


Get Class Definition

Description

Get the definition of a class.

Usage

getClass(Class, .Force = FALSE, where)
getClassDef(Class, where, package)

Arguments

Class | the character-string name of the class.
.Force | if TRUE, return NULL if the class is undefined; otherwise, an undefined class results in an error.
where | environment from which to begin the search for the definition; by default, start at the top-level (global) environment and proceed through the search list.
package | the name of the package asserted to hold the definition. Supplied instead of where, with the distinction that the package need not be currently attached.

Details

A call to getClass returns the complete definition of the class supplied as a string, including all slots, etc. in classes that this class extends. A call to getClassDef returns the definition of the class from the environment where, unadorned. It's usually getClass you want.

If you really want to know whether a class is formally defined, call isClass.

Value

The object defining the class. This is an object of class "classRepEnvironment". However, do not deal with the contents of the object directly unless you are very sure you know what you're doing. Even then, it is nearly always better practice to use functions such as setClass and setIs. Messing up a class object will cause great confusion.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

Classes, setClass, isClass.

Examples

getClass("numeric") ## a built in class

cld <- getClass("thisIsAnUndefinedClass", .Force = TRUE)
cld ## a NULL prototype
## If you are really curious:
str(cld)
## Whereas these generate errors:
try(getClass("thisIsAnUndefinedClass"))
try(getClassDef("thisIsAnUndefinedClass"))


Get or Test for the Definition of a Method

Description

The functions getMethod and selectMethod get the definition of a particular method; the functions existsMethod and hasMethod test for the existence of a method. In both cases the first function only gets direct definitions and the second uses inheritance. The function findMethod returns the package(s) in the search list (or in the packages specified by the where argument) that contain a method for this function and signature.

The other functions are support functions: see the details below.

Usage

getMethod(f, signature=character(), where, optional=FALSE, mlist, fdef)

findMethod(f, signature, where)

getMethods(f, where)

existsMethod(f, signature = character(), where)

hasMethod(f, signature=character(), where)

selectMethod(f, signature, optional = FALSE, useInherited = TRUE,
             mlist = (if (is.null(fdef)) NULL else
                      getMethodsForDispatch(f, fdef)),
             fdef = getGeneric(f, !optional))

MethodsListSelect(f, env, mlist, fEnv, finalDefault, evalArgs,
                  useInherited, fdef, resetAllowed)

Arguments

f | The character-string name of the generic function.
signature | the signature of classes to match to the arguments of f. See the details below. For selectMethod, the signature can optionally be an environment with classes assigned to the names of the corresponding arguments. Note: the names correspond to the names of the classes, not to the objects supplied in a call to the generic function. (You are not likely to find this approach convenient, but it is used internally and is marginally more efficient.)
where | The position or environment in which to look for the method(s): by default, anywhere in the current search list.
optional | If the selection does not produce a unique result, an error is generated, unless this argument is TRUE. In that case, the value returned is either a MethodsList object, if more than one method matches this signature, or NULL if no method matches.
mlist | Optionally, the list of methods in which to search. By default, the function finds the methods for the corresponding generic function. To restrict the search to a particular package or environment, e.g., supply this argument as getMethodsMetaData(f,where). For selectMethod, see the discussion of argument fdef.
fdef | Optionally, the generic function from which the method is to be retrieved. (Unlikely to be used, except internally in the package source.)
env | The environment in which argument evaluations are done in MethodsListSelect. Currently must be supplied, but should usually be sys.frame(sys.parent()) when calling the function explicitly for debugging purposes.
fEnv, finalDefault, evalArgs, useInherited, resetAllowed | Internal-use arguments for the function's environment, the method to use as the overall default, whether to evaluate arguments, which arguments should use inheritance, and whether the cached methods are allowed to be reset.

Details

The signature argument specifies classes, in an extended sense, corresponding to formal arguments of the generic function. As supplied, the argument may be a vector of strings identifying classes, and may be named or not. Names, if supplied, match the names of those formal arguments included in the signature of the generic. That signature is normally all the arguments except .... However, generic functions can be specified with only a subset of the arguments permitted, or with the signature taking the arguments in a different order.

It's a good idea to name the arguments in the signature to avoid confusion, if you're dealing with a generic that does something special with its signature. In any case, the elements of the signature are matched to the formal signature by the same rules used in matching arguments in function calls (see match.call).

The strings in the signature may be class names, "missing" or "ANY". See Methods for the meaning of these in method selection. Arguments not supplied in the signature implicitly correspond to class "ANY"; in particular, giving an empty signature means to look for the default method.

A call to getMethod returns the method for a particular function and signature. As with other get functions, argument where controls where the function looks (by default anywhere in the search list) and argument optional controls whether the function returns NULL or generates an error if the method is not found. The search for the method makes no use of inheritance.

The function selectMethod also looks for a method given the function and signature, but makes full use of the method dispatch mechanism; i.e., inherited methods and group generics are taken into account just as they would be in dispatching a method for the corresponding signature, with the one exception that conditional inheritance is not used. Like getMethod, selectMethod returns NULL or generates an error if the method is not found, depending on the argument optional.

The functions existsMethod and hasMethod return TRUE or FALSE according to whether a method is found, the first corresponding to getMethod (no inheritance) and the second to selectMethod.

The function getMethods returns all the methods for a particular generic (in the form of a generic function with the methods information in its environment). The function is called from the evaluator to merge method information, and is not intended to be called directly. Note that it gets all the visible methods for the specified functions. If you want only the methods defined explicitly in a particular environment, use the function getMethodsMetaData instead.

The function MethodsListSelect performs a full search (including all inheritance and group generic information: see the Methods documentation page for details on how this works). The call returns a possibly revised methods list object, incorporating any method found as part of the allMethods slot.

Normally you won't call MethodsListSelect directly, but it is possible to use it for debugging purposes (only for distinctly advanced users!).

Note that the statement that MethodsListSelect corresponds to the selection done by the evaluator is a fact, not an assertion, in the sense that the evaluator code constructs and executes a call to MethodsListSelect when it does not already have a cached method for this generic function and signature. (The value returned is stored by the evaluator so that the search is not required next time.)

Value

The call to selectMethod or getMethod returns a MethodDefinition-class object, the selected method, if a unique selection exists. (This class extends function, so you can use the result directly as a function if that is what you want.) Otherwise an error is thrown if optional is FALSE. If optional is TRUE, the value returned is NULL if no method matched, or a MethodsList object if multiple methods matched.
The call to getMethods returns the MethodsList object containing all the methods requested. If there are none, NULL is returned: getMethods does not generate an error in this case.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

GenericFunctions

Examples

setGeneric("testFun", function(x)standardGeneric("testFun"))
setMethod("testFun", "numeric", function(x)x+1)
hasMethod("testFun", "numeric")
## Not run: [1] TRUE
hasMethod("testFun", "integer") #inherited
## Not run: [1] TRUE
existsMethod("testFun", "integer")
## Not run: [1] FALSE
hasMethod("testFun") # default method
## Not run: [1] FALSE
hasMethod("testFun", "ANY")
## Not run: [1] FALSE


The Name associated with a Given Package

Description

The functions below produce the package associated with a particular environment or position on the search list, or of the package containing a particular function. They are primarily used to support computations that need to differentiate objects on multiple packages.

Usage

getPackageName(where)

packageSlot(object)
packageSlot(object) <- value

Arguments

where | the environment or position on the search list associated with the desired package.
object | object providing a character string name, plus the package in which this object is to be found.
value | the name of the package.

Details

Package names are normally installed during loading of the package, by the INSTALL script or by the library function. (Currently, the name is stored as the object .packageName but don't trust this for the future.)

Value

packageName return the character-string name of the package (without the extraneous "package:" found in the search list).
packageSlot returns or sets the package name slot (currently an attribute, not a formal slot, but this will likely change).

See Also

search

Examples

## both the following usually return "base"
getPackageName(length(search()))


Look for an Argument in the Call

Description

Returns TRUE if name corresponds to an argument in the call, either a formal argument to the function, or a component of ..., and FALSE otherwise.

Usage

hasArg(name)

Arguments

name The unquoted name of a potential argument.

Details

The expression hasArg(x), for example, is similar to !missing(x), with two exceptions. First, hasArg will look for an argument named x in the call if x is not a formal argument to the calling function, but ... is. Second, hasArg never generates an error if given a name as an argument, whereas missing(x) generates an error if x is not a formal argument.

Value

Always TRUE or FALSE as described above.

See Also

missing

Examples

ftest <- function(x1, ...) c(hasArg(x1), hasArg(y2))

ftest(1) ## c(TRUE, FALSE)
ftest(1, 2)  ## c(TRUE, FALSE)
ftest(y2=2)   ## c(FALSE, TRUE)
ftest(y=2)    ## c(FALSE, FALSE) (no partial matching)
ftest(y2 = 2, x=1)  ## c(TRUE, TRUE) partial match x1


Methods to Initialize New Objects from a Class

Description

The arguments to function new to create an object from a particular class can be interpreted specially for that class, by the definition of a method for function initialize for the class. This documentation describes some existing methods, and also outlines how to write new ones.

Methods

.Object = "ANY"
The default method for initialize takes either named or unnamed arguments. Argument names must be the names of slots in this class definition, and the corresponding arguments must be valid objects for the slot (that is, have the same class as specified for the slot, or some superclass of that class). If the object comes from a superclass, it is not coerced strictly, so normally it will retain its current class (specifically, as(object, Class, strict = FALSE)).

Unnamed arguments must be objects of this class, of one of its superclasses, or one of its subclasses (from the class, from a class this class extends, or from a class that extends this class). If the object is from a superclass, this normally defines some of the slots in the object. If the object is from a subclass, the new object is that argument, coerced to the current class.

Unnamed arguments are processed first, in the order they appear. Then named arguments are processed. Therefore, explicit values for slots always override any values inferred from superclass or subclass arguments.

.Object = "traceable"
Objects of a class that extends traceable are used to implement debug tracing (see traceable-class and trace).

The initialize method for these classes takes special arguments def, tracer, exit, at, print. The first of these is the object to use as the original definition (e.g., a function). The others correspond to the arguments to trace.

.Object = "environment"
The initialize method for environments takes a named list of objects to be used to initialize the environment.
.Object = "signature"
This is a method for internal use only. It takes an optional functionDef argument to provide a generic function with a signature slot to define the argument names. See Methods for details.

Writing Initialization Methods

Initialization methods provide a general mechanism corresponding to generator functions in other languages.

The arguments to initialize are .Object and .... Nearly always, initialize is called from new, not directly. The .Object argument is then the prototype object from the class.

Two techniques are often appropriate for initialize methods: special argument names and callNextMethod.

You may want argument names that are more natural to your users than the (default) slot names. These will be the formal arguments to your method definition, in addition to .Object (always) and ... (optionally). For example, the method for class "traceable" documented above would be created by a call to setMethod of the form:

    setMethod("initialize", "traceable",
      function(.Object, def, tracer, exit, at, print) ...
    )

In this example, no other arguments are meaningful, and the resulting method will throw an error if other names are supplied.

When your new class extends another class, you may want to call the initialize method for this superclass (either a special method or the default). For example, suppose you want to define a method for your class, with special argument x, but you also want users to be able to set slots specifically. If you want x to override the slot information, the beginning of your method definition might look something like this:

    function(.Object, x, ...) {
      Object <- callNextMethod(.Object, ...)
      if(!missing(x)) { # do something with x

You could also choose to have the inherited method override, by first interpreting x, and then calling the next method.


Is an Object from a Class

Description

is: With two arguments, tests whether object can be treated as from class2.

With one argument, returns all the super-classes of this object's class.

extends: Does the first class extend the second class? Returns maybe if the extension includes a test.

setIs: Defines class1 to be an extension of class2.

Usage

is(object, class2)

extends(class1, class2, maybe=TRUE, fullInfo = FALSE)

setIs(class1, class2, test=NULL, coerce=NULL, replace=NULL,
      by = character(), where = topenv(parent.frame()), classDef =,
      extensionObject = NULL, doComplete = TRUE)

Arguments

object | any R object.
class1, class2 | the names of the classes between which is relations are to be defined.
maybe, fullInfo | In a call to extends, maybe is a flag to include/exclude conditional relations, and fullInfo is a flag, which if TRUE causes object(s) of class classExtension to be returned, rather than just the names of the classes or a logical value. See the details below.
extensionObject | alternative to the test, coerce, replace, by arguments; an object from class SClassExtension describing the relation. (Used in internal calls.)
doComplete | when TRUE, the class definitions will be augmented with indirect relations as well. (Used in internal calls.)
test, coerce, replace | In a call to setIs, functions optionally supplied to test whether the relation is defined, to coerce the object to class2, and to alter the object so that is(object, class2) is identical to value.
by | In a call to setIs, the name of an intermediary class. Coercion will proceed by first coercing to this class and from there to the target class. (The intermediate coercions have to be valid.)
where | In a call to setIs, where to store the metadata defining the relationship. Default is the global environment.
classDef | Optional class definition for class , required internally when setIs is called during the initial definition of the class by a call to setClass. Don't use this argument, unless you really know why you're doing so.

Details

extends:

Given two class names, extends by default says whether the first class extends the second; that is, it does for class names what is does for an object and a class. Given one class name, it returns all the classes that class extends (the “superclasses” of that class), including the class itself. If the flag fullInfo is TRUE, the result is a list, each element of which is an object describing the relationship; otherwise, and by default, the value returned is only the names of the classes.

setIs:

This function establishes an inheritance relation between two classes, by some means other than having one class contain the other. It should not be used for ordinary relationships: either include the second class in the contains= argument to setClass if the class is contained in the usual way, or consider setClassUnion to define a virtual class that is extended by several ordinary classes. A call to setIs makes sense, for example, if one class ought to be automatically convertible into a second class, but they have different representations, so that the conversion must be done by an explicit computation, not just be inheriting slots, for example. In this case, you will typically need to provide both a coerce= and replace= argument to setIs.

The coerce, replace, and by arguments behave as described for the setAs function. It's unlikely you would use the by argument directly, but it is used in defining cached information about classes. The value returned (invisibly) by setIs is the extension information, as a list.

The coerce argument is a function that turns a class1 object into a class2 object. The replace argument is a function of two arguments that modifies a class1 object (the first argument) to replace the part of it that corresponds to class2 (supplied as value, the second argument). It then returns the modified object as the value of the call. In other words, it acts as a replacement method to implement the expression as(object, class2) <- value.

The easiest way to think of the coerce and replace functions is by thinking of the case that class1 contains class2 in the usual sense, by including the slots of the second class. (To repeat, in this situation you would not call setIs, but the analogy shows what happens when you do.)

The coerce function in this case would just make a class2 object by extracting the corresponding slots from the class1 object. The replace function would replace in the class1 object the slots corresponding to class2, and return the modified object as its value.

The relationship can also be conditional, if a function is supplied as the test argument. This should be a function of one argument that returns TRUE or FALSE according to whether the object supplied satisfies the relation is(object, class2). If you worry about such things, conditional relations between classes are slightly deprecated because they cannot be implemented as efficiently as ordinary relations and because they sometimes can lead to confusion (in thinking about what methods are dispatched for a particular function, for example). But they can correspond to useful distinctions, such as when two classes have the same representation, but only one of them obeys certain additional constraints.

Because only global environment information is saved, it rarely makes sense to give a value other than the default for argument where. One exception is where=0, which modifies the cached (i.e., session-scope) information about the class. Class completion computations use this version, but don't use it yourself unless you are quite sure you know what you're doing.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

Examples

## a class definition (see setClass for the example)
setClass("trackCurve",
         representation("track", smooth = "numeric"))
## A class similar to "trackCurve", but with different structure
## allowing matrices for the "y" and "smooth" slots
setClass("trackMultiCurve",
         representation(x="numeric", y="matrix", smooth="matrix"),
         prototype = structure(list(), x=numeric(), y=matrix(0,0,0),

                               smooth= matrix(0,0,0)))
## Automatically convert an object from class "trackCurve" into
## "trackMultiCurve", by making the y, smooth slots into 1-column matrices
setIs("trackCurve",
      "trackMultiCurve",
      coerce = function(obj) {
        new("trackMultiCurve",
            x = obj@x,
            y = as.matrix(obj@y),
            curve = as.matrix(obj@smooth))
      },
      replace = function(obj, value) {
        obj@y <- as.matrix(value@y)
        obj@x <- value@x
        obj@smooth <- as.matrix(value@smooth)
        obj})

## Automatically convert the other way, but ONLY
## if the y data is one variable.
setIs("trackMultiCurve",
      "trackCurve",
      test = function(obj) {ncol(obj@y) == 1},
      coerce = function(obj) {
        new("trackCurve",
            x = slot(obj, "x"),
            y = as.numeric(obj@y),
            smooth = as.numeric(obj@smooth))
      },
      replace = function(obj, value) {
        obj@y <- matrix(value@y, ncol=1)
        obj@x <- value@x
        obj@smooth <- value@smooth
        obj})


Check for a Sealed Method or Class

Description

These functions check for either a method or a class that has been “sealed” when it was defined, and which therefore cannot be re-defined.

Usage

isSealedMethod(f, signature, fdef, where)
isSealedClass(Class, where)

Arguments

f | The quoted name of the generic function.
signature | The class names in the method's signature, as they would be supplied to setMethod.
fdef | Optional, and usually omitted: the generic function definition for f.
Class | The quoted name of the class.
where | where to search for the method or class definition. By default, searches from the top environment of the call to isSealedMethod or isSealedClass, typically the global environment or the namespace of a package containing a call to one of the functions.

Details

In the R implementation of classes and methods, it is possible to seal the definition of either a class or a method. The basic classes (numeric and other types of vectors, matrix and array data) are sealed. So also are the methods for the primitive functions on those data types. The effect is that programmers cannot re-define the meaning of these basic data types and computations. More precisely, for primitive functions that depend on only one data argument, methods cannot be specified for basic classes. For functions (such as the arithmetic operators) that depend on two arguments, methods can be specified if one of those arguments is a basic class, but not if both are.

Programmers can seal other class and method definitions by using the sealed argument to setClass or setMethod.

Value

The functions return FALSE if the method or class is not sealed (including the case that it is not defined); TRUE if it is.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

Examples

## these are both TRUE
isSealedMethod("+", c("numeric", "character"))
isSealedClass("matrix")

setClass("track",
            representation(x="numeric", y="numeric"))
## but this is FALSE
isSealedClass("track")
## and so is this
isSealedClass("A Name for an undefined Class")
## and so are these, because only one of the two arguments is basic
isSealedMethod("+", c("track", "numeric"))
isSealedMethod("+", c("numeric", "track"))


Classes to Represent Unevaluated Language Objects

Description

The virtual class "language" and the specific classes that extend it represent unevaluated objects, as produced for example by the parser or by functions such as quote.

Usage

### each of these classes corresponds to an unevaluated object
### in the S language.  The class name can appear in method signatures,
### and in a few other contexts (such as some calls to as()).

"("
"<-"
"call"
"for"
"if"
"repeat"
"while"
"name"
"{"

### Each of the classes above extends the virtual class

"language"

Objects from the Class

"language" is a virtual class; no objects may be created from it.

Objects from the other classes can be generated by a call to new(Class, ...), where Class is the quoted class name, and the ... arguments are either empty or a single object that is from this class (or an extension).

Methods

coerce
signature(from = "ANY", to = "call"). A method exists for as(object, "call"), calling as.call().


Elements of Language Objects

Description

Internal routines to support some operations on language objects.

Usage

languageEl(object, which)

isGrammarSymbol(symbol)

Summary of Functions

languageEl:
extract an element of a language object, consistently for different kinds of objects.

The 1st., etc. elements of a function are the corresponding formal arguments, with the default expression if any as value.

The first element of a call is the name or the function object being called.

The 2nd, 3rd, etc. elements are the 1st, 2nd, etc. arguments expressions. Note that the form of the extracted name is different for R and S-Plus. When the name (the first element) of a call is replaced, the languageEl replacement function coerces a character string to the internal form for each system.

The 1st, 2nd, 3rd elements of an if expression are the test, first, and second branch.

The 1st element of a for object is the name (symbol) being used in the loop, the second is the expression for the range of the loop, the third is the body of the loop.

The first element of a while object is the loop test, and the second the body of the loop.

isGrammarSymbol:
Checks whether the symbol is part of the grammar. Don't use this function directly.


Class "LinearMethodsList"

LinearMethodsList-class(methods) R Documentation

Class 'LinearMethodsList'

Description

A version of methods lists that has been “linearized” for producing summary information. The actual objects from class "MethodsList" used for method dispatch are defined recursively over the arguments involved.

Objects from the Class

The function linearizeMlist converts an ordinary methods list object into the linearized form.

Slots

methods:
Object of class "list", the method definitions.
arguments:
Object of class "list", the corresponding formal arguments.
classes:
Object of class "list", the corresponding classes in the signatures.
fromClasses:
Object of class "list"

Future Note

The current version of linearizeMlist does not take advantage of the MethodDefinition class, and therefore does more work for less effect than it could. In particular, we may move to redefine both the function and the class to take advantage of the stored signatures. Don't write code depending precisely on the present form, although all the current information will be obtainable in the future.

See Also

Function linearizeMlist for the computation, and MethodsList-class for the original, recursive form.


Classes to Represent Method Definitions

Description

These classes extend the basic class "function" when functions are to be stored and used as method definitions.

Details

Method definition objects are functions with additional information defining how the function is being used as a method. The target slot is the class signature for which the method will be dispatched, and the defined slot the signature for which the method was orignally specified (that is, the one that appeared in some call to setMethod).

Objects from the Class

The action of setting a method by a call to setMethod creates an object of this class. It's unwise to create them directly.

The class "SealedMethodDefinition" is created by a call to setMethod with argument sealed = TRUE. It has the same representation as "MethodDefinition".

Slots

.Data:
Object of class "function"; the data part of the definition.
target:
Object of class "signature"; the signature for which the method was wanted.
defined:
Object of class "signature"; the signature for which a method was found. If the method was inherited, this will not be identical to target.
generic:
Object of class "character"; the function for which the method was created.

Extends

Class "function", from data part.
Class "PossibleMethod", directly.
Class "OptionalMethods", by class "function".

See Also

class MethodsList-class for the objects defining sets of methods associated with a particular generic function. The individual method definitions stored in these objects are from class MethodDefinition, or an extension. MethodWithNext-class for an extension used by callNextMethod.


General Information on Methods

Description

This documentation section covers some general topics on how methods work and how the methods package interacts with the rest of R. The information is usually not needed to get started with methods and classes, but may be helpful for moderately ambitious projects, or when something doesn't work as expected.

The section How Methods Work describes the underlying mechanism; Dispatch and Method Selection provides more details on how class definitions determine which methods are used. For additional information specifically about class definitions, see ?Classes.

How Methods Work

A generic function is a function that has associated with it a collection of other functions (the methods), all of which agree in formal arguments with the generic.

Each R package will include methods metadata objects corresponding to each generic function for which methods have been defined in that package. When the package is loaded into an R session, the methods for each generic function are cached, that is, stored in the environment of the generic function along with the methods from previously loaded packages. This merged table of methods is used to dispatch or select methods from the generic, using class inheritance and possibly group generic functions to find an applicable method. See the Dispatch section below. The caching computations ensure that only one version of each generic function is visible globally; although different attached packages may contain a copy of the generic function, these are in fact identical.

The methods for a generic are stored according to the corresponding signature for which the method was defined, in a call to setMethod. The signature associates one class name with each of a subset of the formal arguments to the generic function. Which formal arguments are available, and the order in which they appear, are determined by the "signature" slot of the generic function. By default, the signature of the generic consists of all the formal arguments except ..., in the order they appear in the function definition.

Trailing arguments in the signature will be inactive if no method has yet been specified that included those arguments. Inactive arguments are not needed or used in labeling the cached methods. (The distinction does not change which methods are dispatched, but ignoring inactive arguments does improve the efficiency of dispatch. Thus, defining the generic signature to contain the most useful arguments first can help efficiency somewhat.)

All arguments in the signature of the generic function will be evaluated when the function is called, rather than using the traditional lazy evaluation rules of S. Therefore, it's important to exclude from the signature any arguments that need to be dealt with symbolically (such as the first argument to function substitute). Note that only actual arguments are evaluated, not default expressions. A missing argument enters into the method selection as class "missing" and non-missing arguments according to their actual class.

As of version 2.4.0 of R, the cached methods are stored in an environment object. The names used for assignment are a concatenation of the class names for the arguments in the active signature.

Dispatch and Method Selection

When a call to a generic function is evaluated, a method is selected corresponding to the classes of the actual arguments in the signature. First, the cached methods table is searched for a direct match; that is, a method stored under the direct class names. The direct class is the value of class(x) for each non-missing argument, and class "missing" for each missing argument. If no method is found directly for the actual arguments in a call to a generic function, an attempt is made to match the available methods to the arguments by using inheritance.

Each class definition potentially includes the names of one or more classes that the new class contains. (These are sometimes called the superclasses of the new class.) The S language has an additional, explicit mechanism for defining superclasses, the setIs mechanism. Also, a call to setClassUnion makes the union class a superclass of each of the members of the union. All three mechanisms are treated equivalently for purposes of inheritance: they define the direct superclasses of a particular class.

The direct superclasses themselves may contain other classes. Putting all this information together produces the full list of superclasses for this class. The superclass list is included in the definition of the class that is cached during the R session. Each element of the list describes the nature of the relationship (see SClassExtension-class for details). Included in the element is a distance slot giving a numeric distance between the two classes. The distance currently is the path length for the relationship: 1 for direct superclasses (regardless of which mechanism defined them), then 2 for the direct superclasses of those classes, and so on. In addition, any class implicitly has class "ANY" as a superclass. The distance to "ANY" is treated as larger than the distance to any actual class. The special class "missing" corresponding to missing arguments has only "ANY" as a superclass, while "ANY" has no superclasses.

The information about superclasses is summarized when a class definition is printed.

When a method is to be selected by inheritance, a search is made in the table for all methods directly corresponding to a combination of either the direct class or one of its superclasses, for each argument in the active signature. For an example, suppose there is only one argument in the signature and that the class of the corresponding object was "dgeMatrix" (from the Matrix package on CRAN). This class has two direct superclasses and through these 4 additional superclasses. Method selection finds all the methods in the table of directly specified methods labeled by one of these classes, or by "ANY".

When there are multiple arguments in the signature, each argument will generate a similar list of inherited classes. The possible matches are now all the combinations of classes from each argument (think of the function outer generating an array of all possible combinations). The search now finds all the methods matching any of this combination of classes. The computation of distances also has to combine distances for the individual arguments. There are many ways to combine the distances; the current implementation simply adds them. The result of the search is then a list of zero, one or more methods, and a parallel vector of distances between the target signature and the available methods.

If the list has more than one matching method, only those corresponding to the minimum distance are considered. There may still be multiple best methods. The dispatch software considers this an ambiguous case and warns the user (only on the first call for this selection). The method occurring first in the list of superclasses is selected. By the mechanism of producing the extension information, this orders the direct superclasses by the order they appeared in the original call to setClass, followed by classes specified in setIs calls, in the order those calls were evaluated, followed by classes specified in unions. Then the superclasses of those classes are appended (note that only the ordering of classes within a particular generation of superclasses counts, because only these will have the same distance). For further discussion of method selection, see the document http://developer.r-project.org/howMethodsWork.pdf.

All this detail about selection is less important than the realization that having ambiguous method selection usually means that you need to be more specific about intentions. It is likely that some consideration other than the ordering of superclasses in the class definition is more important in determining which method should be selected, and the preference may well be different for different generic functions. Where ambiguities arise, the best approach is usually to provide a specific method for the subclass.

When the inherited method has been selected, the selection is cached in the generic function so that future calls with the same class will not require repeating the search. Cached non-direct selections are not themselves used in inheritance searches, since that could result in invalid selections.

Besides being initiated through calls to the generic function, method selection can be done explicitly by calling the function selectMethod.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference.

See Also

setGeneric, setClass and the document http://developer.r-project.org/howMethodsWork.pdf.


Formal Methods and Classes

Description

Formally defined methods and classes for R objects, plus other programming tools, as described in the references.

Details

This package provides the “S4” or “S version 4” approach to methods and classes in a functional language.

For a complete list of functions and classes, use library(help="methods").

Author(s)

R Development Core Team

Maintainer: R Core Team R-core@r-project.org

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.


MethodsList Objects

Description

These functions create and manipulate MethodsList objects, the objects used in R to store methods for dispatch. You should not call any of these functions from code that you want to port to S-Plus. Instead, use the functions described in the references.

Usage

MethodsList(.ArgName, ...)

makeMethodsList(object, level=1)

SignatureMethod(names, signature, definition)

insertMethod(mlist, signature, args, def, cacheOnly)

inheritedSubMethodLists(object, thisClass, mlist, ev)

showMlist(mlist, includeDefs = TRUE, inherited = TRUE,
   classes, useArgNames, printTo = stdout() )

## S3 method for class 'MethodsList':
print(x, ...)

listFromMlist(mlist, prefix = list())

linearizeMlist(mlist, inherited = TRUE)

finalDefaultMethod(mlist, fname = "NULL")

mergeMethods(m1, m2, genericLabel)

loadMethod(method, fname, envir)

Details

Note that MethodsList objects represent methods only in the R implementation. You can use them to find or manipulate information about methods, but avoid doing so if you want your code to port to S-Plus.

Details

MethodsList:
Create a MethodsList object out of the arguments.

Conceptually, this object is a named collection of methods to be dispatched when the (first) argument in a function call matches the class corresponding to one of the names. A final, unnamed element (i.e., with name "") corresponds to the default method.

The elements can be either a function, or another MethodsList. In the second case, this list implies dispatching on the second argument to the function using that list, given a selection of this element on the first argument. Thus, method dispatching on an arbitrary number of arguments is defined.

MethodsList objects are used primarily to dispatch OOP-style methods and, in R, to emulate S4-style methods.

SignatureMethod:
construct a MethodsList object containing (only) this method, corresponding to the signature; i.e., such that signature[[1]] is the match for the first argument, signature[[2]] for the second argument, and so on. The string "missing" means a match for a missing argument, and "ANY" means use this as the default setting at this level.

The first argument is the argument names to be used for dispatch corresponding to the signatures.

insertMethod:
insert the definition def into the MethodsList object, mlist, corresponding to the signature. By default, insert it in the slot "methods", but cacheOnly=TRUE inserts it into the "allMethods" slot (used for dispatch but not saved).
inheritedSubMethodLists:
Utility function to match the object or the class (if the object is NULL) to the elements of a methods list. Used in finding inherited methods, and not meant to be called directly.
showMlist:
Prints the contents of the MethodsList. If includeDefs the signatures and the corresonding definitions will be printed; otherwise, only the signatures.
listFromMlist:
Undo the recursive nature of the methods list, making a list of function definitions, with the names of the list being the corresponding signatures prefix is the partial signature (a named list of classes) to be prepended to the signatures in this object.

A utility function used to iterate over all the individual methods in the object, it calls itself recursively.

linearizeMlist:
Undo the recursive nature of the methods list, making a list of function definitions, with the names of the list being the corresponding signatures.

Designed for printing; for looping over the methods, use the above listFromMlist instead.

finalDefaultMethod:
The true default method for the methods list object mlist (the method that matches class "ANY" for as many arguments as are used in methods matching for this generic function). If mlist is null, returns the function called fname, or NULL if there is no such function.
mergeMethods:
Merges the methods in the second MethodsList object into the first, and returns the merged result. Called from getAllMethods. For a primitive function, genericLabel is supplied as the name of the generic.
loadMethod:
Called, if necessary, just before a call to method is dispatched in the frame envir. The function exists so that methods can be defined for special classes of objects. Usually the point is to assign or modify information in the frame environment to be used evaluation. For example, the standard class MethodDefinition has a method that stores the target and defined signatures in the environment. Class MethodWithNext has a method taking account of the mechanism for storing the method to be used in a call to callNextMethod.

Any methods defined for loadMethod must return the function definition to be used for this call; typically, this is just the method argument.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.


Class MethodsList, Representation of Methods for a Generic Function

MethodsList-class(methods) R Documentation

Class MethodsList Representation of Methods for a Generic Function

Description

Objects from this class are generated and revised by the definition of methods for a generic function.

Details

Suppose a function f has formal arguments x and y. The methods list object for that function has the object as.name("x") as its argument slot. An element of the methods named "track" is selected if the actual argument corresponding to x is an object of class "track". If there is such an element, it can generally be either a function or another methods list object.

In the first case, the function defines the method to use for any call in which x is of class "track". In the second case, the new methods list object defines the available methods depending on the remaining formal arguments, in this example, y.

Each method corresponds conceptually to a signature; that is a named list of classes, with names corresponding to some or all of the formal arguments. In the previous example, if selecting class "track" for x, finding that the selection was another methods list and then selecting class "numeric" for y would produce a method associated with the signature x = "track", y = "numeric".

You can see the methods arranged by signature by calling the function showMethods, A methods list can be converted into an ordinary list with the methods arranged this way (in two different forms) by calling the functions listFromMlist and linearizeMlist.

Slots

argument:
Object of class "name". The name of the argument being used for dispatch at this level.
methods:
A named list of the methods (and method lists) defined explicitly for this argument. The names are the names of classes, and the corresponding element defines the method or methods to be used if the corresponding argument has that class. See the details below.
allMethods:
A named list, contains all the directly defined methods from the methods slot, plus any inherited methods. Ignored when methods tables are used for dispatch (see Methods

Extends

Class "OptionalMethods", directly.


Additional (Support) Functions for Methods

Description

These are support routines for computations on formal methods.

Usage

getMethodsForDispatch(f, fdef)

cacheMethod(f, sig, def, args, fdef, inherited = FALSE)

resetGeneric(f, fdef, mlist, where, deflt)

Summary of Functions

resetGeneric:
reset the currently defined methods for this generic to the currently visible methods, looking from environment where. Returns TRUE or FALSE according to whether information for the function was found in the metadata.

Normally not called directly, since changes to methods, attaching and detaching packages all generate a call automatically.

cacheMethod:
Store the definition for this function and signature in the method metadata for the function. Used to store extensions of coerce methods found through inheritance, and to cache methods with callNextMethod information.

No persistent effect, since the method metadata is session-scope only.

getMethodsForDispatch:
Get the current methods list object representing the methods for function f, merged from the various packages and with any additional caching information stored in the allMethods slot.

If methods have not yet been merged, calling getMethodsForDispatch will cause the merge to take place.


Utility Functions for Methods and S-Plus Compatibility

Description

These are utilities, currently in the methods package, that either provide some functionality needed by the package (e.g., element matching by name), or add compatibility with S-Plus, or both.

Usage

functionBody(fun=sys.function(sys.parent()))

allNames(x)

getFunction(name, generic=TRUE, mustFind=TRUE, where)

el(object, where)

elNamed(x, name, mustFind=FALSE)

formalArgs(def)

Quote()

showDefault(object, oldMethods = TRUE)

initMethodDispatch(where = topenv(parent.frame()))

methodSignatureMatrix(object, sigSlots = c("target", "defined"))

Summary of Functions

allNames:
the character vector of names (unlike names(), never returns NULL).
getFunction:
find the object as a function.
elNamed:
get the element of the vector corresponding to name. Unlike the [, [[, and $ operators, this function requires name to match the element name exactly (no partial matching).
formalArgs:
Returns the names of the formal arguments of this function.
existsFunction:
Is there a function of this name? If generic is FALSE, generic functions are not counted.
findFunction:
return all the indices of the search list on which a function definition for name exists.

If generic is FALSE, ignore generic functions.

showDefault:
Utility, used to enable show methods to be called by the automatic printing (via print.default).

Argument oldMethods controls whether old-style print methods are used for this object. It is TRUE by default if called directly, but FALSE when called from the methods package for automatic printing (to avoid potential recursion).

initMethodDispatch:
Turn on the internal method dispatch code. Called on attaching the package. Also, if dispatch has been turned off (by calling .isMethodsDispatchOn(FALSE)—a very gutsy thing to do), calling this function should turn dispatch back on again.
methodSignatureMatrix:
Returns a matrix with the contents of the specified slots as rows. The slots should be named character strings of the same length. Basically used to turn the signatures of a "MethodDefinition" objectg into a matrix for printing.


Class MethodWithNext

Description

Class of method definitions set up for callNextMethod

Objects from the Class

Objects from this class are generated as a side-effect of calls to callNextMethod.

Slots

.Data:
Object of class "function"; the actual function definition.
nextMethod:
Object of class "PossibleMethod" the method to use in response to a callNextMethod() call.
excluded:
Object of class "list"; one or more signatures excluded in finding the next method.
target:
Object of class "signature", from class "MethodDefinition"
defined:
Object of class "signature", from class "MethodDefinition"
generic:
Object of class "character"; the function for which the method was created.

Extends

Class "MethodDefinition", directly.
Class "function", from data part.
Class "PossibleMethod", by class "MethodDefinition".
Class "OptionalMethods", by class "MethodDefinition".

Methods

findNextMethod
signature(method = "MethodWithNext"): used internally by method dispatch.
loadMethod
signature(method = "MethodWithNext"): used internally by method dispatch.
show
signature(object = "MethodWithNext")

See Also

callNextMethod, and MethodDefinition-class.


Generate an Object from a Class

Description

Given the name or the definition of a class, plus optionally data to be included in the object, new returns an object from that class.

Usage

new(Class, ...)

initialize(.Object, ...)

Arguments

Class | Either the name of a class (the usual case) or the object describing the class (e.g., the value returned by getClass).
... | Data to include in the new object. Named arguments correspond to slots in the class definition. Unnamed arguments must be objects from classes that this class extends.
.Object | An object: see the Details section.

Details

The function new begins by copying the prototype object from the class definition. Then information is inserted according to the ... arguments, if any. As of version 2.4 of R, the type of the prototype object, and therefore of all objects returned by new(), is "S4" except for classes that extend one of the basic types, where the prototype has that basic type. User functions that depend on typeof(object) should be careful to handle "S4" as a possible type.

The interpretation of the ... arguments can be specialized to particular classes, if an appropriate method has been defined for the generic function "initialize". The new function calls initialize with the object generated from the prototype as the .Object argument to initialize.

By default, unnamed arguments in the ... are interpreted as objects from a superclass, and named arguments are interpreted as objects to be assigned into the correspondingly named slots. Thus, explicit slots override inherited information for the same slot, regardless of the order in which the arguments appear.

The initialize methods do not have to have ... as their second argument (see the examples), and generally it is better design not to have ... as a formal argument, if only a fixed set of arguments make sense.

For examples of initialize methods, see initialize-methods for existing methods for classes "traceable" and "environment", among others.

Note that the basic vector classes, "numeric", etc. are implicitly defined, so one can use new for these classes.

References

The functions in this package emulate the facility for classes and methods described in Programming with Data (John M. Chambers, Springer, 1998). See this book for further details and examples.

See Also

Classes

Examples

## using the definition of class "track" from Classes

## a new object with two slots specified
t1 <- new("track", x = seq(along=ydata), y = ydata)

# a new object including an object from a superclass, plus a slot
t2 <- new("trackCurve", t1, smooth = ysmooth)

### define a method for initialize, to ensure that new objects have
### equal-length x and y slots.

setMethod("initialize",
          "track",
          function(.Object, x = numeric(0), y = numeric(0)) {
            if(nargs() > 1) {
              if(length(x) != length(y))
                stop("specified x and y of different lengths")
              .Object@x <- x
              .Object@y <- y
            }
            .Object
          })

### the next example will cause an error (x will be numeric(0)),
### because we didn't build in defaults for x,
### although we could with a more elaborate method for initialize

try(new("track", y = sort(rnorm(10))))

## a better way to implement the previous initialize method.
## Why?  By using callNextMethod to call the default initialize method
## we don't inhibit classes that extend "track" from using the general
## form of the new() function.  In the previous version, they could only
## use x and y as arguments to new, unless they wrote their own
## intialize method.

setMethod("initialize", "track", function(.Object, ...) {
    .Object <- callNextMethod()
    if(length(.Object@x) != length(.Object@y))
     stop("specified x and y of different lengths")
    .Object
  })


Call an Inherited Method

Description

A call to callNextMethod can only appear inside a method definition. It then results in a call to the first inherited method after the current method, with the arguments to the current method passed down to the next method. The value of that method call is the value of callNextMethod.

Usage

callNextMethod(...)

Arguments

... Optionally, the arguments to the function in its next call (but note that the dispatch is as in the detailed description below; the arguments have no effect on selecting the next method.)
If no arguments are included in the call to callNextMethod, the effect is to call the method with the current arguments. See the detailed description for what this really means.
Calling with no arguments is often the natural way to use callNextMethod; see the examples.

Details

The “next” method (i.e., the first inherited method) is defined to be that method which would have been called if the current method did not exist. This is more-or-less literally what happens: The current method (to be precise, the method with signature given by the defined slot of the method from which callNextMethod is called) is deleted from a copy of the methods for the current generic, and selectMethod is called to find the next method (the result is cached in a special object, so the search only typically happens once per session per combination of argument classes).

Note that the preceding definition means that the next method is defined uniquely when setMethod inserts the method containing the callNextMethod call, given the definitions of the classes in the signature. The choice does not depend on the path that gets us to that method (for example, through inheritance or from another callNextMethod call). This definition was not enforced in versions of R prior to 2.3.0, where the method was selected based on the target signature, and so could vary depending on the actual arguments.

It is also legal, and often useful, for the method called by callNextMethod to itself have a call to callNextMethod. This generally works as you would expect, but for completeness be aware that it is possible to have ambiguous inheritance in the S structure, in the sense that the same two classes can appear as superclasses in the opposite order in two other class definitions. In this case the effect of a nested instance of callNextMethod is not well defined. Such inconsistent class hierarchies are both rare and nearly always the result of bad design, but they are possible, and currently undetected.

The statement that the method is called with the current arguments is more precisely as follows. Arguments that were missing in the current call are still missing (remember that "missing" is a valid class in a method signature). For a formal argument, say x, that appears in the original call, there is a corresponding argument in the next method call equivalent to “x = x”. In effect, this means that the next method sees the same actual arguments, but arguments are evaluated only once.

Value

The value returned by the selected method.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

Methods for the general behavior of method dispatch

Examples

## some class definitions with simple inheritance
setClass("B0" , representation(b0 = "numeric"))

setClass("B1", representation(b1 = "character"), contains = "B0")

setClass("B2", representation(b2 = "logical"), contains = "B1")

## and a rather silly function to illustrate callNextMethod

f <- function(x) class(x)

setMethod("f", "B0", function(x) c(x@b0^2, callNextMethod()))
setMethod("f", "B1", function(x) c(paste(x@b1,":"), callNextMethod()))
setMethod("f", "B2", function(x) c(x@b2, callNextMethod()))

b1 <- new("B1", b0 = 2, b1 = "Testing")

b2 <- new("B2", b2 = FALSE, b1 = "More testing", b0 = 10)

f(b2)

f(b1)


A Vector of Object Names, with associated Package Names

ObjectsWithPackage-class(methods) R Documentation

A Vector of Object Names with associated Package Names

Description

This class of objects is used to represent ordinary character string object names, extended with a package slot naming the package associated with each object.

Objects from the Class

The function getGenerics returns an object of this class.

Slots

.Data:
Object of class "character": the object names.
package:
Object of class "character" the package names.

Extends

Class "character", from data part.
Class "vector", by class "character".

See Also

Methods for general background.


Old functions to access slots in a class definition

Description

Expect these functions to become deprecated in the near future.

They do nothing but access a slot in a class definition, and don't even do this consistently with the right name (they date back to the early implementation of the methods package). Higher-level functions for the useful operations (e.g., extends for getExtends) should be used instead.

Usage

getAccess(ClassDef)

getClassName(ClassDef)

getClassPackage(ClassDef)

getExtends(ClassDef)

getProperties(ClassDef)

getPrototype(ClassDef)

getSubclasses(ClassDef)

getValidity(ClassDef)

getVirtual(ClassDef)

Arguments

ClassDef the class definition object

Details

The functions should be replaced by direct access to the slots, or by use of higher-level alternatives.

The functions and corresponding slots are:
getAccess | "access"
getClassName | "className"
getClassPackage | "package"
getExtends | "contains"
getProperties | "slots"
getPrototype | "prototype"
getSubclasses | "subclasses"
getValidity | "validity"
getVirtual | "virtual"

See Also

classRepresentation-class


Generate a Shell for Documentation of a Formal Class

Description

Assembles all relevant slot and method information for a class, with minimal markup for Rd processing; no QC facilities at present.

Usage

promptClass(clName, filename = NULL, type = "class",
            keywords = "classes", where = topenv(parent.frame()))

Arguments

clName | a character string naming the class to be documented.
filename | usually, a connection or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is the topic name for the class documentation, followed by ".Rd". Can also be NA (see below).
type | the documentation type to be declared in the output file.
keywords | the keywords to include in the shell of the documentation. The keyword "classes" should be one of them.
where | where to look for the definition of the class and of methods that use it.

Details

The class definition is found on the search list. Using that definition, information about classes extended and slots is determined.

In addition, the currently available generics with methods for this class are found (using getGenerics). Note that these methods need not be in the same environment as the class definition; in particular, this part of the output may depend on which packages are currently in the search list.

As with other prompt-style functions, unless filename is NA, the documentation shell is written to a file, and a message about this is given. The file will need editing to give information about the meaning of the class. The output of promptClass can only contain information from the metadata about the formal definition and how it is used.

If filename is NA, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to cat(unlist(x), file = filename, sep = "\n"), where x is the list-style representation.

Value

If filename is NA, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly.

Author(s)

VJ Carey stvjc@channing.harvard.edu and John Chambers

References

The functions in this package emulate the facility for classes and methods described in Programming with Data (John M. Chambers, Springer, 1998). See this book for further details and examples.

See Also

prompt for documentation of functions, promptMethods for documentation of method definitions.

For processing of the edited documentation, either use R CMD Rdconv, or include the edited file in the ‘man’ subdirectory of a package.

Examples

## Not run:
> promptClass("track")
A shell of class documentation has been written to the
file "track-class.Rd".
## End(Not run)


Generate a Shell for Documentation of Formal Methods

Description

Generates a shell of documentation for the methods of a generic function.

Usage

promptMethods(f, filename = NULL, methods)

Arguments

f | a character string naming the generic function whose methods are to be documented.
filename | usually, a connection or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to the coded topic name for these methods (currently, f followed by "-methods.Rd"). Can also be FALSE or NA (see below).
methods | Optional methods list object giving the methods to be documented. By default, the first methods object for this generic is used (for example, if the current global environment has some methods for f, these would be documented). If this argument is supplied, it is likely to be getMethods(f, where), with where some package containing methods for f.

Details

If filename is FALSE, the text created is returned, presumably to be inserted some other documentation file, such as the documentation of the generic function itself (see prompt).

If filename is NA, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to cat(unlist(x), file = filename, sep = "\n"), where x is the list-style representation.

Otherwise, the documentation shell is written to the file specified by filename.

Value

If filename is FALSE, the text generated; if filename is NA, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

prompt and promptClass


Utilities for Managing Class Definitions

Description

These are various functions to support the definition and use of formal classes. Most of them are rarely suitable to be called directly.

Others are somewhat experimental and/or partially implemented only. Do refer to setClass for normal code development.

Usage

testVirtual(properties, extends, prototype, where)

makePrototypeFromClassDef(slots, ClassDef, extends, where)

newEmptyObject()

completeClassDefinition(Class, ClassDef, where, doExtends)

getSlots(x)

getAllSuperClasses(ClassDef, simpleOnly = TRUE)

superClassDepth(ClassDef, soFar, simpleOnly = TRUE)

isVirtualClass(Class, where)

newBasic(Class, ...)

makeExtends(Class, to, coerce, test, replace, by, package, slots,
                 classDef1, classDef2)

reconcilePropertiesAndPrototype(name, properties, prototype,
       superClasses, where)

tryNew(Class, where)

trySilent(expr)

empty.dump()

showClass(Class, complete=TRUE, propertiesAreCalled="Slots")

showExtends(ext, printTo = stdout())

possibleExtends(class1, class2, ClassDef1 = getClassDef(class1),
                 ClassDef2 = getClassDef(class2, where =
                 .classEnv(ClassDef1)))

completeExtends(ClassDef, class2, extensionDef, where)

classMetaName(name)

methodsPackageMetaName(prefix, name)

metaNameUndo(strings, prefix = "M", searchForm = FALSE)

requireMethods(functions, signature, message, where)

checkSlotAssignment(obj, name, value)

defaultPrototype()

isClassDef(object)

validSlotNames(names)

getDataPart(object)
setDataPart(object, value)

Summary of Functions

testVirtual:
Test for a Virtual Class. Figures out, as well as possible, whether the class with these properties, extension, and prototype is a virtual class. Can be forced to be virtual by extending "VIRTUAL".

Otherwise, a class is virtual only if it has no slots, extends no non-virtual classes, and has a NULL Prototype.

makePrototypeFromClassDef:
Makes the prototype implied by the class definition.

The following three rules are applied in this order.

  1. If the class has slots, then the prototype for each slot is used by default, but a corresponding element in the explicitly supplied prototype in ClassDef, if there is one, is used instead (but it must be coercible to the class of the slot). This includes the data part (".Data" slot) if there is one.
  2. If there are no slots but a non-null prototype was specified, this is returned.
  3. If there is a non-virtual superclass (a class in the extends list), then its prototype is used. The data part is extracted if needed (it is allowed to have two superclasses with a data part; the first is used and a warning issued on any others).

If all three of the above fail, the prototype is NULL.

newEmptyObject:
Utility function to create an empty object into which slots can be set.

Currently just creates an empty list with class "NULL".

Later version should create a special object reference that marks an object currently with no slots and no data.

completeClassDefinition:
Completes the definition of Class, relative to the class definitions visible from environment where. If doExtends is TRUE, complete the super- and sub-class information.

This function is called when a class is defined or re-defined.

getFromClassDef:
Extracts one of the intrinsically defined class definition properties (".Properties", etc.) Strictly a utility function.
getSlots:
Returns a named character vector. The names are the names of the slots, the values are the classes of the corresponding slots. The argument x can either be the name of a class or the class definition object.
getAllSuperClasses, superClassDepth:
Get the names of all the classes that this class definition extends.

getAllSuperClasses is a utility function used to complete a class definition. It returns all the superclasses reachable from this class, in breadth-first order (which is the order used for matching methods); that is, the first direct superclass followed by all its superclasses, then the next, etc. (The order is relevant only in the case that some of the superclasses have multiple inheritance.)

superClassDepth, which is called from getAllSuperClasses, returns the same information, but as a list with components label and depth, the latter for the number of generations back each class is in the inheritance tree. The argument soFar is used to avoid loops in the network of class relationships.

isVirtualClass:
Is the named class a virtual class?

A class is virtual if explicitly declared to be, and also if the class is not formally defined.

assignClassDef:
assign the definition of the class to the specially named object
newBasic:
the implementation of the function new for basic classes that don't have a formal definition.

Any of these could have a formal definition, except for Class="NULL" (disallowed because NULL can't have attributes). For all cases except "NULL", the class of the result will be set to Class.

See new for the interpretation of the arguments.

makeExtends:
convert the argument to a list defining the extension mechanism.
reconcilePropertiesAndPrototype:
makes a list or a structure look like a prototype for the given class.

Specifically, returns a structure with attributes corresponding to the slot names in properties and values taken from prototype if they exist there, from new(classi) for the class, classi of the slot if that succeeds, and NULL otherwise.

The prototype may imply slots not in the properties list, since properties does not include inherited slots (these are left unresolved until the class is used in a session).

tryNew:
Tries to generate a new element from this class, but if the attempt fails (as, e.g., when the class is undefined or virtual) just returns NULL.

This is inefficient and also not a good idea when actually generating objects, but is useful in the initial definition of classes.

showClass:
Print the information about a class definition.

If complete is TRUE, include the indirect information about extensions.

showExtends:
Print the elements of the list of extensions; for printTo = FALSE, returns a list with components what and how; this is used e.g., by promptClass().
possibleExtends:
Find the information that says whether class1 extends class2, directly or indirectly.

This can be either a logical value or an object of class SClassExtension-class containing various functions to test and/or coerce the relationship.

completeExtends:
complete the extends information in the class definition, by following transitive chains.

If class2 and extensionDef are included, this class relation is to be added. Otherwise just use the current ClassDef.

Both the contains and subclasses slots are completed with any indirect relations visible.

classMetaName:
a name for the object storing this class's definition
methodsPackageMetaName:
a name mangling device to hide metadata defining method and class information.
metaNameUndo
As its name implies, this function undoes the name-mangling used to produce meta-data object names, and returns a object of class ObjectsWithPackage-class.
requireMethods:
Require a subclass to implement methods for the generic functions, for this signature.

For each generic, setMethod will be called to define a method that throws an error, with the supplied message.

The requireMethods function allows virtual classes to require actual classes that extend them to implement methods for certain functions, in effect creating an API for the virtual class.

Otherwise, default methods for the corresponding function would be called, resulting in less helpful error messages or (worse still) silently incorrect results.

checkSlotAssignment:
Check that the value provided is allowed for this slot, by consulting the definition of the class. Called from the C code that assigns slots.

For privileged slots (those that can only be set by accesor functions defined along with the class itself), the class designer may choose to improve efficiency by validating the value to be assigned in the accessor function and then calling slot<- with the argument check=FALSE, to prevent the call to checkSlotAssignment.

defaultPrototype:
The prototype for a class which will have slots, is not a virtual class, and does not extend one of the basic classes. In future releases, this will likely be a non-vector R object type, but none of the current types (as of release 1.4) is suitable.
.InitBasicClasses, .InitMethodsListClass, .setCoerceGeneric:
These functions perform part of the initialization of classes and methods, and are called (only!) from .First.lib.
isClassDef:
Is object a representation of a class?
validSlotNames:
Returns names unless one of the names is reserved, in which case there is an error. (As of writing, "class" is the only reserved slot name.)
getDataPart, setDataPart:
Utilities called from the base C code to implement object@.Data.


Construct a Representation or a Prototype for a Class Definition

Description

In calls to setClass, these two functions construct, respectively, the representation and prototype arguments. They do various checks and handle special cases. You're encouraged to use them when defining classes that, for example, extend other classes as a data part or have multiple superclasses, or that combine extending a class and slots.

Usage

representation(...)
prototype(...)

Arguments

... The call to representation takes arguments that are single character strings. Unnamed arguments are classes that a newly defined class extends; named arguments name the explicit slots in the new class, and specify what class each slot should have.
In the call to prototype, if an unnamed argument is supplied, it unconditionally forms the basis for the prototype object. Remaining arguments are taken to correspond to slots of this object. It is an error to supply more than one unnamed argument.

Details

The representation function applies tests for the validity of the arguments. Each must specify the name of a class.

The classes named don't have to exist when representation is called, but if they do, then the function will check for any duplicate slot names introduced by each of the inherited classes.

The arguments to prototype are usually named initial values for slots, plus an optional first argument that gives the object itself. The unnamed argument is typically useful if there is a data part to the definition (see the examples below).

Value

The value pf representation is just the list of arguments, after these have been checked for validity.
The value of prototype is the object to be used as the prototype. Slots will have been set consistently with the arguments, but the construction does not use the class definition to test validity of the contents (it hardly can, since the prototype object is usually supplied to create the definition).

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

setClass

Examples

## representation for a new class with a directly define slot "smooth"
## which should be a "numeric" object, and extending class "track"
representation("track", smooth ="numeric")

setClass("Character",representation("character"))
setClass("TypedCharacter",representation("Character",type="character"),
          prototype(character(0),type="plain"))
ttt <- new("TypedCharacter", "foo", type = "character")

setClass("num1", representation(comment = "character"),
         contains = "numeric",
         prototype = prototype(pi, comment = "Start with pi"))


RMethodUtils

Description

Utility functions to support the definition and use of formal methods. Most of these functions will not normally be called directly by the user.

Usage

getGeneric(f, mustFind=FALSE, where, package)

getGroup(fdef, recursive, where)
getGroupMembers(group, recursive = FALSE, character = TRUE)

getMethodsMetaData(f, where)
assignMethodsMetaData (f, value, fdef, where, deflt)
mlistMetaName (name, package)

makeGeneric(f, fdef, fdefault, group=list(), valueClass=character(),
            package, signature = NULL, genericFunction = NULL)

makeStandardGeneric(f, fdef)

generic.skeleton(name, fdef, fdefault)

defaultDumpName(generic, signature)

getAllMethods(f, fdef, where)

doPrimitiveMethod(name, def, call= sys.call(sys.parent()),
                  ev = sys.frame(sys.parent(2)))

conformMethod(signature, mnames, fnames, f)

matchSignature(signature, fun, where)

removeMethodsObject(f, where)

findUnique(what, message, where)

MethodAddCoerce(method, argName, thisClass, methodClass)

cacheMetaData(where, attach = TRUE, searchWhere)

cacheGenericsMetaData(f, fdef, attach = TRUE, where, package, methods)

setPrimitiveMethods(f, fdef, code, generic, mlist)

missingArg(symbol, envir = parent.frame(), eval)

balanceMethodsList(mlist, args, check = TRUE)

sigToEnv(signature, generic)

rematchDefinition(definition, generic, mnames, fnames, signature)
unRematchDefinition(definition)

asMethodDefinition(def, signature, sealed = FALSE)

addNextMethod(method, f, mlist, optional, envir)

Summary of Functions

getGeneric:
returns the definition of the function named f as a generic.

If no definition is found, throws an error or returns NULL according to the value of mustFind. By default, searches in the top-level environment (normally the global environment, but adjusted to work correctly when package code is evaluated from the function library).

Primitive functions are dealt with specially, since there is never a formal generic definition for them. The value returned is the formal definition used for assigning methods to this primitive. Not all primitives can have methods; if this one can't, then getGeneric returns NULL or throws an error.

getGroup:
returns the groups to which this generic belongs, searching from environment where (the global environment normally by default).

If recursive=TRUE, also all the group(s) of these groups.

getGroupMembers:
Return all the members of the group generic function named group. If recursive is TRUE, and some members are group generics, includes their members as well. If character is TRUE, returns just a character vector of the names; otherwise returns a list, whose elements may (or may not) include either names with a package attribute or actual generic functions.

Note that members that are not defined as generic functions will not be included in the returned value. To see the raw data, use getGeneric(group)@groupMembers.

getMethodsMetaData, assignMethodsMetaData, mlistMetaName:
Utilities to get (getMethodsMetaData) and assign (assignMethodsMetaData) the metadata object recording the methods defined in a particular package, or to return the mangled name for that object (mlistMetaName).

The assign function should not be used directly. The get function may be useful if you want explicitly only the outcome of the methods assigned in this package. Otherwise, use getMethods.

matchSignature:
Matches the signature object (a partially or completely named subset of the signature arguments of the generic function object fun), and return a vector of all the classes in the order specified by fun@signature. The classes not specified by signature will be "ANY" in the value, but extra trailing "ANY"'s are removed. When the input signature is empty, the returned signature is a single "ANY" matching the first formal argument (so the returned value is always non-empty).

Generates an error if any of the supplied signature names are not legal; that is, not in the signature slot of the generic function.

If argument where is supplied, a warning will be issued if any of the classes does not have a formal definition visible from where.

MethodAddCoerce:
Possibly modify one or more methods to explicitly coerce this argument to methodClass, the class for which the method is explicitly defined. Only modifies the method if an explicit coerce is required to coerce from thisClass to methodClass.
removeMethodsObject:
remove the metadata object containing methods for f.
findUnique:
Return the list of environments (or equivalent) having an object named what, using environment where and its parent environments. If more than one is found, a warning message is generated, using message to identify what was being searched for, unless message is the empty string.
cacheMetaData, cacheGenericsMetaData, setPrimitiveMethods:
Utilities for ensuring that the internal information about class and method definitions is up to date. Should normally be called automatically whenever needed (for example, when a method or class definition changes, or when a package is attached or detached). Required primarily because primitive functions are dispatched in C code, rather than by the official model.

The setPrimitiveMethods function resets the caching information for a particular primitive function. Don't call it directly.

missingArg:
Returns TRUE if the symbol supplied is missing from the call corresponding to the environment supplied (by default, environment of the call to missingArg). If eval is true, the argument is evaluated to get the name of the symbol to test. Note that missingArg is closer to the “blue-book” sense of the missing function, not that of the current R base package implementation. But beware that it works reliably only if no assignment has yet been made to the argument. (For method dispatch this is fine, because computations are done at the begining of the call.)
balanceMethodsList:
Called from setMethod to ensure that all nodes in the list have the same depth (i.e., the same number of levels of arguments). Balance is needed to ensure that all necessary arguments are examined when inherited methods are being found and added to the allMethods slot. No actual recomputation is needed usually except when a new method uses a longer signature than has appeared before.

Balance requires that all methods be added to the generic via setMethod (how else could you do it?) or by the initial setGeneric call converting the ordinary function.

sigToEnv:
Turn the signature (a named vector of classes) into an environment with the classes assigned to the names. The environment is then suitable for calling MethodsListSelect, with evalArgs=FALSE, to select a method corresponding to the signature. Usually not called directly: see selectMethod.
.saveImage:
Flag, used in dynamically initializing the methods package from .First.lib
rematchDefinition, unRematchDefinition:
If the specified method in a call to setMethod specializes the argument list (by replacing ...), then rematchDefinition constructs the actual method stored. Using knowledge of how rematchDefinition works, unRematchDefinition reverses the procedure; if given a function or method definition that does not correspond to this form, it just returns its argument.
asMethodDefinition:
Turn a function definition into a MethodDefinition-class object, corresponding to the given signature (by default generates a default method with empty signature). The definition is sealed according to the sealed argument.
addNextMethod:
A generic function that finds the next method in mlist corresponding the method definition method and adds the method to the methods list, which it then returns. It uses methods defined suitably for ordinary methods and for methods with calls to callNextMethod.
makeGeneric:
Makes a generic function object corresponding to the given function name, optional definition and optional default method. Other arguments supply optional elements for the slots of genericFunction-class.
makeStandardGeneric:
a utility function that makes a valid function calling standardGeneric for name f. Works (more or less) even if the actual definition, fdef, is not a proper function, that is, it's a primitive or internal.
conformMethod:
If the formal arguments, mnames, are not identical to the formal arguments to the function, fnames, conformMethod determines whether the signature and the two sets of arguments conform, and returns the signature, possibly extended. The function name, f is supplied for error messages.

The method assignment conforms if either method and function have identical formal argument lists. It can also conform if the method omits some of the formal arguments of the function but: (1) the non-omitted arguments are a subset of the function arguments, appearing in the same order; (2) there are no arguments to the method that are not arguments to the function; and (3) the omitted formal arguments do not appear as explicit classes in the signature.

defaultDumpName:
the default name to be used for dumping a method.
getAllMethods:
A generic function (with methods) representing the merge of all the methods defined for this generic starting from environment where, including all parent environments. By default, uses the global environment (and therefore all packages on the search list). This function exists largely to re-compute the full set of methods when a change to the available methods occurs. Since all such recomputations are supposed to be automatic, direct calls to getAllMethods should not be needed.

If the generic f has a group generic, methods for this group generic (and further generations of group generics, if any) are also merged.

The merging rule is as follows: each generic is merged across packages, and the group generics are then merged, finally adding the directly defined methods of f.

The effect of the merging rule is that any method directly defined for f on any included package overrides a method for the same signature defined for the group generic; similarly for the group generic and its group, if any, etc.

For f or for a specific group generic, methods override in the order of the packages being searched. A method for a particular signature on a particular package overrides any methods for the same signature on packages later on in the list of packages being searched.

The slot "allMethods" of the merged methods list is set to a copy of the methods slot; this is the slot where inherited methods are stored.

doPrimitiveMethod:
do a primitive call to builtin function name the definition and call provided, and carried out in the environment ev.

A call to doPrimitiveMethod is used when the actual method is a .Primitive. (Because primitives don't behave correctly as ordinary functions, not having either formal arguments nor a function body).

See Also

setGeneric, setClass, showMethods.

Examples

getGroup("exp")
getGroup("==", recursive = TRUE)

getGroupMembers("Arith")
getGroupMembers("Math")
getGroupMembers("Ops") # -> its sub groups


S4 Group Generic Functions

Description

Methods can be defined for groups of functions known as group generic functions. These exist in both S3 (see S3groupGeneric) and S4 flavours, with different groups.

Methods are defined for the group of functions as a whole. A method defined for an individual member of the group takes precedence over a method defined for the group as a whole.

When package methods is attached there are objects visible with the names of the group generics: these functions should never be called directly (a suitable error message will result if they are).

Usage

## S4 group generics:
Arith(e1, e2)
Compare(e1, e2)
Ops(e1, e2)
Logic(e1, e2)
Math(x)
Math2(x, digits)
Summary(x, ..., na.rm = FALSE)
Complex(z)

Arguments

x, z, e1, e2 | objects.
digits | number of digits to be used in round or signif.
... | further arguments passed to or from methods.
na.rm | logical: should missing values be removed?

Details

When package methods is attached (which it is by default), formal (S4) methods can be defined for the group generic functions (which are R objects which should never be called directly – a suitable error message will result if they are). There are also S3 groups Math, Ops, Summary and Complex, see ?S3groupGeneric, with no corresponding R objects.

The functions belonging to the various groups are as follows:

Arith
"+", "-", "*", "^", "%%", "%/%", "/"
Compare
"==", ">", "<", "!=", "<=", ">="
Logic
"&", "|", but not "!" since that has only one argument. Note that this is contrary to Chambers(1998), on purpose.
Ops
"Arith", "Compare", "Logic"
Math
"log", "sqrt", "log10", "cumprod", "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "ceiling", "cos", "cosh", "cumsum", "exp", "floor", "gamma", "lgamma", "sin", "sinh", "tan", "tanh", "trunc"
Math2
"round", "signif"
Summary
"max", "min", "range", "prod", "sum", "any", "all"
Complex
"Arg", "Conj", "Im", "Mod", "Re"

Note that "Ops" merely consists of three sub groups. Functions with the group names exist in the methods package but should not be called directly.

All the functions in these groups (other than the group generics themselves) are basic functions in R. They are not by default S4 generic functions, and many of them are defined as primitives, meaning that they do not have formal arguments. However, you can still define formal methods for them. The effect of doing so is to create an S4 generic function with the appropriate arguments, in the environment where the method definition is to be stored. It all works more or less as you might expect, admittedly via a bit of trickery in the background.

Note: currently those members which are not primitive functions must have been converted to S4 generic functions (preferably before setting an S4 group generic method) as it only sets methods for known S4 generics. This can be done by a call to setGeneric, for example setGeneric("round", group="Math2").

References

Appendix A, Classes and Methods of
Chambers, J. M. and Hastie, T. J. eds (1992) Statistical Models in S. Wadsworth & Brooks/Cole.

Chambers, J. M. (1998) Programming with Data. Springer, pp. 352–4.

See Also

S3groupGeneric for S3 group generics.

Examples

setClass("testComplex", representation(zz = "complex"))
## method for whole group "Complex"
setMethod("Complex", "testComplex",
          function(z) c("groupMethod", callGeneric(z@zz)))
## exception for Arg() :
setMethod("Arg", "testComplex",
          function(z) c("ArgMethod", Arg(z@zz)))
z1 <- 1+2i
z2 <- new("testComplex", zz = z1)
stopifnot(identical(Mod(z2), c("groupMethod", Mod(z1))))
stopifnot(identical(Arg(z2), c("ArgMethod", Arg(z1))))


Class to Represent Inheritance (Extension) Relations

Description

An object from this class represents a single “is” relationship; lists of these objects are used to represent all the extensions (superclasses) and subclasses for a given class. The object contains information about how the relation is defined and methods to coerce, test, and replace correspondingly.

Objects from the Class

Objects from this class are generated by setIs, from direct calls and from the contains= information in a call to setClass, and from class unions created by setClassUnion. In the last case, the information is stored in defining the subclasses of the union class (allowing unions to contain sealed classes).

Slots

subClass,superClass:
The classes being extended: corresponding to the from, and to arguments to setIs.
package:
The package to which that class belongs.
coerce:
A function to carry out the as() computation implied by the relation. Note that these functions should not be used directly. They only deal with the strict=TRUE calls to the as function, with the full method constructed from this mechanically.
test:
The function that would test whether the relation holds. Except for explicitly specified test arguments to setIs, this function is trivial.
replace:
The method used to implement as(x, Class) <- value.
simple:
A "logical" flag, TRUE if this is a simple relation, either because one class is contained in the definition of another, or because a class has been explicitly stated to extend a virtual class. For simple extensions, the three methods are generated automatically.
by:
If this relation has been constructed transitively, the first intermediate class from the subclass.
dataPart:
A "logical" flag, TRUE if the extended class is in fact the data part of the subclass. In this case the extended class is a basic class (i.e., a type).
distance:
The distance between the two classes, 1 for directly contained classes, plus the number of generations between otherwise.

Methods

No methods defined with class "SClassExtension" in the signature.

See Also

is, as, and classRepresentation-class.


Heuristic test for an object from an S4 class

Description

Returns TRUE if object has been generated from a formally defined (“S4”) class. DEPRECATED: use isS4(object) instead.

Usage

seemsS4Object(object)

Arguments

object Any object.

Details

The class of the object is examined for the "package" attribute included when objects are generated from an S4 class. The test in this function has been superseded by an internal bit set when S4 objects are generated.

The seemsS4Object function is deprecated and will be removed.

The test can be fooled in at least two ways:

  1. It will give TRUE incorrectly if someone puts a "package" string attribute on the class of an S3 object. Presumably unlikely.
  2. It will give FALSE incorrectly for class definitions and certain other objects for packages that have not been INSTALLed since the seemsS4Object was added to R. See the Warning below.

Value

Always TRUE or FALSE for any object.

Warnings

One motivation for this function is to prevent standard S3 vector operations from being applied to S4 objects that are not vectors. Note that seemsS4Object() alone is not that test. One also needs to check that the object does not inherit from class "vector". See the examples.

The existence of a class definition for the object's class is also not equivalent. S4 class definitions are recorded for S3 classes registered via setOldClass, but registering does not change the class of such objects, so they are not judged to be S4 objects (and should not be).

Certain other S4 objects used to be generated without the "package" attribute in earlier builds of R, notably class definitions. Packages using S4 objects must be reinstalled with a version of R recent enough to contain the seemsS4Object function (e.g., R 2.3.0 or later).

Examples

seemsS4Object(1) # FALSE

seemsS4Object(getClass(class(1)))  #TRUE

## how to test for an S4 object that is not a vector

S4NotVector <- function(object) seemsS4Object(object) && !is(object, "vector")

setClass("classNotNumeric", representation(x="numeric", y="numeric"))

setClass("classWithNumeric", representation(y="numeric"), contains = "numeric")

obj1 <- new("classNotNumeric", x=1, y=2)

obj2 <- new("classWithNumeric", 1, y=2)

seemsS4Object(obj1); seemsS4Object(obj2)  # TRUE, TRUE
S4NotVector(obj1); S4NotVector(obj2)  # TRUE, FALSE


Deprecated: Session Data and Debugging Tools

Description

The functions traceOn and traceOff have been replaced by extended versions of the functions trace and untrace, and should not be used.

Usage

sessionData()

traceOn(what, tracer=browseAll, exit=NULL)

traceOff(what)

browseAll()

Details

sessionData:
return the index of the session data in the search list, attaching it if it is not attached.
traceOn:
initialize tracing on calls to function what. The function or expression tracer is called on entry, and the function or expression exit on exit.
traceOff:
turn off tracing of this function.
browseAll:
browse the current stack of function calls.

Uses the function debugger to set up browser calls on the frames. On exit from that function, computation continues after the call to browseAll. Computations done in the frames will have no effect.

References

See Programming with Data (John M. Chambers, Springer, 1998) for the equivalent functions.


Create a Class Definition

Description

Functions to create (setClass) and manipulate class definitions.

Usage

setClass(Class, representation, prototype, contains=character(),
         validity, access, where, version, sealed, package)

removeClass(Class, where)

isClass(Class, formal=TRUE, where)

getClasses(where, inherits = missing(where))

findClass(Class, where, unique = "")

resetClass(Class, classDef, where)

sealClass(Class, where)

Arguments

Class | character string name for the class. Other than setClass, the functions will usually take a class definition instead of the string (allowing the caller to identify the class uniquely).
representation | the slots that the new class should have and/or other classes that this class extends. Usually a call to the representation function.
prototype | an object (usually a list) providing the default data for the slots specified in the representation.
contains | what classes does this class extend? (These are called superclasses in some languages.) When these classes have slots, all their slots will be contained in the new class as well.
where | For setClass and removeClass, the environment in which to store or remove the definition. Defaults to the top-level environment of the calling function (the global environment for ordinary computations, but the environment or namespace of a package when loading that package). For other functions, where defines where to do the search for the class definition, and the default is to search from the top-level environment or namespace of the caller to this function.
unique | if findClass expects a unique location for the class, unique is a character string explaining the purpose of the search (and is used in warning and error messages). By default, multiple locations are possible and the function always returns a list.
inherits | in a call to getClasses, should the value returned include all parent environments of where, or that environment only? Defaults to TRUE if where is omitted, and to FALSE otherwise.
validity | if supplied, should be a validity-checking method for objects from this class (a function that returns TRUE if its argument is a valid object of this class and one or more strings describing the failures otherwise). See validObject for details.
access | Access list for the class. Saved in the definition, but not currently used.
version | A version indicator for this definition. Saved in the definition, but not currently used.
sealed | If TRUE, the class definition will be sealed, so that another call to setClass will fail on this class name.
package | An optional package name for the class. By default (and usually) the package where the class definition is assigned will be used.
formal | Should a formal definition be required?
classDef | For removeClass, the optional class definition (but usually it's better for Class to be the class definition, and to omit classDef).

Details

These are the functions that create and manipulate formal class definitions. Brief documentation is provided below. See the references for an introduction and for more details.

setClass:
Define Class to be an S-style class. The effect is to create an object, of class "classRepEnvironment", and store this (hidden) in the specified environment or database. Objects can be created from the class (e.g., by calling new), manipulated (e.g., by accessing the object's slots), and methods may be defined including the class name in the signature (see setMethod).
removeClass:
Remove the definition of this class, from the environment where if this argument is supplied; if not, removeClass will search for a definition, starting in the top-level environment of the call to removeClass, and remove the (first) definition found.
isClass:
Is this the name of a formally defined class? (Argument formal is for compatibility and is ignored.)
getClasses:
The names of all the classes formally defined on where. If called with no argument, all the classes visible from the calling function (if called from the top-level, all the classes in any of the environments on the search list). The inherits argument can be used to search a particular environment and all its parents, but usually the default setting is what you want.
findClass:
The list of environments or positions on the search list in which a class definition of Class is found. If where is supplied, this is an environment (or namespace) from which the search takes place; otherwise the top-level environment of the caller is used. If unique is supplied as a character string, findClass returns a single environment or position. By default, it always returns a list. The calling function should select, say, the first element as a position or environment for functions such as get.

If unique is supplied as a character string, findClass will warn if there is more than one definition visible (using the string to identify the purpose of the call), and will generate an error if no definition can be found.

resetClass:
Reset the internal definition of a class. Causes the complete definition of the class to be re-computed, from the representation and superclasses specified in the original call to setClass.

This function is called when aspects of the class definition are changed. You would need to call it explicitly if you changed the definition of a class that this class extends (but doing that in the middle of a session is living dangerously, since it may invalidate existing objects).

sealClass:
Seal the current definition of the specified class, to prevent further changes. It is possible to seal a class in the call to setClass, but sometimes further changes have to be made (e.g., by calls to setIs). If so, call sealClass after all the relevant changes have been made.

Inheritance and Prototypes

Defining new classes that inherit from (“extend”) other classes is a powerful technique, but has to be used carefully and not over-used. Otherwise, you will often get unintended results when you start to compute with objects from the new class.

As shown in the examples below, the simplest and safest form of inheritance is to start with an explicit class, with some slots, that does not extend anything else. It only does what we say it does.

Then extensions will add some new slots and new behavior.

Another variety of extension starts with one of the built-in data types, perhaps with the intension of modifying R's standard behavior for that class. In this case, the new class inherits the built-in data type as its “data” part. See the “numWithId” example below.

When such a class definition is printed, the data part shows up as a pseudo-slot named “.Data”.

S3 Classes

Earlier, informal classes of objects (usually referred to as “S3” classes) are used by many R functions. It's natural to consider including them as the class for a slot in a formal class, or even as a class to be extended by the new class. This isn't prohibited but there are some disadvantages, and if you do want to include S3 classes, they should be declared by including them in a call to setOldClass. Here are some considerations:

  • Using S3 classes somewhat defeats the purpose of defining a formal class: An important advantage to your users is that a formal class provides guarantees of what the object contains (minimally, the classes of the slots and therfore what data they contain; optionally, any other requirements imposed by a validity method).

    But there is no guarantee whatever about the data in an object from an S3 class. It's entirely up to the functions that create or modify such objects. If you want to provide guarantees to your users, you will need a valdity method that explicitly checks the contents of S3-class objects.

  • To get the minimal guarantee (that the object in a slot has, or extends, the class for the slot) you should ensure that the S3 classes are known to be S3 classes, with the possible inheritance. To do this, include a call to setOldClass for the S3 classes used.

    Otherwise, the S3 class is undefined (and the code used by setClass will issue a warning). Slot assignments, for example, will not then check for possible errors.

  • These caveats apply to S3 classes; that is, objects with a class assigned by some R function but without a formal class definition. In contrast, the built-in data types (numeric, list, etc.) are generally fine as slots or for contains= classes (see the previous section). These data types don't have formal slots, but the base code in the system essentially forces them to contain the type of data they claim to have.

    The data types matrix and array are somewhat in between. They do not have an explicit S3 class, but do have one or two attributes. There is no general problem in having these as slots, but because there is no guarantee of a dimnames slot, they don't work as formal classes. The ts class is treated as a formal class, extending class vector.

Note

Certain slot names are not allowed in the current implementation, as they correspond to attributes which are treated specially. These are class, comment, dim, dimnames, names, (from R 2.4.0) row.names and tsp.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

setClassUnion, Methods, makeClassRepresentation

Examples

## A simple class with two slots
setClass("track",
         representation(x="numeric", y="numeric"))
## A class extending the previous, adding one more slot
setClass("trackCurve",
         representation("track", smooth = "numeric"))
## A class similar to "trackCurve", but with different structure
## allowing matrices for the "y" and "smooth" slots
setClass("trackMultiCurve",
         representation(x="numeric", y="matrix", smooth="matrix"),
         prototype = list(x=numeric(), y=matrix(0,0,0),
                          smooth= matrix(0,0,0)))
##
## Suppose we want trackMultiCurve to be like trackCurve when there's
## only one column.
## First, the wrong way.
try(setIs("trackMultiCurve", "trackCurve",
    test = function(obj) {ncol(slot(obj, "y")) == 1}))

## Why didn't that work?  You can only override the slots "x", "y",
## and "smooth" if you provide an explicit coerce function to correct
## any inconsistencies:

setIs("trackMultiCurve", "trackCurve",
  test = function(obj) {ncol(slot(obj, "y")) == 1},
  coerce = function(obj) {
     new("trackCurve",
         x = slot(obj, "x"),
         y = as.numeric(slot(obj,"y")),
         smooth = as.numeric(slot(obj, "smooth")))
  })

## A class that extends the built-in data type "numeric"

setClass("numWithId", representation(id = "character"),
         contains = "numeric")

new("numWithId", 1:3, id = "An Example")


Classes Defined as the Union of Other Classes

Description

A class may be defined as the union of other classes; that is, as a virtual class defined as a superclass of several other classes. Class unions are useful in method signatures or as slots in other classes, when we want to allow one of several classes to be supplied.

Usage

setClassUnion(name, members, where)
isClassUnion(Class)

Arguments

name | the name for the new union class.
members | the classes that should be members of this union.
where | where to save the new class definition; by default, the environment of the package in which the setClassUnion call appears, or the global environment if called outside of the source of a package.
Class | the name or definition of a class.

Details

The classes in members must be defined before creating the union. However, members can be added later on to an existing union, as shown in the example below. Class unions can be members of other class unions.

Class unions are the only way to create a class that is extended by a class whose definition is sealed (for example, the basic datatypes or other classes defined in the base or methods package in R are sealed). You cannot say setIs("function", "other") unless "other" is a class union. In general, a setIs call of this form changes the definition of the first class mentioned (adding "other" to the list of superclasses contained in the definition of "function").

Class unions get around this by not modifying the first class definition, relying instead on storing information in the subclasses slot of the class union. In order for this technique to work, the internal computations for expressions such as extends(class1, class2) work differently for class unions than for regular classes; specifically, they test whether any class is in common between the superclasses of class1 and the subclasses of class2.

The different behavior for class unions is made possible because the class definition object for class unions has itself a special class, "ClassUnionRepresentation", an extension of "classRepresentation" (see classRepresentation-class).

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

Examples

## a class for either numeric or logical data
setClassUnion("maybeNumber", c("numeric", "logical"))

## use the union as the data part of another class
setClass("withId", representation("maybeNumber", id = "character"))

w1 <- new("withId", 1:10, id = "test 1")
w2 <- new("withId", sqrt(w1)%%1 < .01, id = "Perfect squares")

## add class "complex" to the union "maybeNumber"
setIs("complex", "maybeNumber")

w3 <- new("withId", complex(real = 1:10, imaginary = sqrt(1:10)))

## a class union containing the existing class  union "OptionalFunction"
setClassUnion("maybeCode",
    c("expression", "language", "OptionalFunction"))

is(quote(sqrt(1:10)), "maybeCode")  ## TRUE


Define a New Generic Function

Description

Create a new generic function of the given name, for which formal methods can then be defined. Typically, an existing non-generic function becomes the default method, but there is much optional control. See the details section.

Usage

setGeneric(name, def= , group=list(), valueClass=character(), where= ,
           package= , signature= , useAsDefault= , genericFunction= )

setGroupGeneric(name, def= , group=list(), valueClass=character(),
                knownMembers=list(), package= , where= )

Arguments

name | The character string name of the generic function. In the simplest and most common case, a function of this name is already defined. The existing function may be non-generic or already a generic (see the details).
def | An optional function object, defining the generic. This argument is usually only needed (and is then required) if there is no current function of this name. In that case, the formal arguments and default values for the generic are taken from def. You can also supply this argument if you want the generic function to do something other than just dispatch methods (an advanced topic best left alone unless you are sure you want it). Note that def is not the default method; use argument useAsDefault if you want to specify the default separately.
group | Optionally, a character string giving the group of generic functions to which this function belongs. Methods can be defined for the corresponding group generic, and these will then define methods for this specific generic function, if no method has been explicitly defined for the corresponding signature. See the references for more discussion.
valueClass | An optional character vector or unevaluated expression. The value returned by the generic function must have (or extend) this class, or one of the classes; otherwise, an error is generated. See the details section for supplying an expression.
package | The name of the package with which this function is associated. Usually determined automatically (as the package containing the non-generic version if there is one, or else the package where this generic is to be saved).
where | Where to store the resulting initial methods definition, and possibly the generic function; by default, stored into the top-level environment.
signature | Optionally, the signature of arguments in the function that can be used in methods for this generic. By default, all arguments other than ... can be used. The signature argument can prohibit methods from using some arguments. The argument, if provided, is a vector of formal argument names.
genericFunction | The object to be used as a (nonstandard) generic function definition. Supply this explicitly only if you know what you are doing!
useAsDefault | Override the usual choice of default argument (an existing non-generic function or no default if there is no such function). Argument useAsDefault can be supplied, either as a function to use for the default, or as a logical value. FALSE says not to have a default method at all, so that an error occurs if there is not an explicit or inherited method for a call. TRUE says to use the existing function as default, unconditionally (hardly ever needed as an explicit argument). See the section on details.
knownMembers | (For setGroupGeneric only) The names of functions that are known to be members of this group. This information is used to reset cached definitions of the member generics when information about the group generic is changed.

Details

The setGeneric function is called to initialize a generic function in an environment (usually the global environment), as preparation for defining some methods for that function.

The simplest and most common situation is that name is already an ordinary non-generic function, and you now want to turn this function into a generic. In this case you will most often supply only name. The existing function becomes the default method, and the special group and valueClass properties remain unspecified.

A second situation is that you want to create a new, generic function, unrelated to any existing function. In this case, you need to supply a skeleton of the function definition, to define the arguments for the function. The body of a generic function is usually a standard form, standardGeneric(name) where name is the quoted name of the generic function.

When calling setGeneric in this form, you would normally supply the def argument as a function of this form. If not told otherwise, setGeneric will try to find a non-generic version of the function to use as a default. If you don't want this to happen, supply the argument useAsDefault. That argument can be the function you want to be the default method. You can supply the argument as FALSE to force no default (i.e., to cause an error if there is not direct or inherited method on call to the function).

The same no-default situation occurs if there is no non-generic form of the function, and useAsDefault=FALSE. Remember, though, you can also just assign the default you want (even one that generates an error) rather than relying on the prior situation.

You cannot (and never need to) create an explicit generic for the primitive functions in the base library. These are dispatched from C code for efficiency and are not to be redefined in any case.

As mentioned, the body of a generic function usually does nothing except for dispatching methods by a call to standardGeneric. Under some circumstances you might just want to do some additional computation in the generic function itself. As long as your function eventually calls standardGeneric that is permissible (though perhaps not a good idea, in that it makes the behavior of your function different from the usual S model). If your explicit definition of the generic function does not call standardGeneric you are in trouble, because none of the methods for the function will ever be dispatched.

By default, the generic function can return any object. If valueClass is supplied, it should be a vector of class names; the value returned by a method is then required to satisfy is(object, Class) for one of the specified classes. An empty (i.e., zero length) vector of classes means anything is allowed. Note that more complicated requirements on the result can be specified explicitly, by defining a non-standard generic function.

The setGroupGeneric function behaves like setGeneric except that it constructs a group generic function, differing in two ways from an ordinary generic function. First, this function cannot be called directly, and the body of the function created will contain a stop call with this information. Second, the group generic function contains information about the known members of the group, used to keep the members up to date when the group definition changes, through changes in the search list or direct specification of methods, etc.

Value

The setGeneric function exists for its side effect: saving the generic function to allow methods to be specified later. It returns name.

Generic Functions and Primitive Functions

A number of the basic R functions are specially implemented as primitive functions, to be evaluated directly in the underlying C code rather than by evaluating an S language definition. Primitive functions are eligible to have methods, but are handled differently by setGeneric and setGroupGeneric. A call to setGeneric for a primitive function does not create a new definition of the function, and the call is allowed only to “turn on” methods for that function.

A call to setGeneric for a primitive causes the evaluator to look for methods for that generic; a call to setGroupGeneric for any of the groups that include primitives ("Arith", "Logic", "Compare", "Ops", "Math", "Math2", "Summary", and "Complex") does the same for each of the functions in that group.

You usually only need to use either function if the methods are being defined only for the group generic. Defining a method for a primitive function, say "+", by a call to setMethod turns on method dispatch for that function. But in R defining a method for the corresponding group generic, "Arith", does not currently turn on method dispatch (for efficiency reasons). If there are no non-group methods for the functions, you have two choices.

You can turn on method dispatch for all the functions in the group by calling setGroupGeneric("Arith"), or you can turn on method dispatch for only some of the functions by calling setGeneric("+"), etc. Note that in either case you should give the name of the generic function as the only argument.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

Methods for a discussion of other functions to specify and manipulate the methods of generic functions.

Examples

###   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
      })

## An example of group generic methods, using the class
## "track"; see the documentation of setClass for its definition

## define a method for the Arith group

setMethod("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(rnorm(10)))

t1 - 100
1/t1


Create and Save a Method

Description

Create and save a formal method for a given function and list of classes.

Usage

setMethod(f, signature=character(), definition,
          where = topenv(parent.frame()),
          valueClass = NULL, sealed = FALSE)

removeMethod(f, signature, where)

Arguments

f | A generic function or the character-string name of the function.
signature | A match of formal argument names for f with the character-string names of corresponding classes. This argument can also just be the vector of class names, in which case the first name corresponds to the first formal argument, the next to the second formal argument, etc.
definition | A function definition, which will become the method called when the arguments in a call to f match the classes in signature, directly or through inheritance.
where | the database in which to store the definition of the method; For removeMethod, the default is the location of the (first) instance of the method for this signature.
valueClass | If supplied, this argument asserts that the method will return a value of this class. (At present this argument is stored but not explicitly used.)
sealed | If TRUE, the method so defined cannot be redefined by another call to setMethod (although it can be removed and then re-assigned). Note that this argument is an extension to the definition of setMethod in the reference.

Details

R methods for a particular generic function are stored in an object of class MethodsList. The effect of calling setMethod is to store definition in a MethodsList object on database where. If f doesn't exist as a generic function, but there is an ordinary function of the same name and the same formal arguments, a new generic function is created, and the previous non-generic version of f becomes the default method. This is equivalent to the programmer calling setGeneric for the same function; it's better practice to do the call explicitly, since it shows that you intend to turn f into a generic function.

Methods are stored in a hierarchical structure: see Methods for how the objects are used to select a method, and MethodsList for functions that manipulate the objects.

The class names in the signature can be any formal class, plus predefined basic classes such as "numeric", "character", and "matrix". Two additional special class names can appear: "ANY", meaning that this argument can have any class at all; and "missing", meaning that this argument must not appear in the call in order to match this signature. Don't confuse these two: if an argument isn't mentioned in a signature, it corresponds implicitly to class "ANY", not to "missing". See the example below. Old-style (“S3”) classes can also be used, if you need compatibility with these, but you should definitely declare these classes by calling setOldClass if you want S3-style inheritance to work.

While f can correspond to methods defined on several packages or environments, the underlying model is that these together make up the definition for a single generic function. When R proceeds to select and evaluate methods for f, the methods on the current search list are merged to form a single generic function and associated methods list. When f is called and a method is “dispatched”, the evaluator matches the classes of the actual arguments to the signatures of the available methods. When a match is found, the body of the corresponding method is evaluated, but without rematching the arguments to f. Aside from not rematching the arguments, the computation proceeds as if the call had been to the method. In particular, the lexical scope of the method is used.

Method definitions can have default expressions for arguments. If those arguments are then missing in the call to the generic function, the default expression in the method is used. If the method definition has no default for the argument, then the expression (if any) supplied in the definition of the generic function itself is used. But note that this expression will be evaluated in the environment defined by the method.

It is possible to have some differences between the formal arguments to a method supplied to setMethod and those of the generic. Roughly, if the generic has ... as one of its arguments, then the method may have extra formal arguments, which will be matched from the arguments matching ... in the call to f. (What actually happens is that a local function is created inside the method, with its formal arguments, and the method is re-defined to call that local function.)

Method dispatch tries to match the class of the actual arguments in a call to the available methods collected for f. Roughly, for each formal argument in turn, we look for the best match (the exact same class or the nearest element in the value of extends for that class) for which there is any possible method matching the remaining arguments. See Methods for more details.

Value

These functions exist for their side-effect, in setting or removing a method in the object defining methods for the specified generic.
The value returned by removeMethod is TRUE if a method was found to be removed.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details and ongoing development, see ?Methods and the pointers from that documentation..

See Also

Methods, MethodsList for details of the implementation

Examples

## methods for plotting track objects (see the example for setClass)
##
## First, with only one object as argument:
setMethod("plot", signature(x="track", y="missing"),
  function(x,  y, ...) plot(slot(x, "x"), slot(x, "y"), ...)
)
## Second, plot the data from the track on the y-axis against anything
## as the x data.
setMethod("plot", signature(y = "track"),
 function(x, y, ...) plot(x, slot(y, "y"), ...)
)
## and similarly with the track on the x-axis (using the short form of
## specification for signatures)
setMethod("plot", "track",
 function(x, y, ...) plot(slot(x, "y"), y,  ...)
)
t1 <- new("track", x=1:20, y=(1:20)^2)
tc1 <- new("trackCurve", t1)
slot(tc1, "smooth") <- smooth.spline(slot(tc1, "x"), slot(tc1, "y"))$y #$
plot(t1)
plot(qnorm(ppoints(20)), t1)
## An example of inherited methods, and of conforming method arguments
## (note the dotCurve argument in the method, which will be pulled out
## of ... in the generic.
setMethod("plot", c("trackCurve", "missing"),
function(x, y, dotCurve = FALSE, ...) {
  plot(as(x, "track"))
  if(length(slot(x, "smooth") > 0))
    lines(slot(x, "x"), slot(x, "smooth"),
         lty = if(dotCurve) 2 else 1)
  }
)
## the plot of tc1 alone has an added curve; other uses of tc1
## are treated as if it were a "track" object.
plot(tc1, dotCurve = TRUE)
plot(qnorm(ppoints(20)), tc1)

## defining methods for a special function.
## Although "[" and "length" are not ordinary functions
## methods can be defined for them.
setMethod("[", "track",
  function(x, i, j, ..., drop) {
    x@x <- x@x[i]; x@y <- x@y[i]
    x
  })
plot(t1[1:15])

setMethod("length", "track", function(x)length(x@y))
length(t1)

## methods can be defined for missing arguments as well
setGeneric("summary") ## make the function into a generic

## A method for summary()
## The method definition can include the arguments, but
## if they're omitted, class "missing" is assumed.

setMethod("summary", "missing", function() "<No Object>")


Specify Names for Old-Style Classes

Description

Register an old-style (a.k.a. `S3') class as a formally defined class. The Classes argument is the character vector used as the class attribute; in particular, if there is more than one string, old-style class inheritance is mimiced. Registering via setOldClass allows S3 classes to appear in method signatures, and as a slot in an S4 class if a prototype is included.

Usage

setOldClass(Classes, prototype, where, test = FALSE)

Arguments

Classes | A character vector, giving the names for old-style classes, as they would appear on the right side of an assignment of the class attribute.
prototype | An optional object to use as the prototype. This should be provided as the default S3 object for the class, if you plan to use the class as a slot in an S4 class. See the details section.
where | Where to store the class definitions, the global or top-level environment by default. (When either function is called in the source for a package, the class definitions will be included in the package's environment by default.)
test | flag, if TRUE, inheritance must be tested explicitly for each object, needed if the S3 class can have a different set of class strings, with the same first string. See the details below.

Details

Each of the names will be defined as an S4 class, extending the remaining classes in Classes, and the class oldClass, which is the “root” of all old-style classes. S3 classes have no formal definition, and therefore no formally defined slots. If a prototype argument is supplied in the call to setOldClass(), objects from the class can be generated. If the S3 class is to be a slot in an S4 class, providing a prototype is recommended. Otherwise, the class will be created as a virtual S4 class; method dispatch will still work and inheritance will follow the S3 class hierarchy, but actions that require a prototype object from the class will not. For example, using the class as a slot in an S4 class definition will set the corresponding slot to NULL in the prototype for the S4 class.

Providing a prototype allows the function new() to be called for this class, but optional arguments in this call are not meaningful, since the class has no formal slots. Extending an S3 class with an S4 class is formally legal, but discouraged. Since the S4 subclass will have a single character string in its class(), S3 inheritance will not work. Also, there is no safe way for a general object from the S3 class to be inserted when an object is generated from the subclass.

See Methods for the details of method dispatch and inheritance. See the section Register or Convert? for comments on the alternative of defining “real” S4 classes rather than using setOldClass.

Some S3 classes cannot be represented as an ordinary combination of S4 classes and superclasses, because objects from the S3 class can have a variable set of strings in the class. It is still possible to register such classes as S4 classes, but now the inheritance has to be verified for each object, and you must call setOldClass with argument test=TRUE once for each superclass.

For example, ordered factors always have the S3 class c("ordered", "factor"). This is proper behavior, and maps simply into two S4 classes, with "ordered" extending "factor".

But objects whose class attribute has "POSIXt" as the first string may have either (or neither) of "POSIXct" or "POSIXlt" as the second string. This behavior can be mapped into S4 classes but now to evaluate is(x, "POSIXlt"), for example, requires checking the S3 class attribute on each object. Supplying the test=TRUE argument to setOldClass causes an explicit test to be included in the class definitions. It's never wrong to have this test, but since it adds significant overhead to methods defined for the inherited classes, you should only supply this argument if it's known that object-specific tests are needed.

The list .OldClassesList contains the old-style classes that are defined by the methods package. Each element of the list is an old-style list, with multiple character strings if inheritance is included. Each element of the list was passed to setOldClass when creating the methods package; therefore, these classes can be used in setMethod calls, with the inheritance as implied by the list.

Register or Convert?

A call to setOldClass creates formal classes corresponding to S3 classes, allows these to be used as slots in other classes or in a signature in setMethod, and mimics the S3 inheritance.

Supplying the prototype and optionally the generator arguments allows the S4 class created to be non-virtual, making it a candidate to be a slot in S4 class definitions and to be extended by S4 classes. The class still does not have formally defined slots. Because R implements slots as attributes, an S3 class that uses attributes (factor, for example) can in principle be defined as an S4 class with slots. However, a class such as lm that uses components of a list in a similar role cannot have formal slots. The slots would not be interpreted by S3 code written for lm objects.

If your class does in fact have a consistent set of attributes, so that every object from the class has the same structure, you may prefer to take some extra time to write down a specific definition in a call to setClass to convert the class to a fully functional formal class. On the other hand, if the actual contents of the class vary from one object to another, such a definition will not generally be possible. You should still register the class via setOldClass, unless its class attribute is hopelessly unpredictable.

An S3 class has consistent structure if each object has the same set of attributes, both the names and the classes of the attributes being the same for every object in the class. In practice, you can convert classes that are slightly less well behaved. If a few attributes appear in some but not all objects, you can include these optional attributes as slots that always appear in the objects, if you can supply a default value that is equivalent to the attribute being missing. Sometimes NULL can be that value: A slot (but not an attribute) can have the value NULL. If version, for example, was an optional attribute, the old test is.null(attr(x,"version") for a missing version attribute could turn into is.null(x@version) for the formal class.

The requirement that slots have a fixed class can be satisfied indirectly as well. Slots can be specified with class "ANY", allowing an arbitrary object. However, this eliminates an important benefit of formal class definitions; namely, automatic validation of objects assigned to a slot. If just a few different classes are possible, consider using setClassUnion to define valid objects for a slot.

See Also

setClass, setMethod

Examples

setOldClass(c("mlm", "lm"))
setGeneric("dfResidual", function(model)standardGeneric("dfResidual"))
setMethod("dfResidual", "lm", function(model)model$df.residual)

## dfResidual will work on mlm objects as well as lm objects
myData <- data.frame(time = 1:10, y = (1:10)^.5)
myLm <- lm(cbind(y, y^3)  ~ time, myData)

rm(myData, myLm)
removeGeneric("dfResidual")
## Not run: setOldClass("data.frame", prototoype = data.frame())

## End(Not run)


Create a Class Definition

Description

Constructs a classRepresentation-class object to describe a particular class. Mostly a utility function, but you can call it to create a class definition without assigning it, as setClass would do.

Usage

makeClassRepresentation(name, slots=list(), superClasses=character(),
                        prototype=NULL, package, validity, access,
                        version, sealed, virtual=NA, where)

Arguments

name | character string name for the class
slots | named list of slot classes as would be supplied to setClass, but without the unnamed arguments for superClasses if any.
superClasses | what classes does this class extend
prototype | an object providing the default data for the class, e.g, the result of a call to prototype.
package | The character string name for the package in which the class will be stored; see getPackageName.
validity | Optional validity method. See validObject, and the discussion of validity methods in the reference.
access | Access information. Not currently used.
version | Optional version key for version control. Currently generated, but not used.
sealed | Is the class sealed? See setClass.
virtual | Is this known to be a virtual class?
where | The environment from which to look for class definitions needed (e.g., for slots or superclasses). See the discussion of this argument under GenericFunctions.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

setClass


Show an Object

Description

Display the object, by printing, plotting or whatever suits its class. This function exists to be specialized by methods. The default method calls showDefault.

Formal methods for show will usually be invoked for automatic printing (see the details).

Usage

show(object)

Arguments

object Any R object

Details

The methods package overrides the base definition of print.default to arrange for automatic printing to honor methods for the function show. This does not quite manage to override old-style printing methods, since the automatic printing in the evaluator will look first for the old-style method.

If you have a class myClass and want to define a method for show, all will be well unless there is already a function named print.myClass. In that case, to get your method dispatched for automatic printing, it will have to be a method for print. A slight cheat is to override the function print.myClass yourself, and then call that function also in the method for show with signature "myClass".

Value

show returns an invisible NULL.

See Also

showMethods prints all the methods for one or more functions; showMlist prints individual methods lists; showClass prints class definitions. Neither of the latter two normally needs to be called directly.

Examples

## following the example shown in the setMethod documentation ...
setClass("track",
         representation(x="numeric", y="numeric"))
setClass("trackCurve",
         representation("track", smooth = "numeric"))

t1 <- new("track", x=1:20, y=(1:20)^2)

tc1 <- new("trackCurve", t1)

setMethod("show", "track",
  function(object)print(rbind(x = object@x, y=object@y))
)
## The method will now be used for automatic printing of t1

t1

## Not run:
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
x    1    2    3    4    5    6    7    8    9    10    11    12
y    1    4    9   16   25   36   49   64   81   100   121   144
  [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
x    13    14    15    16    17    18    19    20
y   169   196   225   256   289   324   361   400
## End(Not run)
## and also for tc1, an object of a class that extends "track"
tc1

## Not run:
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
x    1    2    3    4    5    6    7    8    9    10    11    12
y    1    4    9   16   25   36   49   64   81   100   121   144
  [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
x    13    14    15    16    17    18    19    20
y   169   196   225   256   289   324   361   400
## End(Not run)


Show all the methods for the specified function(s)

Description

Show a summary of the methods for one or more generic functions, possibly restricted to those involving specified classes.

Usage

showMethods(f = character(), where = topenv(parent.frame()),
            classes = NULL, includeDefs = FALSE, inherited = TRUE,
            showEmpty, printTo = stdout())

Arguments

f | one or more function names. If omitted, all functions will be shown that match the other arguments.
where | Used only when f is missing, or length 0, to determine which generic functions to examine. If where is supplied, only the generic functions returned by getGenerics(where) are eligible for printing. If where is also missing, all the cached generic functions are considered.
classes | If argument classes is supplied, it is a vector of class names that restricts the displayed results to those methods whose signatures include one or more of those classes.
includeDefs | If includeDefs is TRUE, include the definitions of the individual methods in the printout.
inherited | If inherits is TRUE, then methods that have been found by inheritance, so far in the session, will be included and marked as inherited. Note that an inherited method will not usually appear until it has been used in this session. See selectMethod if you want to know what method is dispatched for particular classes of arguments.
showEmpty | logical indicating whether methods with no defined methods matching the other criteria should be shown at all. By default, TRUE if and only if argument f is not missing.
printTo | The connection on which the printed information will be written; by default, standard output. If printTo is FALSE, the output will be collected as a character vector and returned as the value of the call to showMethod. See show.

Details

The name and package of the generic are followed by the list of signatures for which methods are currently defined, according to the criteria determined by the various arguments. Note that the package refers to the source of the generic function. Individual methods for that generic can come from other packages as well.

Value

If printTo is FALSE, the character vector that would have been printed is returned; otherwise the value is the connection or filename, via invisible.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. See Methods and references from there.

See Also

setMethod, and GenericFunctions for other tools involving methods; selectMethod will show you the method dispatched for a particular function and signature of classes for the arguments.

Examples

## Assuming the methods for plot
## are set up as in the example of help(setMethod),
## print (without definitions) the methods that involve class "track":
showMethods("plot", classes = "track")
## Not run:
Function "plot":
x = ANY, y = track
x = track, y = missing
x = track, y = ANY
## End(Not run)

not.there <- !any("package:stats4" == search())
if(not.there) library(stats4)
showMethods(class = "mle")
if(not.there) detach("package:stats4")


Class "signature" For Method Definitions

signature-class(methods) R Documentation

Class 'signature' For Method Definitions

Description

This class represents the mapping of some of the formal arguments of a function onto the names of some classes. It is used as one of two slots in the MethodDefinition-class.

Objects from the Class

Objects can be created by calls of the form new("signature", functionDef, ...). The functionDef argument, if it is supplied as a function object, defines the formal names. The other arguments define the classes.

Slots

.Data:
Object of class "character" the classes.
names:
Object of class "character" the corresponding argument names.

Extends

Class "character", from data part. Class "vector", by class "character".

Methods

initialize
signature(object = "signature"): see the discussion of objects from the class, above.

See Also

MethodDefinition-class for the use of this class


The Slots in an Object from a Formal Class

Description

These functions return or set information about the individual slots in an object.

Usage

object@name
object@name <- value

slot(object, name)
slot(object, name, check = TRUE) <- value

slotNames(x)

Arguments

object | An object from a formally defined class.
name | The character-string name of the slot. The name must be a valid slot name: see Details below.
value | A new value for the named slot. The value must be valid for this slot in this object's class.
x | Either the name of a class or an object from that class. Print getClass(class) to see the full description of the slots.
check | If TRUE, check the assigned value for validity as the value of this slot. You should never set this to FALSE in normal use, since the result can create invalid objects.

Details

The "@" operator and the slot function extract or replace the formally defined slots for the object. The operator takes a fixed name, which can be unquoted if it is syntactically a name in the language. A slot name can be any non-empty string, but if the name is not made up of letters, numbers, and ., it needs to be quoted (by backticks or single or double quotes).

In the case of the slot function, name can be any expression that evaluates to a valid slot in the class definition. Generally, the only reason to use the functional form rather than the simpler operator is because the slot name has to be computed.

The definition of the class contains the names of all slots directly and indirectly defined. Each slot has a name and an associated class. Extracting a slot returns an object from that class. Setting a slot first coerces the value to the specified slot and then stores it.

Unlike attributes, slots are not partially matched, and asking for (or trying to set) a slot with an invalid name for that class generates an error.

Note that currently, slotNames() behaves particularly for class representation objects – this is considered bogus and likely to be changed.

Currently the @ extraction operator and slot function do no checking, neither that object has a formal class nor that name is a valid slot name for the class. (They will extract the attribute of the given name if it exists from any R object.) The replacement forms do check (at least if check=TRUE).

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

@, Classes, Methods, getClass

Examples

setClass("track", representation(x="numeric", y="numeric"))
myTrack <- new("track", x = -4:4, y = exp(-4:4))
slot(myTrack, "x")
slot(myTrack, "y") <- log(slot(myTrack, "y"))
str(myTrack)

slotNames("track") # is the same as
slotNames(myTrack)


Classes Corresponding to Basic Structures

Description

The virtual class structure and classes that extend it are formal classes analogous to S language structures such as arrays and time-series

Usage

## The folowing class names can appear in method signatures,
## as the class in as() and is() expressions, and, except for
## the classes commented as VIRTUAL, in calls to new()

"matrix"
"array"
"ts"

"structure" ## VIRTUAL

Objects from the Classes

Objects can be created by calls of the form new(Class, ...), where Class is the quoted name of the specific class (e.g., "matrix"), and the other arguments, if any, are interpreted as arguments to the corresponding function, e.g., to function matrix(). There is no particular advantage over calling those functions directly, unless you are writing software designed to work for multiple classes, perhaps with the class name and the arguments passed in.

Extends

The specific classes all extend class "structure", directly, and class "vector", by class "structure".

Methods

coerce
Methods are defined to coerce arbitrary objects to these classes, by calling the corresponding basic function, for example, as(x, "matrix") calls as.matrix(x).


SubstituteDirect

Description

Substitute for the variables named in the second argument the corresponding objects, substituting into object. The argument frame is a named list; if omitted, the environment of the caller is used.

This function differs from the ordinary substitute in that it treats its first argument in the standard S way, by evaluating it. In contrast, substitute does not evaluate its first argument.

The goal is to replace this with an eval= argument to substitute.

Usage

substituteDirect(object, frame, cleanFunction=TRUE)


Classes Used Internally to Control Tracing

Description

The classes described here are used by the R function trace to create versions of functions and methods including browser calls, etc., and also to untrace the same objects.

Usage

### Objects from the following classes are generated
### by calling trace() on an object from the corresponding
### class without the "WithTrace" in the name.

"functionWithTrace"
"MethodDefinitionWithTrace"
"MethodWithNextWithTrace"
"genericFunctionWithTrace"
"groupGenericFunctionWithTrace"

### the following is a virtual class extended by each of the
### classes above

"traceable"

Objects from the Class

Objects will be created from these classes by calls to trace. (There is an initialize method for class "traceable", but you are unlikely to need it directly.)

Slots

.Data:
The data part, which will be "function" for class "functionWithTrace", and similarly for the other classes.
original:
Object of the original class; e.g., "function" for class "functionWithTrace".

Extends

Each of the classes extends the corresponding untraced class, from the data part; e.g., "functionWithTrace" extends "function". Each of the specific classes extends "traceable", directly, and class "VIRTUAL", by class "traceable".

Methods

The point of the specific classes is that objects generated from them, by function trace(), remain callable or dispatchable, in addition to their new trace information.

See Also

function trace


Test the Validity of an Object

Description

The validity of object related to its class definition is tested. If the object is valid, TRUE is returned; otherwise, either a vector of strings describing validity failures is returned, or an error is generated (according to whether test is TRUE). Optionally, all slots in the object can also be validated.

The function setValidity sets the validity method of a class (but more normally, this method will be supplied as the validity argument to setClass). The method should be a function of one object that returns TRUE or a description of the non-validity.

Usage

validObject(object, test = FALSE, complete = FALSE)

setValidity(Class, method, where = topenv(parent.frame()) )

Arguments

object | Any object, but not much will happen unless the object's class has a formal definition.
test | logical; if TRUE and validity fails, the function returns a vector of strings describing the problems. If test is FALSE (the default) validity failure generates an error.
complete | logical; if TRUE, validity methods will be applied recursively to any of the slots that have such methods.
Class | the name or class definition of the class whose validity method is to be set.
method | a validity method; that is, either NULL or a function of one argument (the object). Like validObject, the function should return TRUE if the object is valid, and one or more descriptive strings if any problems are found. Unlike validObject, it should never generate an error.
where | the modified class definition will be stored in this environment.

Note that validity methods do not have to check validity of superclasses: the logic of validObject ensures these tests are done once only. As a consequence, if one validity method wants to use another, it should extract and call the method from the other definition of the other class by calling getValidity: it should not call validObject.

Details

Validity testing takes place “bottom up”: Optionally, if complete=TRUE, the validity of the object's slots, if any, is tested. Then, in all cases, for each of the classes that this class extends (the “superclasses”), the explicit validity method of that class is called, if one exists. Finally, the validity method of object's class is called, if there is one.

Testing generally stops at the first stage of finding an error, except that all the slots will be examined even if a slot has failed its validity test.

The standard validity test (with complete=FALSE) is applied when an object is created via new with any optional arguments (without the extra arguments the result is just the class prototype object).

Value

validObject returns TRUE if the object is valid. Otherwise a vector of strings describing problems found, except that if test is FALSE, validity failure generates an error, with the corresponding strings in the error message.

References

The R package methods implements, with a few exceptions, the programming interface for classes and methods in the book Programming with Data (John M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

While the programming interface for the methods package follows the reference, the R software is an original implementation, so details in the reference that reflect the S4 implementation may appear differently in R. Also, there are extensions to the programming interface developed more recently than the reference. For a discussion of details see ?Methods and the links from that documentation.

See Also

setClass.

Examples

setClass("track",
          representation(x="numeric", y = "numeric"))
t1 <- new("track", x=1:10, y=sort(rnorm(10)))
## A valid "track" object has the same number of x, y values
validTrackObject <- function(x){
    if(length(x@x) == length(x@y)) TRUE
    else paste("Unequal x,y lengths: ", length(x@x), ", ", length(x@y),
    sep="")
}
## assign the function as the validity method for the class
setValidity("track", validTrackObject)
## t1 should be a valid "track" object
validObject(t1)
## Now we do something bad
t2 <- t1
t2@x <- 1:20
## This should generate an error
## Not run: try(validObject(t2))

setClass("trackCurve",
         representation("track", smooth = "numeric"))

## all superclass validity methods are used when validObject
## is called from initialize() with arguments, so this fails
## Not run: trynew("trackCurve", t2)

setClass("twoTrack", representation(tr1 = "track", tr2 ="track"))

## validity tests are not applied recursively by default,
## so this object is created (invalidly)
tT  <- new("twoTrack", tr2 = t2)

## A stricter test detects the problem
## Not run: try(validObject(tT, complete = TRUE))


List of Builtin and Special Functions

Description

A named list providing instructions for turning builtin and special functions into generic functions.

Functions in R that are defined as .Primitive(<name>) are not suitable for formal methods, because they lack the basic reflectance property. You can't find the argument list for these functions by examining the function object itself.

Future versions of R may fix this by attaching a formal argument list to the corresponding function. While generally the names of arguments are not checked by the internal code implementing the function, the number of arguments frequently is.

In any case, some definition of a formal argument list is needed if users are to define methods for these functions. In particular, if methods are to be merged from multiple packages, the different sets of methods need to agree on the formal arguments.

In the absence of reflectance, this list provides the relevant information via a dummy function associated with each of the known specials for which methods are allowed.

At the same, the list flags those specials for which methods are meaningless (e.g., for) or just a very bad idea (e.g., .Primitive).

A generic function created via setMethod, for example, for one of these special functions will have the argument list from .BasicFunsList. If no entry exists, the argument list (x, ...) is assumed.