Saturday, November 28, 2020

What is Object-Oriented Programming in R? Provide examples

 Object-Oriented Programming (OOP) is the most popular programming language. With the help of oops concepts, we can construct the modular pieces of code which are used to build blocks for large systems. R is a functional language, and we can do programming in oops style. In R, oops is a great tool to manage the complexity of larger programs.

R Object Oriented Programming

In Object-Oriented Programming, S3 and S4 are the two important systems.

S3

In oops, the S3 is used to overload any function. So that we can call the functions with different names and it depends on the type of input parameter or the number of parameters.

S4

S4 is the most important characteristic of oops. However, this is a limitation, as it is quite difficult to debug. There is an optional reference class for S4.

Objects and Classes in R

In R, everything is an object. Therefore, programmers perform OOPS concept when they write code in R. An object is a data structure which has some methods that can act upon its attributes.

In R, classes are the outline or design for the object. Classes encapsulate the data members, along with the functions. In R, there are two most important classes, i.e., S3 and S4, which play an important role in performing OOPs concepts.

Let's discuss both the classes one by one with their examples for better understanding.

1) S3 Class

With the help of the S3 class, we can take advantage of the ability to implement the generic function OO. Furthermore, using only the first argument, S3 is capable of dispatching. S3 differs from traditional programming languages such as Java, C ++, and C #, which implement OO passing messages. This makes S3 easy to implement. In the S3 class, the generic function calls the method. S3 is very casual and has no formal definition of classes.

S3 requires very little knowledge from the programmer.

Creating an S3 class

In R, we define a function which will create a class and return the object of the created class. A list is made with relevant members, class of the list is determined, and a copy of the list is returned. There is the following syntax to create a class

  1. variable_name <- list(member1, member2, member3.........memberN)  

Example

  1. <- list(name = "Ram"age = 29GPA = 4.0)  
  2. class(s) <- "Faculty"  
  3. s  

Output

R Object Oriented Programming

There is the following way in which we define our generic function print.

  1. print  
  2. function(x, ...)  
  3. UseMethod("Print")  

When we execute or run the above code, it will give us the following output:

R Object Oriented Programming

Like print function, we will make a generic function GPA to assign a new value to our GPA member. In the following way we will make the generic function GPA

  1. GPA <- function(obj1){  
  2. UseMethod("GPA")  
  3. }  

Once our generic function GPA is created, we will implement a default function for it

  1. GPA.default <- function(obj){  
  2. cat("We are entering in generic function\n")  
  3. }  

After that we will make a new method for our GPA function in the following way

  1. GPA.faculty <- function(obj1){  
  2. cat("Final GPA is ",obj1$GPA,"\n")  
  3. }  

And at last we will run the method GPA as

  1. GPA(s)  

Output

R Object Oriented Programming

Inheritance in S3

Inheritance means extracting the features of one class into another class. In the S3 class of R, inheritance is achieved by applying the class attribute in a vector.

For inheritance, we first create a function which creates new object of class faculty in the following way

  1. faculty<- function(n,a,g) {  
  2. value <- list(nname=n, aage=a, GPA=g)  
  3. attr(value, "class") <- "faculty"  
  4. value  
  5. }  

After that we will define a method for generic function print() as

  1.  print.student <- function(obj1) {  
  2. cat(1obj$name, "\n")  
  3. cat(1obj$age, "years old\n")  
  4. cat("GPA:", obj1$GPA, "\n")  
  5. }  

Now, we will create an object of class InternationalFaculty which will inherit from faculty class. This process will be done by assigning a character vector of class name as:

  1. class(Objet) <- c(child, parent)  

so,

  1. # create a list  
  2. fac <- list(name="Shubham"age=22GPA=3.5, country="India")  
  3. # make it of the class InternationalFaculty which is derived from the class Faculty  
  4. class(fac) <- c("InternationalFaculty","Faculty")  
  5. # print it out  
  6. fac  

When we run the above code which we have discussed, it will generate the following output:

R Object Oriented Programming

We can see above that, we have not defined any method of form print. InternationalFaculty (), the method called print.Faculty(). This method of class Faculty was inherited.

So our next step is to defined print.InternationalFaculty() in the following way:

  1. print.InternationalFaculty<- function(obj1) {  
  2. cat(obj1$name, "is from", obj1$country, "\n")  
  3. }  

The above function will overwrite the method defined for class faculty as

  1. Fac  


R Object Oriented Programming

getS3method and getAnywhere function

There are the two most common and popular S3 method functions which are used in R. The first method is getS3method() and the second one is getAnywhere().

S3 finds the appropriate method associated with a class, and it is useful to see how a method is implemented. Sometimes, the methods are non-visible, because they are hidden in a namespace. We use getS3method or getAnywhere to solve this problem.

getS3method

R Object Oriented Programming

getAnywhere function

  1. getAnywhere("simpleloess")  

2) S4 Class

The S4 class is similar to the S3 but is more formal than the latter one. It differs from S3 in two different ways. First, in S4, there are formal class definitions which provide a description and representation of classes. In addition, it has special auxiliary functions for defining methods and generics. The S4 also offers multiple dispatches. This means that common functions are capable of taking methods based on multiple arguments which are based on class.

Creating an S4 class

In R, we use setClass() command for creating S4 class. In S4 class, we will specify a function for verifying the data consistency and also specify the default value. In R, member variables are called slots.

To create an S3 class, we have to define the class and its slots. There are the following steps to create an S4 class

Step 1:

In the first step, we will create a new class called faculty with three slots name, age, and GPA.

  1. setClass("faculty", slots=list(name="character"age="numeric"GPA="numeric"))  

There are many other optional arguments of setClass() function which we can explore by using ?setClass command.

R Object Oriented Programming

Step 2:

In the next step, we will create the object of S4 class. R provides new() function to create an object of S4 class. In this new function we pass the class name and the values for the slots in the following way:

  1. setClass("faculty", slots=list(name="character"age="numeric"GPA="numeric"))  
  2. # creating an object using new()  
  3. # providing the class name and value for slots  
  4. <- new("faculty",name="Shubham"age=22GPA=3.5)  
  5. s  

It will generate the following output

R Object Oriented Programming

Creating S4 objects using a generator function

The setClass() function returns a generator function. This generator function helps in creating new objects. And it acts as a constructor.

  1. <- setClass("faculty", slots=list(name="character"age="numeric"GPA="numeric"))  
  2. A  

It will generate the following output:

R Object Oriented Programming

Now we can use the above constructor function to create new objects. The constructor in turn uses the new() function to create objects. It is just a wrap around. Let's see an example to understand how S4 object is created with the help of generator function.

Example

  1. faculty<-setClass("faculty", slots=list(name="character"age="numeric"GPA="numeric"))  
  2. # creating an object using generator() function  
  3. # providing the class name and value for slots  
  4. faculty(name="Shubham"age=22GPA=3.5)  

Output

R Object Oriented Programming

Inheritance in S4 class

Like S3 class, we can perform inheritance in S4 class also. The derived class will inherit both attributes and methods of the parent class. Let's start understanding that how we can perform inheritance in S4 class. There are the following ways to perform inheritance in S4 class:

Step 1:

In the first step, we will create or define class with appropriate slots in the following way:

  1. setClass("faculty",  
  2. slots=list(name="character"age="numeric"GPA="numeric")  
  3. )  

Step 2:

After defining class, our next step is to define class method for the display() generic function. This will be done in the following manner:

  1. setMethod("show",  
  2. "faculty",  
  3. function(obj) {  
  4. cat(obj@name, "\n")  
  5. cat(obj@age, "years old\n")  
  6. cat("GPA:", obj@GPA, "\n")  
  7. }  
  8. )  

Step 3:

In the next step, we will define the derived class with the argument contains. The derived class is defined in the following way

  1. setClass("Internationalfaculty",  
  2. slots=list(country="character"),  
  3. contains="faculty"  
  4. )  

In our derived class we have defined only one attribute i.e. country. Other attributes will be inherited from its parent class.

  1. <- new("Internationalfaculty",name="John"age=21GPA=3.5, country="India")  
  2. show(s)  


R Object Oriented Programming

When we did show(s), the method defines for class faculty gets called. We can also define methods for the derived class of the base class as in the case of the S3 system.

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...