Object Oriented Programming in R | R Object & Classes

1. Object Oriented Programming in R – Objective

In this R tutorial we are going to discuss the most important concept i.e. Object Oriented Programming in R. In this topic we will discuss Introduction to Object Oriented Programming, what is the concept of Objects and Class in R language, How to Create S3 and S4 classes in R Programming. We will also cover the inheritance in S3 and S4 classes in R, methods of S3 and S4 classes in the R programming language.

Object Oriented Programming in R | R Object & Classes

Object Oriented Programming in R | R Object & Classes

2. What is Object Oriented Programming in R?

Object-oriented programming (OOP) is a popular programming language. It allows us to construct modular pieces of code which are used as building blocks for large systems. R is a functional language. It also supports exists for programming in an object-oriented style. Object oriented programming in Ris a superb tool to manage complexity in larger programs. It is particularly suited to GUI development.
There are two systems in Object oriented programming in R, known as S3 and S4.

  • S3 is being used to overload any function. It means calling a different name of the function. It depends upon the type of input parameter or the number of a parameter).
  • The S4 is a characteristic OOP system, but it is tricky to debug.
  • Reference classes are the modern alternative for S4 classes.

3. What are Objects and Classes in R?

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

4. Classes in R

Let’s discuss the R classes with the help of examples.

i. S3 class

Creating an S3 class

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

Constructing a new S3 class

For Example:

> jim <- list(height = 2.54 * 12 * 6/100, weight = 180/2.2,+ name = "James")
> class(jim) <- "person"
> class(jim)

We have now made an object of class person
We now define a print method.
> print(jim)
> print.person <- function(x, ...) {
+ cat("name:", x$name, "\n")
+ cat("height:", x$height, "meters", "\n")
+ cat("weight:", x$weight, "kilograms", "\n")
+ }
> print(jim)

Note the method/class has the ”dot” naming convention of method.class.

a. Inheritance in S3

In S3, inheritance is achieved by the class attribute is a vector.
For Example:

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

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

b. Useful S3 method functions

  • methods(“print”) and methods(class = “lm”)
  • getS3method(“print”,”person”)

Gets the appropriate method associated with a class, useful to see how a method is implemented.

  • Sometimes, methods are non-visible, because they are hidden in a namespace. Use getS3method or getAnywhere to get around this.

> residuals.HoltWinters
> getS3method("residuals.HoltWinters")
> getAnywhere("residuals.HoltWinters")

ii. S4 class

a. Creating an S4 class

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

b. Constructing a new S4 class

We define the class and its slots, and the code to define the class is given below:

# Create the base Agent class
# This is used to represent the most basic agent in a simulation.
Agent <- setClass(
# Set the name for the class
# Define the slots
slots = c(
location = "numeric",
velocity = "numeric",
active   = "logical"
# Set the default values for the slots. (optional)
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!
if(sum(object@velocity^2)>100.0) {
return("The velocity level is out of bounds.")

Now that the code to define the class is given we can create an object whose class is Agent.
> a <- Agent()
> a

An object of class “Agent”
Slot "location":
[1] 0 0
Slot "velocity":
[1] 0 0
Slot "active":
[1] TRUE

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

  • To determine whether or not a variable refers to an object we use is.object command.
  • We use the isS4 command to determine whether a variable is an S4 object
  • The importance of the commands is that the isS4 command alone cannot determine if 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.

> is.object(a)
[1] TRUE
> isS4(a)
[1] TRUE

In an object set of commands are used 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. It returns the names of the slots associated with the class as strings.
> slotNames(a)
[1] "location" "velocity" "active"
> slotNames("Agent")
[1] "location" "velocity" "active"

The getSlots and slotNames command are similar as they both take the name of a class as a string. It returns a vector whose entries are the types associated with the 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]
> s[[1]]
[1] "numeric"
> names(s)
[1] "location" "velocity" "active"

The next command examined 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":
[1] 0 0
Slot "velocity":
[1] 0 0
Slot "active":
[1] TRUE
> getClass("Agent")
Class "Agent" [in ".GlobalEnv"]
Name:  location velocity   active
Class:  numeric  numeric  logical

The final command examined is the slot command. In an object to set the value of slot we, can use slot command. “@” operator is been used at the place of slot command.
> slot(a,"location")
[1] 0 0
> slot(a,"location") <- c(1,5)
> a

An object of class “Agent”
Slot "location":
[1] 1 5
Slot "velocity":
[1] 0 0
Slot "active":
[1] TRUE

c. S4 Generic

The function setGeneric is call to make a new generic fuction.

> setGeneric("BMI", function(object) standardGeneric("BMI"))
> setMethod("BMI", "personS4", function(object) {
+ object@weight/object@height^2
+ })
> BMI(jimS4)

So, this was all on Object-Oriented Programming in R.

4. Conclusion – R Object-Oriented Programming

Hence, classes and objects are the most important concept of object oriented programming language. In this tutorial we have described the Object Oriented Programming in R in great detail. If in case you have any questions, so feel free to share with us. We will be happy to solve your queries.
See Also-

Reference for R 

No Responses

  1. anuj says:

    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.