Suppose I have a function like this:
myf = function(x) {
res = dostuff(x)
res # this is a data.frame
}
I want to do something special about res
, for example,
I want to make some generic functions like print.myf, summary.myf, ...
, so I can go ahead and give it a class:
myf = function(x) {
res = dostuff(x)
class(res) = 'myf'
res
}
But this way I cannot use it as a data.frame any more.
An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements. This means that if a variable is declared to be the type of an interface, then its value can reference any object that is instantiated from any class that implements the interface.
A class is just a blueprint or a sketch of these objects. It represents the set of properties or methods that are common to all objects of one type. Unlike most other programming languages, R has a three-class system. These are S3, S4, and Reference Classes.
Use typeof() to determine the base class of an object. A generic function calls specific methods depending on the class of it inputs. In S3 and S4 object systems, methods belong to generic functions, not classes like in other programming languages.
R programming allows you to create a class, which is a blueprint for an object. One of the most used methods for object-oriented programming in R is the S3 system. In R, you can convert a list to a class definition.
Yes, my standard (simple) example is
R> now <- Sys.time()
R> class(now)
[1] "POSIXct" "POSIXt"
R> class(as.POSIXlt(now))
[1] "POSIXlt" "POSIXt"
R>
It is also the reason behind the pro tip of testing with inherits("someClass")
rather than testing the result of class(obj)=="someClass"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With