R Inheritance

One the main concept of object oriented programming is inheritance which allows us to define a new class of existing classes. This means that we can derive new classes from existing base classes and adding new features. Hence, inheritance provides re-usability of code.

Inheritance in S3 class

Since S3 classes do not have any fixed definition. Hence attributes of S3 objects can be arbitrary. As we know, derived class inherits the methods defined for base class. For example, we have a function that creates new objects of class student as follows:
student <- function(n,a,g) {

  value <- list(name=n, age=a, GPA=g)

  attr(value, "class") <- "student"

  value

}
And we have a method defined for generic function print() as follows:
print.student <- function(obj) {

  cat("Name:", obj$name, "\n")

  cat("Age:", obj$age, "years old\n")

  cat("GPA:", obj$GPA, "\n")

}

Now, we want to create an object of the class InternationalStudent which inherits from student. This is be done by assigning a character vector of class names like class(obj) <- c(child, parent).
Example:
# create a list

s <- list(name="Nikita", age=21, GPA=8.5, country="France")

# make it of the class InternationalStudent which is derived from the class student

class(s) <- c("InternationalStudent","student")

# print it out

s
Output:
Name: Nikita

Age: 21 years old

GPA: 8.5

From the above example we can see that, since we have not defined any method of the form print.InternationalStudent(), the method print.student() got called. This method of class student was inherited. Now, let us define print.InternationalStudent():
print.InternationalStudent <- function(obj) {

  cat(obj$name, "is from", obj$country, "\n")

}

s
Output:
Nikita is from France

Inheritance in S4 Class

Since S4 classes have proper definition, derived classes will inherit both attributes and methods of the parent class. Let’s define a class student with a method for the generic function show():
# define a class called student

setClass("student",

         slots=list(name="character", age="numeric", GPA="numeric")

)

# define class method for the show() generic function

setMethod("show",

          "student",

          function(object) {

            cat(object@name, "\n")

            cat(object@age, "years old\n")

            cat("GPA:", object@GPA, "\n")

          }

)

Inheritance is done during the derived class definition with the argument contains:
# inherit from student

setClass("InternationalStudent",

         slots=list(country="character"),

         contains="student"

)
Here, new attribute is country; rest will be inherited from the parent.
s <- new("InternationalStudent",name="Nikita", age=24, GPA=8.5, country="France")

show(s)
Output:
Nikita

24 years old

GPA: 8.5

Inheritance in Reference Class

It is similar to S4 class.
Example: Let’s see an example of student reference class with two methods inc_age() and dec_age().
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

                         }

                       )

)
Now we will inherit from this class. We also overwrite a method dec_age() to add an integrity check to make sure age is never negative.
InternationalStudent <- setRefClass("InternationalStudent",

                                    fields=list(country="character"),

                                    contains="student",

                                    methods=list(

                                      dec_age = function(x) {

                                        if((age - x)<0)  stop("Age cannot be negative")

                                        age <<- age - x

                                      }

                                    )

)
Let’s test it:
s <- InternationalStudent(name="Nikita", age=21, GPA=8.5, country="France")

s$dec_age(5)

s$age

s$dec_age(20)

s$age
Output:
[1] 16

Error in s$dec_age(20) : Age cannot be negative

[1] 16

Related Topics

Normal Distribution in R Programming

In statistics, the normal distribution is a type of probability function. Normal distribution tells the user about the distribution of data values in the dataset. It is a very important...

3 minutes read.

First R Program

First  Hello World R Program As a convention, our first R program will be the “Hello World!” program. We can run our R program either at R command prompt or we...

3 minutes read.

R Operators

A symbol that tells the compiler to perform specific mathematical or logical operations is called operator. R language supports mainly 5 different types of operators, which are listed below: Arithmetic...

3 minutes read.

R Line Graphs

Line graph or line chart is a graph that connects a series of points by drawing segments between them. A line graph represents the relationship between 2 variables. These points...

2 minutes read.

R Date and Time

R provides very large range of capabilities to deal with times and dates. Generally, dates are internally stored as integers, and depending on the operations we will need, we could...

3 minutes read.

Analysis of Covariance in R Programming

Analysis of Covariance can also be named ANCOVA. We know that we use the concept of regression analysis for creating models which can explain the effect of the variation in...

2 minutes read.

Logistic Regression in R Programming

Logistic Regression is a classification supervised machine learning algorithm in R programming. Logistic Regression can also be termed Binomial Logistic Regression, Binary Logistic Regression, or Logit Model. Logistic Regression is...

4 minutes read.

R Excel Files

Microsoft Excel is the spreadsheet program which stores data in the .xls and .xlsx format. R has the facility to read directly from these files using some excel specific packages....

2 minutes read.

R Functions

In programming, a function is a group of instructions that you want to use repeatedly, because of their complexity, are better self-contained in sub-program and called when needed. Hence, we can...

4 minutes read.

How to make Boxplots in R

R Boxplots Boxplot is a measure of how well the data is distributed in a data set. It is used to give a summary of one or several numeric variables. The...

3 minutes read.

R Variables, Constants and Reserved Words

R Variables Variables are very similar to an open box, where you can put any value of your wish. We can change the values as well. Variables are used to store...

4 minutes read.

Scatter Plot in R Programming

A Scatter plot is a type of dispersion graph built to represent the various data points of variables. A Scatter plot is also known as a scatter graph or scattergram.  A scatter plot is used...

4 minutes read.

How to create Histograms in R

R Histograms A Histogram is the graphical representation of the distribution of numeric data. It takes only one numeric variable as input. The variable is cut into several bars (also called...

2 minutes read.

Pie Charts in R Programming

R programming has various libraries to plot various types of charts and graphs. A pie chart is a circular statistical chart or graph, which is divided into slices to represent the numerical...

4 minutes read.

Introduction to R Programming

What is R Programming? R is a programming language which provides an environment for software used for statistical analysis, graphics representation and reporting. It possesses an extensive catalog of...

4 minutes read.

R Inheritance

One the main concept of object oriented programming is inheritance which allows us to define a new class of existing classes. This means that we can derive new classes from...

5 minutes read.

Binomial Distribution in R Programming

In this article, we will talk about the Binomial distribution in R programming. The binomial distribution is a type of probability distribution. As it is a discrete distribution, it will...

3 minutes read.

R Data Types

Data types are used to define the size and type of the variable. In R, there is no need to declare a variable as some data types. The variables are...

4 minutes read.

Clustering in R Programming

The clustering technique is an unsupervised machine learning in R programming. Before discussing clustering techniques, let's have a look at what unsupervised machine learning is?  Unsupervised learning is training the model with...

3 minutes read.

R JSON File

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. JSON file is often used when data is sent from a server to a...

2 minutes read.