What is object-oriented programming (OOP) in R?

Overview

The R programming language uses object-oriented programming (OOP) concepts. OOP in R deals mainly with the objects and classes, which are the main tools used to manage the complex nature of the language.

Classes and objects

We can think of a class as a computer system and an object as the components that make up the computer system, including a visual display unit, a mouse, and a keyboard.

These components (the objects) make up a computer system (the class). An object such as the mouse has certain attributes such as weight, size, and color. It also has certain operating methods, such as clicking or scrolling. In summary, an object is an instance of a class that has attributes (object attributes) and can also be used to perform certain operations (methods). This is what OOP is all about.

Objects in R

Objects in R are simply a term used for the data types in R for various operations and functionalities, just like the mouse is used for clicking and scrolling. In R programming language, there are six basic types of objects. They include:

  1. Matrix: This is a type of data object that is used to store elements of the same data type in a two-dimensional layout. To know more about Matrix in R, click on this Answer.
  2. Lists: This is a data object that includes strings, vectors, numbers, matrices, functions, and so on as its elements. To know more about a list in R, click on this Answer.
  3. Vectors: This data object contains a sequence of elements of the same data types. Some elements include logical (Boolean), character, complex, double, integer, or raw data types. To know more about vectors, click on this Answer.
  4. Arrays: Arrays in R, like a matrix, are used to store elements of the same data types in more than two dimensions. To know more about arrays in R, click on this Answer.
  5. Dataframe: This data object of a two-dimensional structure contains rows and columns. These columns and rows contain values of a variable. To know more about dataframes in R, click on this Answer.
  6. Factors: This is a data object that contains strings or integers used to categorize data. To know more about factors in R, click on this Answer.

Code examples of objects

In the code below, we'll create six object types in R:

# A code to illustrate how R objects are created
# creating a Matrix
# using the matrix() function to create a matrix
my_matrix <- matrix(
c(1,2,3,4,5,6), #data
nrow = 2, # number of rows
ncol = 2, # number of columns
byrow = FALSE, # matrix filling
dimname = list(
c("row1", "row2"),
c("Col1", "Col2")
) # names of rows and columns
)
my_matrix
# creating a list
my_list <- list("Apple", "Mango", FALSE, 10.5)
my_list
# creating a Vector
my_vector <- c(1, 2, 3, 4, 5)
my_vector
# creating an Array
my_array <- array(1:6, dim = c(2, 3, 2))
my_array
# creating a DataFrame
my_dataframe <- data.frame(col1 = c("A", "B"), col2 = c(1, 2))
my_dataframe
# creating a factor
my_factor <- factor(c("Tall", "Average", "Short"))
my_factor

Classes in R

There are basically two types of classes in R programming language:

  1. S3 class
  2. S4 class

The S3 classes

The S3 classes are the most popular classes in R programming language. The implementation of this class does not require much knowledge of programming.

Create an object in the S3 class

To create an object in the S3 class:

  • We create a list representing the object of the class.
  • We pass this object (the list) as an argument of the class() function. The value is assigned to a class name.

Syntax

# creating a list of attributes for the object
my_object <- list(attribute_1, attribute_2)
# defining a class name for the object using the class() function
class(my_object) <- "class_name"
# creating the object
my_object

Explanation

  • Line 2 : We create a list of attributes of the object my_object.
  • Line 5: We define the object's class name using the class() function.
  • Line 8: We create and print the object.

Code example 1

In the code below, we create an object, computer_mouse, which we’ll assign to a list containing its attributes. To print this object we created, we pass it as an argument to the class() function.

# A code illustrating how an object of S3 class is being created
# creating a list of attributes for the object, computer_mouse
computer_mouse <- list(name = "Dell", size = "small", color = "black", weight =119)
# defining a class for the object
class(computer_mouse) <- "computer_system"
# creating the object
computer_mouse

Code explanation

  • Line 4: We create a list of attributes of an object, computer_mouse.
  • Line 7: We define a class name for the object using the class() function.
  • Line 10: We print the object.

Generic functions in the S3 class

A generic function contains one or more functions that implement a particular operation depending on the input type.

Syntax

generic_function.class_name <- function(object{
operation(object$object_attributes )
})
Syntax for creating a generic function

Code explanation

  • generic_function: This represents the name for the generic function.
  • .class_name: This takes the name of the class you created.
  • operation: This is the particular method or operation you wish to perform.
  • object$: This is used to access the attributes of the object created.
  • object_attributes: This represents a specified name of the attributes of the objects created.

Code explanation

In continuation with the previous code where we created an S3 class named "computer_system", we will create a generic function, print(), which will help us print any specified attribute of the object, computer_mouse, by using the operation or method cat().

# A code to illustrate how to create a generic function
# below is the syntax we will replicate
# generic_function.class_name <- function(my_object{
# operation(my_object$object_attributes )
# })
# creating the generic function
print.Computer_system <- function(object) {
cat("The color of the computer mouse is: ", object$color, "\n")
cat("The weight of the computer mouse is: ", object$weight, "\n")
}
# calling the generic function
print(computer_mouse)

Code explanation

From the code above, the generic function was able to return the object's attributes, computer_mouse.

The S4 classes

The S4 classes are not as popular as the S3 classes. The implementation or how the class works requires much more knowledge of programming. S4 classes are conventional and contain functions used to define the methods and generics. They contain multiple inheritance and multiple dispatch.

Creating an object in the S4 class

To create an object in the S4 class:

  • We use the setClass() command to define a class.
  • We pass the name of the class and the definition for its slots.
  • Once the class has been created, the new() function is called to construct an object of the class.

Syntax

Creating an object from an S4 class takes the syntax below:

# create a class using the setClass() function
setClass("class_name", slots=list(value_1, value_2))
# construct an object using the new() function
object_name <- new("class_name", value_1, value_2)
Syntax for creating an object from S4 class

Explanation

  • Line 2: We use the setClass() command to define a class named "class_name" and as well a list of slot values (value_1 and value_2) of the desired object.
  • Line 4: We construct an object, "object_name", using the new() function.

We will illustrate this syntax using a suitable example in the code example section below:

Code example

# A code to illustrate how to create an object of S4 class
# to create S4 class containing the class name and list of slots.
my_class <- setClass("computer_system", slots=list(name="character",
weight="numeric"))
# constructing an object
computer_mouse <- new("computer_system", name="DELL", weight=119)
# Calling object
computer_mouse

Code explanation

  • Lines 4-5: We create a class "computer_system" and a list of sort for the desired object of the class.
  • Line 8: We create an object, computer_mouse, using the new() function.
  • Line 11: We call the object computer_mouse.

Code output

An object of class "Computer_system"
Slot "name":
[1] "Adam"
Slot "weight":
[1] 119
Output of the code

Generic functions in S4 classes

The generic function can help us perform a particular operation based on the input type.

Syntax

The syntax to use when creating a generic function for the S4 class is shown below:

setMethod("show", "class_name", function(object){
operation(object@value_1)
})
Syntax to use when creating an S4 class

Explanation

  • setMethod: This is used to define a generic function.
  • show: This is a generic function.
  • class_name: This is the name of the class.
  • operation: This is the operation we wish to perform using the function.
  • object@vlaue_1: object@ is used to access the value of slots value_1.

Code example

# A code to illustrate how a generic function is created for an S4 class
# creating the S4 class
my_class <- setClass("computer_system", slots=list(name="character",
weight="numeric"))
# constructing an object of the class
computer_mouse <- new("computer_system", name="DELL", weight=119)
# creating a generic function for the class
setMethod("show", "computer_System",
function(object){
cat(obj@name, "\n")
cat(obj@age, "\n")
})
# calling the function
show(computer_mouse)

Code explanation

  • Lines 4-5: We create a class "computer_system" and a list of sort for the desired object of the class.
  • Line 8: We create an object, computer_mouse, using the new() function.
  • Line 11-15: We create a generic function, show(), for the class using setMethod(). This function will perform the cat() operation while the slot values of the object are accessed using @.
  • Line 17: We call the show() function and pass the object computer_mouse as the parameter value.

Code output

An object of class "computer_system"
Slot "name":
[1] "DELL"
Slot "weight":
[1] 119
Output of the code

The code output above shows the result printed in a form with the slot names, along with their respective values.