0% found this document useful (0 votes)
21 views54 pages

Unit 3-1

Uploaded by

gayathrinaik12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views54 pages

Unit 3-1

Uploaded by

gayathrinaik12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

What is Object-Oriented Programming in R?

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.

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 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.

Classes in R
S3 Class
An S3 class is one of the most used classes in R. This class is easy to
implement and many predefined classes are of this type.

The object of an S3 class is a list having class attributes assigned with some
names. The component of the list is represented by the member variable of
the object.

Creating S3 Class

We can create an S3 object by the following steps −

 Make a list having the required component values.


 Then, we can create a class easily using the class() function and also
append a name to this class.

Example
Open Compiler
# Creating list
myList <- list(Name ="Bhuwanesh", Enrollment_Number = 3496303119,
Course = "Btech", Branch = "Information Technology")
# class
class(myList) <- "University"

myList

Output

$Name
[1] "Bhuwanesh"

$Enrollment_Number
[1] 3496303119

$Course
[1] "Btech"

$Branch
[1] "Information Technology"

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

Generic Function

We have generic functions in R that serve the purpose


of polymorphism (like many other oops languages: C++, Java, etc).

Polymorphism is made of two words


− poly and morphism where poly means many and morphism means
forms. It states that a single message can have more than one different form
or it can serve different purposes.

For example in R, the summary() function is a set of many summary()


functions that can be used for different data types and data structures. Such
functions invoke an adequate function depending upon the type of object
passed as an argument. We can see the various implementations of
summary() functions using the methods() function.

methods(summary)

We can create our own generic function in R. Let us consider the following
program that creates a list by the name “myList” and then creates a class out
of it.

Example

Now we display the summary of this class using the summary() function −

Open Compiler
# Create a list
myList <- list(Name ="Bhuwanesh",
Enrollment_Number = 3496303119,
Course = "Btech",
Branch = "Information Technology")

# Define the class


class(myList) <- "University"

# Display the summary


print(summary(myList))
Output

Length Class Mode


Name 1 -none- character
Enrollment_Number 1 -none- numeric
Course 1 -none- character
Branch 1 -none- character

Attributes

The attribute is a piece of extra information associated with an object and


used to handle the object. We can use the attributes() function to get the
attributes of an object.

Example

Let us consider the following program illustrating the working of this function

Open Compiler
# Create a list
myList <- list(Name ="Bhuwanesh",
Enrollment_Number = 3496303119,
Course = "Btech",
Branch = "Information Technology")

# Define a class
class(myList) <- "University"

# Display attributes
print(attributes(myList))

Output

$names
[1] "Name" "Enrollment_Number" "Course"
[4] "Branch"

$class
[1] "University"
We can also apply our own attributes to an object with the help of the attr()
function Let us consider the following illustrating the working of this function

Example
Open Compiler
# Create a list
myList <- list(Name ="Bhuwanesh",
Enrollment_Number = 3496303119,
Course = "Btech",
Branch = "Information Technology")

# Define class
class(myList) <-"University"

# Defining custom attributes


attr(myList,"Grade")<-c('A')

# Display attribute
print(attributes(myList))

Output

$names
[1] "Name" "Enrollment_Number" "Course"
[4] "Branch"

$class
[1] "University"

$Grade
[1] "A"

Inheritance in S3 Class

Inheritance is one of the most important pillars of object-oriented


programming language which allow one class to inherit the properties of
another class. This feature leads to benefits like code-reusability.
The S3 class doesn’t contain any particular pattern for its definition.

Example
Open Compiler
# Create a list
myList1 <- list(Name ="Bhuwanesh", Enrollment_Number = 3496303119,
Course = "Btech", Branch = "Information Technology")

# Define the class


class(myList1) <- "University"

# Create a list
myList2 <- list(College_Rank = 14, State = 'Uttarakhand')

# Define the inheritance relation


class(myList2) <- c("College", "University")

print(myList2)

Output

$College_Rank
[1] 14

$State
[1] "Uttarakhand"

attr(,"class")
[1] "College" "University"

As you can see in the output, class “College” inherits the class “University”.

Example

Now let us try to access and modify the components of the base class
“University” using an object of the base class “College” −

Open Compiler
# Create a list
myList1 <- list(Name ="Bhuwanesh", Enrollment_Number = 3496303119,
Course = "Btech", Branch = "Information Technology")

# Define a class
class(myList1) <- "University"

myList2 <- list(College_Rank = 14, State = 'Uttarakhand')

class(myList2) <- c("College", "University")

# Define the attribute


myList2$Name = "Harshit"

print(myList2)

Output

$College_Rank
[1] 14

$State
[1] "Uttarakhand"

$Name
[1] "Harshit"

attr(,"class")
[1] "College" "University"

You can see in the output, the “Name” property has been modified to
“Harshit”.

S4 Class

R allows us to use another peculiar type of class known as the “S4” class.
This class contains the predefined definition. This class contains functions to
define methods and generics. This class also provides us with auxiliary
functions to define generics and methods.

The setClass() function creates an S4 class. R provides us the new() function


which is used to create an object of the S4 class −
Example

# Define a list
myList1 <- list(Name ="Bhuwanesh",
Enrollment_Number = 3496303119,
Course = "Btech",
Branch = "Information Technology")

# Set the class


setClass("University", slots = list(Name ="character",
Enrollment_Number = "numeric",
Course = "character",
Branch = "character"))

# Define the object


myObject <- new("University",
Name = "Bhuwanesh Nainwal",
Enrollment_Number = 3496303119,
Course = "Btech",
Branch = "Information Technology")

print(myObject)

Output

An object of class "University"


Slot "Name":
[1] "Bhuwanesh Nainwal"

Slot "Enrollment_Number":
[1] 3496303119

Slot "Course":
[1] "Btech"

Slot "Branch":
[1] "Information Technology"

Inheritance in S4 class
Inheritance is one of the most important pillars of object-oriented
programming language which allow one class to inherit the properties of
another class. This feature leads to benefits like code-reusability.

The S4 class contains a proper pattern for its definition. The derived classes
are capable enough to inherit attributes and methods from the base class. In
order to achieve this we can

Example

# Set class
setClass("University",
slots = list(Name = "character",
Enrollment_Number = "numeric",
Branch = "character")
)

# Set methods
setMethod("show", "University",
function(object){
cat(object@Name, "")
cat(object@Enrollment_Number, "")
cat(object@Branch, "")
}
)

# Inherit
setClass("College",
slots = list(Grade= "character"),
contains = "University"
)
# Define the object
object <- new("College", Name = "Bhuwanesh Nainwal",
Branch="Information Technology",
Enrollment_Number = 3496303119)

# Display the object


show(object)
Output

Bhuwanesh Nainwal
3496303119
Information Technology

R Reference Class
How to define a reference class?
Defining reference class is similar to defining a S4 class. Instead
of setClass() we use the setRefClass() function.

> setRefClass("student")

Member variables of a class, if defined, need to be included in the class


definition. Member variables of reference class are called fields (analogous
to slots in S4 classes).

Following is an example to define a class called student with 3


fields, name , age and GPA .

> setRefClass("student", fields = list(name = "character", age =


"numeric", GPA = "numeric"))

How to create a reference objects?


The function setRefClass() returns a generator function which is used to
create objects of that class.
> student <- setRefClass("student",
fields = list(name = "character", age = "numeric", GPA = "numeric"))
> # now student() is our generator function which can be used to create
new objects
> s <- student(name = "John", age = 21, GPA = 3.5)
> s
Reference class object of class "student"
Field "name":
[1] "John"
Field "age":
[1] 21
Field "GPA":
[1] 3.5

How to access and modify fields?


Fields of the object can be accessed using the $ operator.

> s$name
[1] "John"
> s$age
[1] 21
> s$GPA
[1] 3.5

Similarly, it is modified by reassignment.

> s$name <- "Paul"


> s
Reference class object of class "student"
Field "name":
[1] "Paul"
Field "age":
[1] 21
Field "GPA":
[1] 3.5
Warning Note

In R programming, objects are copied when assigned to new variable or


passed to a function (pass by value). For example.

> # create list a and assign to b


> a <- list("x" = 1, "y" = 2)
> b <- a
> # modify b
> b$y = 3
> # a remains unaffected
> a
$x
[1] 1
$y
[1] 2
> # only b is modified
> b
$x
[1] 1
$y
[1] 3

But this is not the case with reference objects. Only a single copy exist and
all variables reference to the same copy. Hence the name, reference.

> # create reference object a and assign to b


> a <- student(name = "John", age = 21, GPA = 3.5)
> b <- a
> # modify b
> b$name <- "Paul"
> # a and b both are modified
> a
Reference class object of class "student"
Field "name":
[1] "Paul"
Field "age":
[1] 21
Field "GPA":
[1] 3.5
> b
Reference class object of class "student"
Field "name":
[1] "Paul"
Field "age":
[1] 21
Field "GPA":
[1] 3.5

This can cause some unwanted change in values and be the source of
strange bugs. We need to keep this in mind while working with reference
objects. To make a copy, we can use the copy() method made availabe to
us.

> # create reference object a and assign a's copy to b


> a <- student(name = "John", age = 21, GPA = 3.5)
> b <- a$copy()
> # modify b
> b$name <- "Paul"
> # a remains unaffected
> a
Reference class object of class "student"
Field "name":
[1] "John"
Field "age":
[1] 21
Field "GPA":
[1] 3.5
> # only b is modified
> b
Reference class object of class "student"
Field "name":
[1] "Paul"
Field "age":
[1] 21
Field "GPA":
[1] 3.5
Reference Methods
Methods are defined for a reference class and do not belong to generic
functions as in S3 and S4 classes.

All reference class have some methods predefined because they all are
inherited from the superclass envRefClass .

> student
Generator for class "student":
Class fields:
Name: name age GPA
Class: character numeric numeric
Class Methods:
"callSuper", "copy", "export", "field", "getClass", "getRefClass",
"import", "initFields", "show", "trace", "untrace", "usingMethods"
Reference Superclasses:
"envRefClass"

We can see class methods like copy() , field() and show() in the above
list. We can create our own methods for the class.
This can be done during the class definition by passing a list of function
definitions to methods argument of setRefClass() .

student <- setRefClass("student",


fields = list(name = "character", age = "numeric", GPA = "numeric"),
methods = list(
inc_age = function(x) {
age <<- age + x
},
dec_age = function(x) {
age <<- age - x
}
)
)
In the above section of our code, we defined two methods
called inc_age() and dec_age() . These two method modify the field age .

Note that we have to use the non-local assignment operator <<- since age
isn't in the method's local environment. This is important.
Using the simple assignment operator <- would have created a local
variable called age , which is not what we want. R will issue a warning in
such case.
Here is a sample run where we use the above defined methods.

> s <- student(name = "John", age = 21, GPA = 3.5)


> s$inc_age(5)
> s$age
[1] 26
> s$dec_age(10)
> s$age
[1] 16
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. s <- list(name = "Ram", age = 29, GPA = 4.0)


2. class(s) <- "Faculty"
3. s

Output

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:

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
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=22, GPA=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:
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
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

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.

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. s <- new("faculty",name="Shubham", age=22, GPA=3.5)
5. s

It will generate the following output

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. A <- setClass("faculty", slots=list(name="character", age="numeric", GPA="numeric"))


2. A

It will generate the following output:

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=22, GPA=3.5)

Output

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. s <- new("Internationalfaculty",name="John", age=21, GPA=3.5, country="India")


2. show(s)

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.

R Classes and Objects


We can do object oriented programming in R. In fact, everything in R is an
object.

An object is a data structure having some attributes and methods which act
on its attributes.

Class is a blueprint for the object. We can think of class like a sketch
(prototype) of a house. It contains all the details about the floors, doors,
windows etc. Based on these descriptions we build the house.
House is the object. As many houses can be made from a description, we
can create many objects from a class. An object is also called an instance
of a class and the process of creating this object is called instantiation.

While most programming languages have a single class system, R has


three class systems. Namely, S3, S4 and more recently Reference class
systems.

They have their own features and peculiarities and choosing one over the
other is a matter of preference. Below, we give a brief introduction to them.

S3 Class
S3 class is somewhat primitive in nature. It lacks a formal definition and
objects of this class can be created simply by adding a class attribute to it.

This simplicity accounts for the fact that it is widely used in the R
programming language. In fact most of the R built-in classes are of this
type.

See R programming S3 Class section for further details.

Example 1: S3 Class

s <- list(name = "John", age = 21, GPA = 3.5)


class(s) <- "student"

# print the list with the updated class


print(s)

Output

$name
[1] "John"

$age
[1] 21

$GPA
[1] 3.5

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

Here, the class attribute allows objects to be associated with a specific


class. The class attribute provides a way to define behavior and methods
for objects of that class.

By assigning the class attribute to the list s, we are essentially indicating


that s is an object of the "student" class within the S3 object-oriented
system.

S4 Class
S4 class is an improvement over the S3 class. They have a formally
defined structure which helps in making objects of the same class look
more or less similar.

Class components are properly defined using the setClass() function and
objects are created using the new() function.
See R programming S4 Class section for further details.
Example 2: S4 class

setClass("student", slots = list(name = "character", age = "numeric",


GPA = "numeric"))

# create an instance of the "student" class


s <- new("student", name = "John", age = 21, GPA = 3.5)

# print the instance


print(s)

Output

An object of class "student"


Slot "name":
[1] "John"

Slot "age":
[1] 21

Slot "GPA":
[1] 3.5

Here, the setClass() function is used to define an S4 class


called "student" with three slots: name of type "character", age of
type "numeric", and GPA of type "numeric".
After defining the class, we have created an instance of the "student" class
using the new() function.
The new() function takes the class name and initializes the object by
providing values for each slot.
Finally, the instance s is printed, displaying the object's class and the
values stored in each slot.
Reference Class
Reference classes were introduced later, compared to the other two. It is
more similar to the object oriented programming we are used to seeing in
other major programming languages.

Reference classes are basically S4 classed with an environment added to


it.

Example 3: Reference class

# define the reference class "student"


student <- setRefClass("student",
fields = list(
name = "character",
age = "numeric",
GPA = "numeric"
)
)

# create an instance of the "student" reference class


s <- student$new(
name = "John",
age = 21,
GPA = 3.5
)

# print the instance


print(s)

Output

Reference class object of class "student"


Field "name":
[1] "John"
Field "age":
[1] 21
Field "GPA":
[1] 3.5
Here, we have defined the reference class "student" using
the setRefClass() function, specifying the class name and the fields within
the class.
The fields argument is a list that defines the names and types of the fields
in the class.
After defining the class, we have created an instance of the "student" class
using the $new() method.
The $new() method takes arguments for each field and initializes the object
with the provided values.
Finally, the instance s is printed, displaying the object's class and the
values stored in each field.

Comparison between S3 vs S4 vs Reference Class


S3 Class S4 Class Reference Class

Class defined using Class defined using


Lacks formal definition
setClass() setRefClass()

Objects are created by setting Objects are created Objects are created using
the class attribute using new() generator functions

Attributes are accessed using Attributes are accessed


Attributes are accessed using $
$ using @

Methods belong to generic Methods belong to


Methods belong to the class
function generic function

Follows copy-on-modify Follows copy-on- Does not follow copy-on-


semantics modify semantics modify semantics

What are objects and classes in R?


An object is a data structure with some attributes and methods which act upon its attributes’ is an object-

oriented language. Everything in R is considered an object. Each object has one or more attributes. Most of the

R objects have an attribute which is the “class” of the object. R provides a bundle of classes for statistical

programming. Everything in R is an object list, vector, data frame, factor, array, etc. An object is a collection of

data members associated with functions. Objects are the Basic Building of a program. An object is also

called an Instance of class. The process of creating an object from a class is called instantiation. Objects

have their attributes like class, dimnames,names,dim,comments etc. An object has a real Existence.

Classes in R
A class is a description of a thing and an object is an instance of a class. A class describes an object type by

mentioning the properties, behavior, and relationship of the object with other objects. The term methods can be

described as functions in association with the specified object types.

A class is a blueprint for the object. For example consider a sketch of a house with all details regarding its

floor, windows, doors, bedrooms, kitchen, etc based on the model in which the house is constructed.

Let us understand a simple example to differentiate an object and a class. Consider a class Person with

attributes and functionalities.


The different values of the attributes such as Name, Age, Profession, and Place create different objects like

Irina, John, and Adam but they belong to the same class Person. The common behavior of a person like

walk(),eat(),,sleep() forms methods to implement or the actions of the objects. So we can say the class is a

blueprint that is responsible for providing Different Properties to objects and providing different methods to

perform operations on those properties.

There are three separate systems of object orientation in R.The three systems are the following:-

1. S3 class

2. S4 class

3. Reference class
Each system is used independently of the other. Developers of new projects are encouraged to use s4 style

classes. They are extensively used in Bioconductor projects. Many developers use S3 classes because they are

quick and easy.

1. S3 Classes in R
S3 carries out a style of object-oriented programming known as generic function OO. This is different from most

programming dialects, similar to Java, C++, and C#, which execute message-passing OO.S3 is primitive in

nature.The objects of the S3 class can be created simply by adding a class attribute to it.S3 classes support the

overloading functions by dividing them into methods.

How to define and create an S3 object?

In S3 objects you can simply create a list.Consider the below example where a list is created with list elements

such as name, class, location, etc.

How to define and create an S3 object?

#Object Orientation in R

#How to define S3 class and create S3 objects ?

#Create a list with needed elements


s3 = list(name = "Stephen", Standard = "x", age = 16, locati Canada")

print(s3)

Output:
$name

[1] "Stephen"

$Standard

[1] "x"

A list s3 is created with name as “Stephen”, Standard as "x",age as 16 and location as " Canada”. These are the

attributes of the list s3 .The screenshot below helps you to understand about the attributes better, which shows

one user data object

Once after creating the S3 list ie the list created with attributes name, standard, age, location you can convert

the list using a class function into an s3 object.

How to define and create an S3 object?

#Creates an object of class "student"


class(s3) = "student"

print(class(s3))

Output:

[1] "student"

2. S4 Classes
S4 classes are an improvement over S3 classes.S4 classes have a formally defined structure which helps in

making objects of the same class which look more or less similar.S4 class is more standardized and structured

and is easier to manipulate.

How to create and manipulate an S4 object?

An s4 class is defined using the setClass() function. In the below example the code defines s4 class with class

name “student” and slots are defined as a list where attributes name, standard, location are character, and age

is numeric.

setClass "student",slots=list(name="character",standard="character",age="numeric",locati))

After creating or defining a S4 class a specific instance of object is created using new().In the below code s4 is

an object created using new() where class name is student with slots like name,standard,age,location filled with

their corresponding values.

s = new("student",name="Sen",standard="XI",age=17,locati)

The whole program when executed returns the below output that shows an object created of class student and

slots with their values like “name” is “Sen “ , Slot "standard" is “XI”etc

#Object Orientation in R

#How to define S4 class and create S4 objects ?

#Create a list with needed elements


setClass("student", slots = list(name = "character", standard = "character", age =
"numeric", locati))
s4 = new("student", name = "Sen", standard = "XI", age = 17, locati)
s4

Output:

An object of class "student"

Slot "name":

[1] "Sen"

Slot "standard":

[1] "XI"

Slot "age":

[1] 17
Slot "location":

[1] "UK"

How to check an object is s4?

To check an object is s4 you can use iss4() function.The iss4() functions returns a boolean value either TRUE if

the object is s4 else returns a FALSE which indicates the objects created is not s4 class.Let us check the object

s4 created in our previous section ia an s4 an object of class student.

IsS4(s4)

The code once executed returns a TRUE as result because it belongs to s4 class.

isS4(s3)
[1] FALSE

How to access and modify S4 slot?

The @ symbol can be used to access the components or contents within s4 .The object type s4 followed by @

symbol and name of the component to be accessed.In below example “name” is one of the attribute created

based on our previous example.

s4@name

This returns the name “Sen” as output.

The @ symbol is also useful to set or reset or assign a value to the object.Let us reset the name “Sen” to

“Peter” using the assigning symbol(<-/=)

s4@name <- "Peter"

An object of class student with new name instead of “Sen” replaced with “Peter” is created as shown below.

An object of class "student"

Slot "name":

[1] "Peter"
Slot "standard":

[1] "XI"

Slot "age":

[1] 17

Slot "location":

[1] "UK"

How do modify slots are S4 objects?

The slot() function allows modifying the slots. The slot() function consists of the name of the object and

attributes as parameters inside the parentheses.

slot(s4,"name")

The code returns “Peter ” as output.You can also modify the value of object using slot() function.

slot(s4,"name")="john"

Output:

An object of class "student"

Slot "name":

[1] "john"

Slot "standard":

[1] "XI"

Slot "age":

[1] 17

Reference class in OOPs


The reference class definition is similar to defining an s4 class. In the s4 class setClass() is used for defining

while reference class is defined using setRefClass() The variable members of a class need to be included in
the class definition. In the Reference class, the member variables are called as fields like slots in the s4

class.

Defining a Reference Class

The below example defines the Reference class student with fields

setRefClass "student",fields=list(name="character",standard="character",age="numeric",locati

Creating a Reference object

A generator function is returned by setRefclass() which is used to create new objects. The definition is stored

to a variable Student. The Student variable which has the definition forms the generator function for the class

student.

Student =
setRefClass("student",fields=list(name="character",standard="character",age="numeric",locati

print(Student)

forms a generator function for class student. It provides details such as class fields,class Methods.

Generator for class "student":

Class fields:

Name: name standard age location


Class: character character numeric character

Class Methods:
"field", "trace", "getRefClass", "initFields", "copy", "callSuper", ".objectPackage",
"export", "untrace",
"getClass", "show", "usingMethods", ".objectParent", "import"

Reference Superclasses:
"envRefClass"

The generator function is student() which creates new object with values to the fields.

# now student() is our generator


function which can be used to create new objects
s = student(name = "john", standard = "X", age = 15, locati
print(s)

The code after execution gives the below output

Output:-
Reference class object of class "student"

Field "name":

[1] "John"

Field " standard ":

[1] "X"

Field " age ":

[1] 15

Field " location ":

[1] "UK"

How to access and modify fields?

Fields of the object can be accessed using the $ operator.

> s$name
[1] "John"
> s$age
[1] 15
> s$ location
[1] "UK"

Similarly, it is modified by reassignment.

> s$name <- "Paul"


> s

The output after reassigning is

Reference class object of class "student"

Field "name":

[1] "Paul"

Field " standard ":

[1] "X"

Field " age ":

[1] 15

Field " location ":

[1] "UK"
S3 class S4 class Reference class

Lacks format definition Class defined Class defined using setRefclass()


using setclass()

Objects are created by Objects are created Objects are created using a generator
setting the class attribute. using new() function that stores class defined.

Attributes are accessed Attributes are accessed Attributes are accessed using $
using $ using @

Methods belong to generic Methods belong to Methods belong to generic functions.


functions. generic functions.

Follows copy-on-modify Follows copy-on-modify Follows copy-on-modify semantics


semantics semantics

How to Implement Error Handling in R Programming




Error handling is a crucial aspect of programming that allows to identify, and gracefully manage
errors or exceptions that may occur during the execution of code. In R Programming Language,
effective error handling can enhance the reliability of scripts and applications.
What are Errors in R?
An error refers to a condition that occurs when the execution of a statement or function encounters
a problem that prevents it from completing successfully. Good error handling helps to deal with
errors and gives helpful messages to users.
Error Handling Techniques
There are some different ways to handle errors in R programming
1. Try-Catch Blocks
2. Custom Error Handling
3. Stop Function
4. Finally Block (Cleanup)
5. The warning() function
1. Using tryCatch()
R
tryCatch({
result <- sqrt(-4)
print(result)
}, error = function(e) {
print("An error occurred:", e$message)
})
Output:
[1] NaN
Warning message:
In sqrt(-4) : NaNs produced
The code attempts to calculate the square root of -4, which is not possible in standard real number
arithmetic, resulting in a NaN (Not a Number) value.
 Since an error occurred (trying to take the square root of a negative number), the error message
“An error occurred:” along with the specific error message is printed.
 Additionally, a warning message is displayed indicating that NaNs (Not a Number) were
produced during the computation.
2.Custom Error Handling
R
check_positive <- function(val) {
if (val < 0) {
stop("Value must be positive")
}
return(val^2) # Squaring the positive value
}

tryCatch({
result <- check_positive(-7)
print(result)
}, error = function(e) {
print(paste("Error occurred:", e$message))
})
Output:
[1] "Error occurred: Value must be positive"
In the tryCatch block, we attempt to execute the check_positive function with a negative value. If
an error occurs within the try block (in this case, because the value is negative), the code jumps to
the error block where we specify what action to take in response to the error. Next print a custom
error message concatenated with the error message obtained from the caught error.
3.Stop Function
R
# Define a function to calculate the factorial of a non-negative integer
factorial <- function(n) {
if (n < 0) {
stop("Input must be a non-negative integer") # Stop execution if input is negative
}

if (n == 0) {
return(1) # Return 1 for factorial of 0
}

result <- 1
for (i in 1:n) {
result <- result * i # Calculate factorial
}
return(result)
}

# Test the factorial function


input <- -5
tryCatch({
result <- factorial(input)
print(paste("Factorial of", input, "is", result))
}, error = function(e) {
print(paste("Error occurred:", e$message))
})
Output:
[1] "Error occurred: Input must be a non-negative integer"
We define a factorial() function that calculates the factorial of a non-negative integer.
 Inside the function, we check if the input n is negative using an if statement. If it is, we use
stop() to terminate the function execution and throw an error with a custom message.
 Then test the factorial() function with a negative input (input <- -5) within a tryCatch block. If an
error occurs during the execution of the factorial() function, it is caught and an error message is
printed.
 This shows how the stop() function can be used to gracefully handle errors by stopping
execution and providing informative error messages.
4.Finally Block (Cleanup)
R
tryCatch({
file_con <- file("file.txt", "r") # Renamed file to file_con for clarity
data <- readLines(file_con)
}, finally = {
if (exists("file_con")) {
close(file_con)
}
})
Output:
Error in file("file.txt", "r") : cannot open the connection
In addition: Warning message:
In file("file.txt", "r") :
cannot open file 'file.txt': No such file or directory
The tryCatch block attempts to open a file named “file.txt” for reading, and then reads its contents
using the readLines() function.
Finally block, regardless of whether an error occurs or not, contains cleanup code. In this case, it
checks if the file_con object exists (which indicates that the file connection was successfully
opened). If it exists, it closes the file connection using the close() function.
5.The Warning() Function
R
# Define a function to calculate the square root of a number
calculate_sqrt <- function(x) {
if (x < 0) {
warning("Input is negative. Square root of negative numbers produces complex results.")
}
return(sqrt(x))
}

# Test the function


result <- calculate_sqrt(-9)
print(result)
Output
Warning messages:
1: In calculate_sqrt(-9) :
Input is negative. Square root of negative numbers produces complex results.
2: In sqrt(x) : NaNs produced
> print(result)
[1] NaN
We define a function calculate_sqrt that calculates the square root of a given number x.
 Inside the function, we check if the input x is negative. If it is, we generate a warning using
warning() to notify the user that taking the square root of negative numbers produces complex
results.
 Then call the calculate_sqrt function with -9 as an argument. This triggers the warning message
since -9 is negative.
Cause of Error
Syntax Error: The code doesn’t follow the right structure. For instance, if we write print(“Hello,
world!”) but forget to close the quotation marks, we’ll see a syntax error.
R
# Incorrect syntax: missing closing quotation mark
print("Hello, world!)
Output:
Error: unexpected symbol in:
"# Incorrect syntax: missing closing quotation mark
print("Hello"
Runtime Error: When the code is written correctly, but it tries to do something impossible. For
example, if we attempt to divide a number by zero, we’ll encounter a runtime error because we
can’t divide by zero.
R
# Attempting to divide by zero
result <- 10 / 0
result
Output:
[1] Inf
Here, R returns Inf, which stands for “infinity,” because dividing any non-zero number by zero
results in infinity in R.
Logical Error: It’s happen when the code looks right and makes sense, but it doesn’t give the
expected results. For example, try to add two words together using the addition operator (+), it
won’t work as expected because we can’t add words together like numbers.
R
# Adding two words together
result <- "Hello" + "World"
Output:
Error in "Hello" + "World" : non-numeric argument to binary operator
Error Handling in R Programming
Syntax Error
R
# Syntax Error Example
# This code contains a syntax error due to a missing closing parenthesis
print("Hello, world!") # Corrected: Added the missing closing parenthesis
Output:
[1] "Hello, world!"
Runtime Error
R
# Define a function to perform division
safe_division <- function(x, y) {
tryCatch(
{
result <- x / y
if(is.infinite(result)){
return("Error: Division by zero occurred.")
} else {
return(result)
}
},
error = function(e) {
return("Error: Division by zero occurred.")
}
)
}

# Example usage
result <- safe_division(10, 0)
print(result) # This will print "Error: Division by zero occurred."
Output:
[1] "Error: Division by zero occurred."
Logical Error
R
# Logical Error Example
# This code attempts to add two strings together, resulting in a logical error
# Corrected: Using paste() function to concatenate strings
result <- paste("Hello", "World")
print(result)
Output:
[1] "Hello World"

Handling Errors in R Programming





Error Handling is a process in which we deal with unwanted or
anomalous errors which may cause abnormal termination of the
program during its execution. In R Programming, there are
basically two ways in which we can implement an error handling
mechanism. Either we can directly call the functions like stop() or
warning(), or we can use the error options such as “warn” or
“warning.expression”. The basic functions that one can use for
error handling in the code :
 stop(…): It halts the evaluation of the current statement and
generates a message argument. The control is returned to the
top level.
 waiting(…): Its evaluation depends on the value of the error
option warn. If the value of the warning is negative then it is
ignored. In case the value is 0 (zero) they are stored and
printed only after the top-level function completes its
execution. If the value is 1 (one) then it is printed as soon as it
has been encountered while if the value is 2 (two) then
immediately the generated warning is converted into an error.
 tryCatch(…): It helps to evaluate the code and assign the
exceptions.
Condition Handling in R
Generally, if we encounter any unexpected errors while executing
a program we need an efficient and interactive way to debug the
error and know what went wrong. However, some errors are
expected but sometimes the models fail to fit and throw an error.
There are basically three methods to handle such conditions and
errors in R :
 try(): it helps us to continue with the execution of the program
even when an error occurs.
 tryCatch(): it helps to handle the conditions and control what
happens based on the conditions.
 withCallingHandlers(): it is an alternative to tryCatch() that
takes care of the local handlers.
try-catch-finally in R
Unlike other programming languages such as Java, C++, and so
on, the try-catch-finally statements are used as a function in R.
The main two conditions to be handled in tryCatch() are “errors”
and “warnings”.
Syntax:
check = tryCatch({
expression
}, warning = function(w){
code that handles the warnings
}, error = function(e){
code that handles the errors
}, finally = function(f){
clean-up code
})
Example:
 R

# R program illustrating error handling

# Applying tryCatch

tryCatch(

# Specifying expression

expr = {

1 + 1

print("Everything was fine.")

},

# Specifying error message

error = function(e){

print("There was an error message.")

},

warning = function(w){
print("There was a warning message.")

},

finally = {

print("finally Executed")

Output:
[1] "Everything was fine."
[1] "finally Executed"

withCallingHandlers() in R
In R, withCallingHandlers() is a variant of tryCatch(). The only
difference is tryCatch() deals with exiting handlers while
withCallingHandlers() deals with local handlers.
Example:
 R

# R program illustrating error handling

# Evaluation of tryCatch

check <- function(expression){

withCallingHandlers(expression,
warning = function(w){

message("warning:\n", w)

},

error = function(e){

message("error:\n", e)

},

finally = {

message("Completed")

})

check({10/2})

check({10/0})

check({10/'noe'})

Output:
R Packages
R packages are the collection of R functions, sample data, and compile codes. In the R environment, these
packages are stored under a directory called "library." During installation, R installs a set of packages. We can
add packages later when they are needed for some specific purpose. Only the default packages will be
available when we start the R console. Other packages which are already installed will be loaded explicitly to be
used by the R program.

There is the following list of commands to be used to check, verify, and use the R packages.
Check Available R Packages

To check the available R Packages, we have to find the library location in which R packages are contained. R
provides libPaths() function to find the library locations.

1. libPaths()

When the above code executes, it produces the following project, which may vary depending on the local
settings of our PCs & Laptops.

ADVERTISEMENT

[1] "C:/Users/ajeet/OneDrive/Documents/R/win-library/3.6"
[2] "C:/Program Files/R/R-3.6.1/library"

Getting the list of all the packages installed

R provides library() function, which allows us to get the list of all the installed packages.

1. library()

When we execute the above function, it produces the following result, which may vary depending on the local
settings of our PCs or laptops.

Packages in library 'C:/Program Files/R/R-3.6.1/library':


Like library() function, R provides search() function to get all packages currently loaded in the R environment.

1. search()

When we execute the above code, it will produce the following result, which may vary depending on the local
settings of our PCs and laptops:

[1] ".GlobalEnv" "package:stats" "package:graphics"


[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"

Install a New Package

In R, there are two techniques to add new R packages. The first technique is installing package directly from
the CRAN directory, and the second one is to install it manually after downloading the package to our local
system.

ADVERTISEMENT

Install directly from CRAN

The following command is used to get the packages directly from CRAN webpage and install the package in the
R environment. We may be prompted to choose the nearest mirror. Choose the one appropriate to our location.

1. install.packages("Package Name")

The syntax of installing XML package is as follows:


1. install.packages("XML")

Output

Install package manually

To install a package manually, we first have to download it


from https://cran.r-project.org/web/packages/available_packages_by_name.html. The required package will be
saved as a .zip file in a suitable location in the local system.

Once the downloading has finished, we will use the following command:

1. install.packages(file_name_with_path, repos = NULL, type = "source")

Install the package named "XML"

1. install.packages("C:\Users\ajeet\OneDrive\Desktop\graphics\xml2_1.2.2.zip", repos = NULL, type = "source")

Load Package to Library


We cannot use the package in our code until it will not be loaded into the current R environment. We also need
to load a package which is already installed previously but not available in the current environment.

There is the following command to load a package:

1. library("package Name", lib.loc = "path to library")

Command to load the XML package

1. install.packages("C:\Users\ajeet\OneDrive\Desktop\graphics\xml2_1.2.2.zip", repos = NULL, type = "source")

List of R packages
R is the language of data science which includes a vast repository of
packages. These packages appeal to different regions which use R for
their data purposes. CRAN has 10,000 packages, making it an ocean of
superlative statistical work. There are lots of packages in R, but we will
discuss the important one.

There are some mostly used and popular packages which are as follows:
1) tidyr
The word tidyr comes from the word tidy, which means clear. So
the tidyr package is used to make the data' tidy'. This package works well
with dplyr. This package is an evolution of the reshape2 package.

2) ggplot2
R allows us to create graphics declaratively. R provides
the ggplot package for this purpose. This package is famous for its
elegant and quality graphs which sets it apart from other visualization
packages.

3) ggraph
R provides an extension of ggplot known as ggraph. The limitation
of ggplot is the dependency on tabular data is taken away in ggraph.

4) dplyr
R allows us to perform data wrangling and data analysis. R provides
the dplyr library for this purpose. This library facilitates several functions
for the data frame in R.

5) tidyquant
The tidyquant is a financial package which is used for carrying out
quantitative financial analysis. This package adds to
the tidyverse universe as a financial package which is used for importing,
analyzing and visualizing the data.

6) dygraphs
The dygraphs package provides an interface to the main JavaScript library
which we can use for charting. This package is essentially used for
plotting time-series data in R.

7) leaflet
For creating interactive visualization, R provides the leaflet package. This
package is an open-source JavaScript library. The world's popular websites
like the New York Times, Github and Flicker, etc. are using leaflet. The
leaflet package makes it easier to interact with these sites.

8) ggmap
For delineating spatial visualization, the ggmap package is used. It is a
mapping package which consists of various tools for geolocating and
routing.

ADVERTISEMENT

9) glue
R provides the glue package to perform the operations of data wrangling.
This package is used for evaluating R expressions which are present
within the string.

10) shiny
R allows us to develop interactive and aesthetically pleasing web apps by
providing a shiny package. This package provides various extensions with
HTML widgets, CSS, and JavaScript.

11) plotly
The plotly package provides online interactive and quality graphs. This
package extends upon the JavaScript library -plotly.js.

12) tidytext
The tidytext package provides various functions of text mining for word
processing and carrying out analysis through ggplot, dplyr, and other
miscellaneous tools.

13) stringr
The stringr package provides simplicity and consistency to use wrappers
for the 'stringi' package. The stringi package facilitates common string
operations.

14) reshape2
This package facilitates flexible reorganization and aggregation of data
using melt () and decast () functions.

15) dichromat
The R dichromat package is used to remove Red-Green or Blue-Green
contrasts from the colors.

16) digest
The digest package is used for the creation of cryptographic hash objects
of R functions.

17) MASS
The MASS package provides a large number of statistical functions. It
provides datasets that are in conjunction with the book "Modern Applied
Statistics with S."

18) caret
R allows us to perform classification and regression tasks by providing the
caret package. CaretEnsemble is a feature of caret which is used for the
combination of different models.

19) e1071
The e1071 library provides useful functions which are essential for data
analysis like Naive Bayes, Fourier Transforms, SVMs, Clustering, and other
miscellaneous functions.

20) sentimentr
The sentiment package provides functions for carrying out sentiment
analysis. It is used to calculate text polarity at the sentence level and to
perform aggregation by rows or grouping variables.

You might also like