Object Oriented Programming (OOP) in R | Create R Objects & Classes

In this R tutorial, we are going to discuss one of the most important concepts i.e. Object Oriented Programming in R. We will discuss the concept of objects and classes in R language, the process to create S3 and S4 classes, inheritance in these classes and its methods in the R programming language.

What is Object Oriented Programming in R?

Object Oriented Programming (OOP) is a popular programming language. Using its concepts, we can construct the modular pieces of code that can be used to build blocks for large systems. R is a functional language. The support also exists for programming in an OOP style. Object Oriented Programming in R is a superb tool to manage complexity in larger programs. It particularly suits for GUI development.

S3 and S4 are the two important systems in Object Oriented Programming:

  • S3 is used to overload any function. Therefore, we can call different names of the function. And, it depends upon the type of input parameter or the number of a parameter.
  • An important characteristic of OOP is S4. However, it poses a limitation as it is quite tricky to debug. An alternate for the S4 is the reference class.

Understand the R Programming Functions thoroughly

What are Objects and Classes in R?

  • Programmers can perform OOP programming in R. That is, everything in R is an object.
  • An object is a data structure. It has some methods that can act upon its attributes.
  • Classes are used as an outline or design for the object. It encapsulates the data members along with the functions.

Classes in R

1. S3 Class

With the help of the S3 class, you can avail its ability to implement generic function OO. Also, using only the first argument, S3 is able to dispatch. S3 is different from conventional programming languages like Java, C++, and C# that implement message passing OO. This makes S3 easier to implement. In S3 class, the generic function makes the call to the method. S3 is very casual and does not have any formal definition of classes.

S3 requires very less knowledge on the part of the programmer.

2. S4 Class

S4 Class is a bit similar to S3 but it is more formal than the latter. It differs from S3 in two different ways. Firstly, in S4, there are formal class definitions that provide description and representation of classes. Furthermore, it has special helper functions for defining methods and generics. S4 also facilitates multiple dispatches. This means that the generic functions are able to pick up methods based on the class comprising of multiple arguments.

Let’s understand these R classes with the help of examples.

1.1 Creating an S3 class

We will show how to define a function that will create and return an object of a given class. A list is created with the relevant members, the list’s class is set, and a copy of the list is being returned.

1.2 Constructing a new S3 class

s <- list(name = "DataFlair", age = 29, GPA = 4.0)
class(s) <- "student"
s

Output:

s list

Let us now define our generic function print.

print
function (x, ...) 
UseMethod("print")

Output:

print function UseMethod

Now, we will make a generic function – GPA

GPA <- function(obj) {
UseMethod("GPA")
}

Let us now implement a default method for our GPA function –

GPA.default <- function(obj) {
cat("This is a generic function\n")
}

Now, we will make a new method for the class “student”

GPA.student <- function(obj) {
cat("Total GPA is", obj$GPA, "\n")
}

Now, let us run this method.

GPA(s)

Output:

GPA function obj 1

Wait! Have you checked the R Vector Functions

1.3 Inheritance in S3

In S3, inheritance is achieved by applying the class attribute in a vector.

For example:

> fit <- glm(rpois(100, lambda = 1) ~
+ 1, family = "poisson")
> class(fit)
> methods("residuals")
> methods("model.matrix")[/php]

Output:

fit glm

If no method is found for the first class, the second class is checked.

1.4 Useful S3 method functions

  • getS3method(“print”,”person”)
  • getAnywhere

S3 gets the appropriate method associated with a class and it is useful to see how a method is implemented.

Sometimes, methods are non-visible, because they are hidden in a namespace. We use getS3method or getAnywhere to resolve this issue.

getS3method:

require(stats)
exists("predict.ppr") # False
getS3method("predict", "ppr") #DataFlair

Output:

require stats

getAnywhere:

getAnywhere(“simpleloess”)

You must know the Principal Components and Factor Analysis in R

S4 Class

2.1 Creating an S4 class

We use setClass() command to create S4 class. We specify a function to verify that the data is consistent (validation) and also specify the default values (the prototype).

2.2 Constructing a new S4 class

We have to define the class and its slots, and the code to define the class is as follows:

Agent <- setClass(
 # Set the name for the class
 "Agent",

 # Define the slots
 slots = c(
   location = "numeric",
   velocity   = "numeric",
   active   = "logical"
 ),

 # Set the default values for the slots. (optional)
 prototype=list(
   location = c(0.0,0.0),
   active   = TRUE,
   velocity = c(0.0,0.0)
 ),

 # Make a function that can test to see if the data is consistent.
 # This is not called if you have an initialize function defined!
 validity=function(object)
 {
   if(sum(object@velocity^2)>100.0) {
     return("The velocity level is out of bounds.")
   }
   return(TRUE)
 }
)

Output:

Agent setClass output

We can create an object whose class is Agent, as the code to define the class is as follows:

a <- Agent()
> a

Output:

a Agent

We can obtain details about the elements using the SlotNames command as follows:

is.object(a)
> isS4(a)
> slotNames(a)
> slotNames("Agent")

Output:

is.object a - Object Oriented Programming in R

There are two functions is.object and the isS4 commands.

  • We use is.object command to determine whether a variable refers to an object or not.
  • We use the isS4 command to determine whether a variable is an S4 object or not.
  • The importance of the commands is that the isS4 command alone cannot determine that a variable is an S3 object. First, we need to determine whether the variable is an object and then decide if it is S4 or not.

In an object, we use a set of commands to get information about the data elements, or slots within an object. The first is the slotNames command which can take either an object or the name of a class. We obtain names of slots that are related to the class as strings.

> slotNames(a)
> slotNames("Agent")

Output:

slotNames a - Object Oriented Programming in R

 

Do you know about R String Manipulation Functions

The getSlots and slotNames command are similar as they both take the name of a class as a string. We obtain a vector in return whose entries consist of the types associated with slots. The names of the entries are the names of the slots.

> getSlots("Agent")
location  velocity    active
"numeric" "numeric" "logical"
> s <- getSlots("Agent")
> s[1]
location
"numeric"
> s[[1]]
> names(s)

Output:

getSlots agent

The next command which we will examine is the getClass command. It has two forms. If you assign S4 class as a variable it returns a list of slots for the class associated with the variable. Another, if you assign a character string with the name of a class it gives the slots and their data types.

> getClass(a)
An object of class "Agent"
Slot "location":
Slot "velocity":
Slot "active":
> getClass("Agent")
Class "Agent" [in ".GlobalEnv"]
Slots:
Name:  location velocity   active
Class:  numeric  numeric  logical

Output:

getClass a

The final command for examining is the slot command. In an object to set the value of slot, we can use slot command. “@” operator is used at the place of slot command.

slot(a,"location")
> slot(a,"location") <- c(1,5)
> a

Output:

slot a location

Summary

Classes and objects are the most important concepts of Object Oriented Programming language(OOP). We tried to describe the Object Oriented Programming in R in great detail.

The secret to crack your R Interview – R Programming Interview Questions

If in case you have any questions, feel free to share with us. We will be glad to solve your queries.

No Responses

  1. anuj says:

    Hi,
    I am an MBA background (marketing) with having no technical background before that has been working in Digital marketing industry(playing with data, business growth n all), I have joined a data science classes. I want to know how difficult would it be for non-technical candidates when in comes to talk about data sciences jobs??

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.