The Wayback Machine - https://web.archive.org/web/20241123190928/https://www.geeksforgeeks.org/r-object-oriented-programming/
Open In App

R – Object Oriented Programming

Last Updated : 13 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes.

OOPs in R Programming Language:

In R programming, OOPs in R  provide classes and objects as its key tools to reduce and manage the complexity of the program. R is a functional language that uses concepts of OOPs. We can think of a class as a sketch of a car. It contains all the details about the model_name, model_no, engine, etc. Based on these descriptions we select a car. The car is the object. Each car object has its own characteristics and features. An object is also called an instance of a class and the process of creating this object is called instantiation. In R S3 and S4 classes are the two most important classes for object-oriented programming. But before going discussing these classes let’s see a brief about classes and objects.

Class and Object

Class is the blueprint or a prototype from which objects are made by encapsulating data members and functions. An object is a data structure that contains some methods that act upon its attributes. 

R - Object Oriented ProgrammingGeeksforgeeks

R – Object Oriented Programming

S3 Class

S3 class does not have a predefined definition and is able to dispatch. In this class, the generic function makes a call to the method. Easy implementation of S3 is possible because it differs from the traditional programming language Java, C++, and C# which implements Object Oriented message passing.

Creating S3 Class

To create an object of this class we will create a list that will contain all the class members. Then this list is passed to the class() method as an argument.

Syntax: 

variable_name <- list(attribute1, attribute2, attribute3….attributeN)

Example: 

In the following code, a Student class is defined. An appropriate class name is given having attributes student’s name and roll number. Then the object of the student class is created and invoked. 

R




# List creation with its attributes name
# and roll no.
a <- list(name="Adam", Roll_No=15)
 
# Defining a class "Student"
class(a) <- "Student"
 
# Creation of object
a


Output:

$name
[1] "Adam"

$Roll_No
[1] 15

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

Generic Functions

The generic functions are a good example of polymorphism. To understand the concept of generic functions consider the print() function. The print() function is a collection of various print functions that are created for different data types and data structures in the R Programming Language. It calls the appropriate function depending on the type of object passed as an argument. We can see the various implementation of print functions using the methods() function.

Example: Seeing different types of the print function

R




methods(print)


Output:

Print methodsGeeksforgeeks

Print methods

Now let’s create a generic function of our own. We will create the print function for our class that will print all the members in our specified format. But before creating a print function let’s create what the print function does to our class.

 Example:

R




# List creation with its attributes name
# and roll no.
a = list(name="Adam", Roll_No=15)
 
# Defining a class "Student"
class(a) = "Student"
 
# Creation of object
print(a)


Output:

$name
[1] "Adam"

$Roll_No
[1] 15

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

Now let’s print all the members in our specified format. Consider the below example –

Example:

R




print.Student <- function(obj){
  cat("name: " ,obj$name, "\n")
  cat("Roll No: ", obj$Roll_No, "\n")
}
 
print(a)


Output:

name:  Adam 
Roll No:  15 

Attributes

Attributes of an object do not affect the value of an object, but they are a piece of extra information that is used to handle the objects. The function attributes() can be used to view the attributes of an object.

Examples: An S3 object is created and its attributes are displayed.

R




attributes(a)


Output:

$names
'name''Roll_No'
$class
'Student'

Also, you can add attributes to an object by using attr. 

R




attr(a, "age")<-c(18)
attributes(a)


Output:

$names
'name''Roll_No'
$class
'Student'
$age
18

Inheritance in S3 Class

Inheritance is an important concept in OOP(object-oriented programming) which allows one class to derive the features and functionalities of another class. This feature facilitates code-reusability.

S3 class in R programming language has no formal and fixed definition. In an S3 object, a list with its class attribute is set to a class name. S3 class objects inherit only methods from their base class.

Example: 

In the following code, inheritance is done using S3 class, firstly the object is created of the class student.

R




# student function with argument
# name(n) and roll_no(r)
student <- function(n, r) {
    value <- list(name=n, Roll=r)
    attr(value, "class") < - "student"
    value
}


Then, the method is defined to print the details of the student. 

R




# 'print.student' method created
print.student <- function(obj) {
 
    # 'cat' function is used to concatenate
    # strings
    cat("Name:", obj$name, "\n")
    cat("Roll", obj$roll, "\n")}


Now, inheritance is done while creating another class by doing class(obj) <- c(child, parent).

R




s <- list(name="Kesha", Roll=21, country="India")
 
# child class 'Student' inherits
# parent class 'student'
class(s) <- c("Student", "student")
s


Output: 

Name: Kesha 
Roll: 21 

The following code overwrites the method for class students.

R




# 'Student' class object is passed
# in the function of class 'student'
 
print.student <- function(obj) {
    cat(obj$name, "is from", obj$country, "\n")
}
s


Output:

Kesha is from India

S4 Class 

S4 class has a predefined definition. It contains functions for defining methods and generics. It makes multiple dispatches easy. This class contains auxiliary functions for defining methods and generics.

Creating S4 class and object 

setClass() command is used to create S4 class. Following is the syntax for setclass command which denotes myclass with slots containing name and rollno.

Syntax: 

 setClass(“myclass”, slots=list(name=”character”, Roll_No=”numeric”))  

The new() function is used to create an object of the S4 class. In this function, we will pass the class name as well as the value for the slots.

Example: 

R




# Function setClass() command used
# to create S4 class containing list of slots.
setClass("Student", slots=list(name="character",
                               Roll_No="numeric"))
 
# 'new' keyword used to create object of
# class 'Student'
a <- new("Student", name="Adam", Roll_No=20)
 
# Calling object
a


Output: 

Slot "name":
[1] "Adam"

Slot "Roll_No":
[1] 20

Create S4 objects from the generator function

setClass() returns a generator function that helps in creating objects and it acts as a constructor.

Example:

R




stud <- setClass("Student", slots=list(name="character",
                               Roll_No="numeric"))
 
# Calling object
stud


Output:

class generator function for class “Student” from package ‘.GlobalEnv’
function (...) 
new("Student", ...)

Now the above-created stud function will act as the constructor for the Student class. It will behave as the new() function.

Example:

R




stud(name="Adam", Roll_No=15)


Output:

An object of class "Student"
Slot "name":
[1] "Adam"

Slot "Roll_No":
[1] 15

Inheritance in S4 class

S4 class in R programming have proper definition and derived classes will be able to inherit both attributes and methods from its base class. For this, we will first create a base class with appropriate slots and will create a generic function for that class. Then we will create a derived class that will inherit using the contains parameter. The derived class will inherit the members as well as functions from the base class.

Example:

R




# Define S4 class
setClass("student",
         slots=list(name="character",
                    age="numeric", rno="numeric")
         )
 
# Defining a function to display object details
setMethod("show", "student",
          function(obj){
              cat(obj@name, "\n")
              cat(obj@age, "\n")
              cat(obj@rno, "\n")
          }
          )
 
# Inherit from student
setClass("InternationalStudent",
         slots=list(country="character"),
         contains="student"
         )
 
# Rest of the attributes will be inherited from student
s <- new("InternationalStudent", name="Adam",
          age=22, rno=15, country="India")
show(s)


Output:

Adam 
22 
15

The reasons for defining both S3 and S4 classes are as follows: 

  • S4 class alone will not be seen if the S3 generic function is called directly. This will be the case, for example, if some function calls unique() from a package that does not make that function an S4 generic.
  • However, primitive functions and operators are exceptions: The internal C code will look for S4 methods if and only if the object is an S4 object. S4 method dispatch would be used to dispatch any binary operator calls where either of the operands was an S4 object.
  • S3 class alone will not be called if there is any eligible non-default S4 method.

So if a package defined an S3 method for unique for an S4 class but another package defined an S4 method for a superclass of that class, the superclass method would be chosen, probably not what was intended.



Previous Article
Next Article

Similar Reads

How to Fix in R: longer object length is not a multiple of shorter object length
In this article, we will be looking at the approach to fix the "longer object length is not a multiple of shorter object length" error in the R programming language. This is a warning message produced by the R compiler. The complete form of this warning message is given below: Warning message: In vect1 + vect2 : longer object length is not a multip
3 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x <- c(1, 2, 3, 4) # Creating a list list1 <- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Convert type of data object in R Programming - type.convert() Function
type.convert() function in R Language is used to compute the data type of a particular data object. It can convert data object to logical, integer, numeric, or factor. Syntax: type.convert(x) Parameter: x: It can be a vector matrix or an array Example 1: Apply type.convert to vector of numbers # R program to illustrate # type.convert to vector of n
2 min read
Return True Indices of a Logical Object in R Programming - which() Function
which() function in R Language is used to return the indices of the object which return true for the logical operation passed as argument. Syntax: which(x, arr.ind) Parameters: x: logical object arr.ind: Boolean value to display indices Example 1: # R program to illustrate # the use of which() function # Create a matrix x <- matrix(1:9, 3, 3) x
1 min read
Create an Object of mode call in R Programming - call() Function
call() function in R Language is used to create or test for objects of mode "call". Syntax: call(name, ...) Parameters: name: a non-empty character string naming the function to be called ...: arguments to be part of the call Example 1: # R program to illustrate # call function # Calling call() function x <- call("sin", 23) y <- cal
1 min read
Return an Object with the specified name in R Programming - get0() and mget() Function
In R programming, get0() and mget() function works similar to get() function. It is used to search and return the object with the specified name passed to it as argument. get0() Function get0() function has the same syntax as get() function but there is an addition of a new parameter which returns an output if the data object is not found. Clearly,
2 min read
Calculate Cumulative Product of a Numeric Object in R Programming – cumprod() Function
cumprod() function in R Language is used to calculate the cumulative product of the vector passed as argument. Syntax: cumprod(x) Parameters: x: Numeric Object Example 1: # R program to illustrate # the use of cumprod() Function # Calling cumprod() Function cumprod(1:4) cumprod(-1:-6) Output: [1] 1 2 6 24 [1] -1 2 -6 24 -120 720 Example 2: # R prog
1 min read
Check if Object is of the Character Data type in R Programming - is.character() Function
is.character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type. Syntax: is.character(Object) Parameter: Object: It could be an array, list, vector, etc. Example 1: # R Program to illustrate # the use of is.character func
1 min read
Get the number of columns of an Object in R Programming - ncol() Function
ncol() function in R Language is used to return the number of columns of the specified matrix. Syntax: ncol(x)Parameters: x: matrix, vector, array or data frame Example 1: C/C++ Code # R program to illustrate # ncol function # Getting R Biochemical Oxygen Demand Dataset BOD # Calling ncol() function to # get the number of columns ncol(BOD) Output:
1 min read
Checking if the Object is a Factor in R Programming - is.factor() Function
is.factor() function in R Language is used to check if the object passed to the function is a Factor or not. It returns a boolean value as output. Syntax: is.factor(Object) Parameters: Object: Object to be checked Example 1: # Creating a vector x<-c("female", "male", "male", "female") # Converting the vect
1 min read
Get the number of rows of an Object in R Programming - nrow() Function
nrow() function in R Language is used to return the number of rows of the specified matrix. Syntax: nrow(x)Parameters: x: matrix, vector, array or data frame Example 1: C/C++ Code # R program to illustrate # nrow function # Getting R Biochemical Oxygen Demand Dataset BOD # Calling nrow() function to # get the number of rows nrow(BOD) Output: Time d
1 min read
Remove Duplicate Elements from an Object in R Programming - unique() Function
unique() function in R Language is used to remove duplicated elements/rows from a vector, data frame or array. Syntax: unique(x) Parameters: x: vector, data frame, array or NULL Example 1: # R program to illustrate # unique function # Initializing some set of numbers x <- c(1:10, 5:9) x # Calling unique() function to print # unique set of number
1 min read
Get the Maximum element of an Object in R Programming - max() Function
max() function in R Language is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc.. Syntax: max(object, na.rm) Parameters: object: Vector, matrix, list, data frame, etc. na.rm: Boolean value to remove NA element. Example 1: # R program to illustrate # the use of max() function #
1 min read
Get the Minimum element of an Object in R Programming - min() Function
min() function in R Language is used to find the minimum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc.. Syntax: min(object, na.rm) Parameters: object: Vector, matrix, list, data frame, etc. na.rm: Boolean value to remove NA element. Example 1: # R program to illustrate # the use of min() function #
1 min read
Display the internal Structure of an Object in R Programming - str() Function
str() function in R Language is used for compactly displaying the internal structure of a R object. It can display even the internal structure of large lists which are nested. It provides one liner output for the basic R objects letting the user know about the object and its constituents. It can be used as an alternative to summary() but str() is m
3 min read
Calculate Cumulative Sum of a Numeric Object in R Programming - cumsum() Function
The cumulative sum can be defined as the sum of a set of numbers as the sum value grows with the sequence of numbers. cumsum() function in R Language is used to calculate the cumulative sum of the vector passed as argument. Syntax: cumsum(x) Parameters: x: Numeric Object Example 1: C/C++ Code # R program to illustrate # the use of cumsum() Function
1 min read
Search and Return an Object with the specified name in R Programming - get() Function
get() function in R Language is used to return an object with the name specified as argument to the function. This is another method of printing values of the objects just like print function. This function can also be used to copy one object to another. Syntax: get(object) Parameters: object: Vector, array, list, etc. Example 1: # R program to ill
1 min read
Sort elements of an Object by its Index Values in R Programming - order() function
order() function in R Language is used to sort an object by its index value. These objects can be vector, matrix or data frames. This function accepts boolean value as argument to sort in ascending or descending order. Syntax: order(x, decreasing, na.last) Parameters: x: Vector to be sorted decreasing: Boolean value to sort in descending order na.l
1 min read
Calculate the Mean of each Row of an Object in R Programming – rowMeans() Function
rowMeans() function in R Language is used to find out the mean of each row of a data frame, matrix, or array. Syntax: rowMeans(data) Parameter: data: data frame, array, or matrix Example 1 # R program to illustrate # rowMean function # Create example values # Set seed set.seed(1234) # Create example data data <- data.frame(matrix(round(runif(12,
1 min read
Get or Set names of Elements of an Object in R Programming - names() Function
names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named. Syntax: names(x) <- value Para
2 min read
Convert an Object to List in R Programming - as.list() Function
as.list() function in R Programming Language is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and dataframes. Syntax: as.list(object) Parameters: object: Vector, Matrix, factor, or data frame R - as.list() Function ExampleExample 1: Converting Vector to list using as.list() function in R Language C/C++ Code #
2 min read
Convert an Object to Data Frame in R Programming - as.data.frame() Function
as.data.frame() function in R Programming Language is used to convert an object to data frame. These objects can be Vectors, Lists, Matrices, and Factors. Syntax: as.data.frame(object) Parameters: object: Vector, Matrix, factor, or data frameR - as.data.frame() Function ExampleExample 1: Basic example of as.data.frame() Function in R C/C++ Code # R
2 min read
Check if the Object is a Matrix in R Programming - is.matrix() Function
is.matrix() function in R Language is used to return TRUE if the specified data is in the form of matrix else return FALSE. Syntax: is.matrix(x) Parameters: x: specified matrix Example 1: # R program to illustrate # is.matrix function # Specifying some different types of arrays A <- matrix(c(1:5)) B <- matrix(c(1:12), nrow = 4, byrow = TRUE)
1 min read
Check if the Object is a Data Frame in R Programming - is.data.frame() Function
is.data.frame() function in R Language is used to return TRUE if the specified data type is a data frame else return FALSE. R data.frame is a powerful data type, especially when processing table (.csv). It can store the data as row and columns according to the table. Syntax: is.data.frame(x) Parameters: x: specified data.frame Example 1: # R progra
1 min read
Check if the Object is a List in R Programming - is.list() Function
is.list() function in R Language is used to return TRUE if the specified data is in the form of list, else returns FALSE. Syntax: is.list(X) Parameters: x: different types of data storage Example 1: # R program to illustrate # is.list function # Initializing some list a <- list(1, 2, 3) b <- list(c("Jan", "Feb", "Mar
1 min read
Check if an Object of the Specified Name is Defined or not in R Programming - exists() Function
exists() function in R Programming Language is used to check if an object with the names specified in the argument of the function is defined or not. It returns TRUE if the object is found. Syntax: exists(name) Parameters: name: Name of the Object to be searchedexists() Function in R Language ExampleExample 1: Apply exists() Function to variable C/
2 min read
Check if an Object is of Type Character in R Programming - is.character() Function
is.character() function in R Language is used to check if the object passed to it as argument is of character type. Syntax: is.character(x) Parameters: x: Object to be checked Example 1: # R program to check if # object is a character # Creating a vector x1 <- 4 x2 <- c("a", "b", "c", "d") x3 <- c(1,
1 min read
Check if an Object is of Type Integer in R Programming - is.integer() Function
is.integer() function in R Language is used to check if the object passed to it as argument is of integer type. Syntax: is.integer(x) Parameters: x: Object to be checked Example 1: # R program to check if # object is an integer # Creating a vector x1 <- 4L x2 <- c(1:6) x3 <- c("a", "b", "c", "d") x4
1 min read
Check if an Object is of Type Numeric in R Programming - is.numeric() Function
is.numeric() function in R Language is used to check if the object passed to it as argument is of numeric type. Syntax: is.numeric(x) Parameters: x: Object to be checked Example 1: # R program to check if # object is of numeric type # Calling is.numeric() function is.numeric(1) is.numeric(1.5) is.numeric(-1.5) Output: [1] TRUE [1] TRUE [1] TRUE Exa
1 min read
Check if an Object is of Complex Data Type in R Programming - is.complex() Function
is.complex() function in R Language is used to check if the object passed to it as argument is of complex data type. Syntax: is.complex(x) Parameters: x: Object to be checked Example 1: # R program to check if # object is of complex type # Calling is.complex() function is.complex(1 + 0i) is.complex(1.5 + 2i) is.complex(-1.5 + 2i) Output: [1] TRUE [
1 min read
Article Tags :
three90RightbarBannerImg