fastread homefastrread library fastread menu

R Programming : Object and Class

Tutorial by:Maria Ghoste      Date: 2016-06-10 00:45:35

❰ Previous Next ❱

We can do object oriented programming in R. In fact, everything in R is an object. An object is a data structure having some attributes and methods which act on these attributes.

Class is a blueprint for the object. We can think of class like a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As, many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

While most programming languages have a single class system, R has three class systems. Namely, S3, S4 and more recently Reference class systems. They have their own features and peculiarities and choosing one over the other is a matter of preference. Below, we give a brief introduction to them.

S3 Class

S3 class is somewhat primitive in nature. It lacks a formal definition and object of this class can be created simply by adding a class attribute to it. This simplicity accounts for the fact that it is widely used in R programming language. In fact most of the R built-in classes are of this type. See R programming S3 Class section for further details.

S4 Class

S4 class are an improvement over S3 class. They have a formally defined structure which helps in making object of the same class look more or less similar. Class components are properly defined using the setClass() function and objects are created using the new() function. See R programming S4 Class section for further details.

Reference Class

Reference class were introduced later, compared to the other two. It is more similar to the object oriented programming we are used to seeing in other major programming languages. Reference classes are basically S4 classed with an environment added to it. See R programming Reference Class section for further details.

Comparision: S3 vs S4 vs Reference Class

S3 Class S4 Class Referene Class
Lacks formal definition Class defined using setClass() Class defined using setRefClass()
Objects are created by setting the class attribute Objects are created using new() Objects are created using generator functions
Attributes are accessed using $ Attributes are accessed using @ Attributes are accessed using $
Methods belong to generic function Methods belong to generic function Methods belong to the class
Follows copy-on-modify semantics Follows copy-on-modify semantics Does not follow copy-on-modify semantics

 

❰ Previous Next ❱


R Programming

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website