Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an object in R have more than one class?

Tags:

oop

r

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.

like image 515
qed Avatar asked Oct 12 '13 15:10

qed


People also ask

Can an object have multiple classes?

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.

What are the classes of objects in R?

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.

How do I find the class of an object in R?

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.

Can you build classes in R?

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.


1 Answers

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".

like image 162
Dirk Eddelbuettel Avatar answered Oct 14 '22 03:10

Dirk Eddelbuettel