as
Force an Object to Belong to a Class
Coerce an object to a given class.
- Keywords
- classes, methods, programming
Usage
as(object, Class, strict=TRUE, ext)as(object, Class) <- value
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, in particular 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 classClass
; some coercion is done, but you're unwise to rely on it.- ext
an optional object defining how
Class
is extended by the class of the object (as returned bypossibleExtends
). This argument is used internally; do not use it directly.
Description
as(object)
returns the version of this object coerced to be the given
Class
. When used in the replacement form on the left of
an assignment, the portion of the object corresponding to
Class
is replaced by value
.
The operation of as()
in either form depends on the
definition of coerce methods. Methods are defined automatically
when the two classes are related by inheritance; that is, when
one of the classes is a subclass of the other.
Coerce methods are also predefined for basic classes (including all the types of vectors, functions and a few others).
Beyond these two sources of methods, further methods are defined
by calls to the setAs
function. See that
documentation also for details of how coerce methods work. Use
showMethods(coerce)
for a list of all currently defined methods, as in the
example below.
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 and all other existing methods
can be listed as shown in the example.
References
Chambers, John M. (2016) Extending R, Chapman & Hall. (Chapters 9 and 10.)
See Also
If you think of using try(as(x, cl))
, consider
canCoerce(x, cl)
instead.
Examples
library(methods)
# NOT RUN {
## Show all the existing methods for as()
showMethods("coerce")
# }