objects and class

R Classes and Objects

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.


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.


Example 1: S3 class

> # create a list with required components
> s <- list(name = "John", age = 21, GPA = 3.5)

> # name the class appropriately
> class(s) <- "student"

Above example creates a S3 class with the given list.


S4 Class

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.

Comparision between S3 vs S4 vs Reference Class

S3 ClassS4 ClassReferene Class
Lacks formal definitionClass defined using setClass()Class defined using setRefClass()
Objects are created by setting the class attributeObjects 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 functionMethods belong to generic functionMethods belong to the class
Follows copy-on-modify semanticsFollows copy-on-modify semanticsDoes not follow copy-on-modify semantics

Comments

Popular posts from this blog

📚Gds-Tech 📚 EMS

vocab

spreadsheet in excel