R Class | R Object | R Objects and Classes: Introduction and Types - r - learn r - r programming
- R has 3 classes. In this article, you'll be introduced to all three classes (S3, S4 and reference class) in R programming.
- 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 its 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.
Sample class object image in C
- 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.
Example 1: S3 class
- Above example creates a S3 class with the given list.
- S4 class are an improvement over the 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.
Example 2: S4 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.
Example 3: Reference class
Comparision between 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|