Object-Oriented Programming in R


Object-oriented programming focuses on data and objects rather than procedures. The object-oriented model helps us to model real-life objects. It is important to master object-oriented programming concepts in order to excel in the field of data science. Each program has special types of classes. In this tutorial, the discussion will be focused on S3 and S4 classes in R, generic functions, inheritances between classes, and polymorphism. In this tutorial, we will discuss object-oriented programming concepts in R.

Object-Oriented Programming in R

Object oriented programming is a programming model that revolves around classes and objects rather than functions. In R we can also create two special types of classes, S3 and S4. The OOPS concept allows us to create modular pieces that act as the building blocks of the large systems. The S3 and S4 are the two important classes in object oriented programming. The S3 class allows overloading any function. The S4 class differs slightly from S3 as it contains helper functions for defining methods and generics.

Classes and Objects in R

A class is a user-defined data type from which objects are created. They are also referred to as blueprints sometimes. This is because they define the structure of objects. A class is a passive entity whereas an object is an active entity.

R considers all things as objects. An object is a single instance of a class. R provides us a class() function which can be either used to define the class of a function or get the information of the class for an already defined object.

A class in R is present in a vector form. Due to this property, the objects can inherit from many classes, and also we can specify the order of inheritance even for complex classes.

Example

Let us consider the following program that checks the class of an object −

Names <-c("Bhuwanesh","Jai", "Piyush", "Anil", "Hitesh", "Naveen")
print(class(Names))

Output

[1] "character"

Since, the class elements belong to character class, therefore “character” has been displayed.

Example

Now let us see how we can append the class of an object −

Names <-c("Bhuwanesh", "Jai", "Piyush", "Anil", "Hitesh", "Naveen")
class(Names)<-append(class(Names), "boys")
print(class(Names))

Output

[1] "character" "boys"     

As you can see in the output, we have appended the class of the vector.

Classes in R

S3 Class

An S3 class is one of the most used classes in R. This class is easy to implement and many predefined classes are of this type.

The object of an S3 class is a list having class attributes assigned with some names. The component of the list is represented by the member variable of the object.

Creating S3 Class

We can create an S3 object by the following steps −

  • Make a list having the required component values.

  • Then, we can create a class easily using the class() function and also append a name to this class.

Example

# Creating list
myList <- list(Name ="Bhuwanesh", Enrollment_Number = 3496303119,
   Course = "Btech", Branch = "Information Technology")
# class
class(myList) <- "University"

myList

Output

$Name
[1] "Bhuwanesh"

$Enrollment_Number
[1] 3496303119

$Course
[1] "Btech"

$Branch
[1] "Information Technology"

attr(,"class")
[1] "University"

Generic Function

We have generic functions in R that serve the purpose of polymorphism (like many other oops languages: C++, Java, etc).

Polymorphism is made of two words − poly and morphism where poly means many and morphism means forms. It states that a single message can have more than one different form or it can serve different purposes.

For example in R, the summary() function is a set of many summary() functions that can be used for different data types and data structures. Such functions invoke an adequate function depending upon the type of object passed as an argument. We can see the various implementations of summary() functions using the methods() function.

methods(summary)

We can create our own generic function in R. Let us consider the following program that creates a list by the name “myList” and then creates a class out of it.

Example

Now we display the summary of this class using the summary() function −

# Create a list
myList <- list(Name ="Bhuwanesh", 
Enrollment_Number = 3496303119,
   Course = "Btech",
   Branch = "Information Technology")

# Define the class
class(myList) <- "University"

# Display the summary
print(summary(myList))

Output

                  Length Class  Mode     
Name              1      -none- character
Enrollment_Number 1      -none- numeric  
Course            1      -none- character
Branch            1      -none- character

Attributes

The attribute is a piece of extra information associated with an object and used to handle the object. We can use the attributes() function to get the attributes of an object.

Example

Let us consider the following program illustrating the working of this function −

# Create a list
myList <- list(Name ="Bhuwanesh", 
   Enrollment_Number = 3496303119,
   Course = "Btech", 
   Branch = "Information Technology")

# Define a class
class(myList) <- "University"

# Display attributes
print(attributes(myList))

Output

$names
[1] "Name"              "Enrollment_Number" "Course"           
[4] "Branch"           

$class
[1] "University"

We can also apply our own attributes to an object with the help of the attr() function Let us consider the following illustrating the working of this function −

Example

# Create a list
myList <- list(Name ="Bhuwanesh",
Enrollment_Number = 3496303119,
   Course = "Btech", 
   Branch = "Information Technology")

# Define class
class(myList) <-"University"

# Defining custom attributes
attr(myList,"Grade")<-c('A')

# Display attribute
print(attributes(myList))

Output

$names
[1] "Name"              "Enrollment_Number" "Course"           
[4] "Branch"           

$class
[1] "University"

$Grade
[1] "A"

Inheritance in S3 Class

Inheritance is one of the most important pillars of object-oriented programming language which allow one class to inherit the properties of another class. This feature leads to benefits like code-reusability.

The S3 class doesn’t contain any particular pattern for its definition.

Example

# Create a list
myList1 <- list(Name ="Bhuwanesh", Enrollment_Number = 3496303119,
   Course = "Btech", Branch = "Information Technology")

# Define the class
class(myList1) <- "University"

# Create a list
myList2 <- list(College_Rank = 14, State = 'Uttarakhand')

# Define the inheritance relation
class(myList2) <- c("College", "University")

print(myList2)

Output

$College_Rank
[1] 14

$State
[1] "Uttarakhand"

attr(,"class")
[1] "College"    "University"

As you can see in the output, class “College” inherits the class “University”.

Example

Now let us try to access and modify the components of the base class “University” using an object of the base class “College” −

# Create a list
myList1 <- list(Name ="Bhuwanesh", Enrollment_Number = 3496303119,
   Course = "Btech", Branch = "Information Technology")

# Define a class
class(myList1) <- "University"

myList2 <- list(College_Rank = 14, State = 'Uttarakhand')

class(myList2) <- c("College", "University")

# Define the attribute
myList2$Name = "Harshit"

print(myList2)

Output

$College_Rank
[1] 14

$State
[1] "Uttarakhand"

$Name
[1] "Harshit"

attr(,"class")
[1] "College"    "University"

You can see in the output, the “Name” property has been modified to “Harshit”.

S4 Class

R allows us to use another peculiar type of class known as the “S4” class. This class contains the predefined definition. This class contains functions to define methods and generics. This class also provides us with auxiliary functions to define generics and methods.

The setClass() function creates an S4 class. R provides us the new() function which is used to create an object of the S4 class −

Example

# Define a list
myList1 <- list(Name ="Bhuwanesh",
   Enrollment_Number = 3496303119,
   Course = "Btech",
   Branch = "Information Technology")

# Set the class
setClass("University", slots = list(Name ="character",
   Enrollment_Number = "numeric",
   Course = "character",
   Branch = "character"))

# Define the object
myObject <- new("University", 
   Name = "Bhuwanesh Nainwal", 
   Enrollment_Number = 3496303119, 
   Course = "Btech", 
   Branch = "Information Technology")

print(myObject)

Output

An object of class "University"
Slot "Name":
[1] "Bhuwanesh Nainwal"

Slot "Enrollment_Number":
[1] 3496303119

Slot "Course":
[1] "Btech"

Slot "Branch":
[1] "Information Technology"

Inheritance in S4 class

Inheritance is one of the most important pillars of object-oriented programming language which allow one class to inherit the properties of another class. This feature leads to benefits like code-reusability.

The S4 class contains a proper pattern for its definition. The derived classes are capable enough to inherit attributes and methods from the base class. In order to achieve this we can

Example

# Set class
setClass("University",
   slots = list(Name = "character",
      Enrollment_Number = "numeric",
      Branch = "character") 
)

# Set methods
setMethod("show", "University",
   function(object){
      cat(object@Name, "
") cat(object@Enrollment_Number, "
") cat(object@Branch, "
") } ) # Inherit setClass("College", slots = list(Grade= "character"), contains = "University" ) # Define the object object <- new("College", Name = "Bhuwanesh Nainwal", Branch="Information Technology", Enrollment_Number = 3496303119) # Display the object show(object)

Output

Bhuwanesh Nainwal 
3496303119 
Information Technology

Conclusion

In this article, we discussed object-oriented programming concepts related to R. Classes like S3 and S4 have been discussed in detail. We believe that this tutorial has surely enhanced your knowledge in the field of data science.

Updated on: 17-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements