R – Inheritance

Last Updated : 22 Jun, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Inheritance is one of the concept in object oriented programming by which new classes can derived from existing or base classes helping in re-usability of code. Derived classes can be the same as a base class or can have extended features which creates a hierarchical structure of classes in the programming environment. In this article, we’ll discuss how inheritance is followed out with three different types of classes in R programming.

Inheritance in S3 Class

S3 class in R programming language has no formal and fixed definition. In an S3 object, a list with its class attribute is set to a class name. S3 class objects inherit only methods from its base class.

Example:




# Create a function to create an object of class
student <- function(n, a, r){
  value <- list(name = n, age = a, rno = r)
  attr(value, "class") <- student
  value
}
  
# Method for generic function print()
print.student <- function(obj){
  cat(obj$name, "\n")
  cat(obj$age, "\n")
  cat(obj$rno, "\n")
}
  
# Create an object which inherits class student
s <- list(name = "Utkarsh", age = 21, rno = 96,
          country = "India")
  
# Derive from class student
class(s) <- c("InternationalStudent", "student")
  
cat("The method print.student() is inherited:\n")
print(s)
  
# Overwriting the print method
print.InternationalStudent <- function(obj){
cat(obj$name, "is from", obj$country, "\n")
}
  
cat("After overwriting method print.student():\n")
print(s)
  
# Check imheritance
cat("Does object 's' is inherited by class 'student' ?\n")
inherits(s, "student")


Output:

The method print.student() is inherited:
Utkarsh 
21 
96 
After overwriting method print.student():
Utkarsh is from India
Does object 's' is inherited by class 'student' ?
[1] TRUE

Inheritance in S4 Class

S4 class in R programming have proper definition and derived classes will be able to inherit both attributes and methods from its base class.

Example:




# Define S4 class
setClass("student",
         slots = list(name = "character"
                      age = "numeric", rno = "numeric"
)
   
# Defining a function to display object details
setMethod("show", "student",
          function(obj){
            cat(obj@name, "\n")
            cat(obj@age, "\n")
            cat(obj@rno, "\n")
          
)
   
# Inherit from student
setClass("InternationalStudent",
slots = list(country = "character"),
contains = "student"
)
   
# Rest of the attributes will be inherited from student
s <- new("InternationalStudent", name = "Utkarsh"
         age = 21, rno = 96, country="India")
show(s)


Output:

Utkarsh 
21 
96 

Inheritance in Reference Class

Inheritance in reference class is almost similar to the S4 class and uses setRefClass() function to perform inheritance.

Example:




# Define class
student <- setRefClass("student",
   fields = list(name = "character",
                 age = "numeric", rno = "numeric"),
   methods = list(
     inc_age <- function(x) {
       age <<- age + x
     },
     dec_age <- function(x) {
       age <<- age - x
     }
   )
)
  
# Inheriting from Reference class
InternStudent <- setRefClass("InternStudent"
   fields = list(country = "character"), 
   contains = "student",
   methods = list(
   dec_age <- function(x) {
     if((age - x) < 0)  stop("Age cannot be negative")
     age <<- age - x
   }
   
)
  
# Create object
s <- InternStudent(name = "Utkarsh",
                   age = 21, rno = 96, country = "India")
  
cat("Decrease age by 5\n")
s$dec_age(5)
s$age
  
cat("Decrease age by 20\n")
s$dec_age(20
s$age


Output:

[1] 16 
Error in s$dec_age(20) : Age cannot be negative
[1] 16



Previous Article
Next Article

Similar Reads

Data analysis using R
Data Analysis is a subset of data analytics, it is a process where the objective has to be made clear, collect the relevant data, preprocess the data, perform analysis(understand the data, explore insights), and then visualize it. The last step visualization is important to make people understand what's happening in the firm. Steps involved in data
10 min read
How to Find and Count Missing Values in R DataFrame
In this article, we will be discussing how to find and count missing values in the R programming language. Find and Count Missing Values in the R DataFrameGenerally, missing values in the given data are represented with NA. In R programming, the missing values can be determined by is.na() method. This method accepts the data variable as a parameter
4 min read
A Guide to dnorm, pnorm, rnorm, and qnorm in R
In this article, we will be looking at a guide to the dnorm, pnorm, qnorm, and rnorm methods of the normal distribution in the R programming language. dnorm function This function returns the value of the probability density function (pdf) of the normal distribution given a certain random variable x, a population mean μ, and the population standard
3 min read
How to Find Confidence Intervals in R?
The confidence interval in R signifies how much uncertainty is present in statistical data. a fundamental statistical technique, confidence intervals offer a range of likely values for an unknown population parameter based on sample data. They are essential to decision-making, hypothesis testing, and statistical inference.In other words, it is defi
6 min read
apply(), lapply(), sapply(), and tapply() in R
In this article, we will learn about the apply(), lapply(), sapply(), and tapply() functions in the R Programming Language. The apply() collection is a part of R essential package. This family of functions helps us to apply a certain function to a certain data frame, list, or vector and return the result as a list or vector depending on the functio
4 min read
How to Change Axis Scales in R Plots?
In this article, we will learn how to change Axis Scales in the R Programming Language. Method 1: Change Axis Scales in Base R To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively. This fu
4 min read
How to Use lm() Function in R to Fit Linear Models?
In this article, we will learn how to use the lm() function to fit linear models in the R Programming Language. A linear model is used to predict the value of an unknown variable based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. The lm() function is used to fit linear models to dat
4 min read
How to Create Tables in R?
In this article, we will discuss how to create tables in R Programming Language. Method 1: Create a table from scratch We can create a table by using as.table() function, first we create a table using matrix and then assign it to this method to get the table format. Syntax: as.table(data) Example: In this example, we will create a matrix and assign
2 min read
How to Convert Character to Numeric in R?
In this article, we will discuss how to convert characters to numeric in R Programming Language. We can convert to numeric by using as.numeric() function. Syntax: as.numeric(character) where, character is an character vector Example: C/C++ Code # create a vector with 5 characters data = c('1', '2', '3', '4', '5') # display type class(data) # conver
1 min read
Change column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
5 min read
R Tutorial | Learn R Programming Language
R Tutorial is designed for beginners and experts. This free R Tutorial gives you concepts of the R programming language. Here you will get a detailed introduction, features, installation, variables, data types, operators, if statements, vectors, data handling, graphics, and statistical modeling of R programming. What is R Programming?R is an interp
7 min read
R - Data Frames
R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data.  Data frames can also be interpreted as matrices where each column of a matrix can be of different data types. R DataFrame is
10 min read
Taking Input from User in R Programming
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. Like other programming languages in R it's also possible to take input from the user. For doing so, there are two methods in R. Using readline() me
7 min read
Printing Output of an R Program
In R there are various methods to print the output. Most common method to print output in R program, there is a function called print() is used. Also if the program of R is written over the console line by line then the output is printed normally, no need to use any function for print that output. To do this just select the output variable and pres
4 min read
Read contents of a CSV File in R Programming - read.csv() Function
read.csv() function in R Language is used to read "comma separated value" files. It imports data in the form of a data frame. Syntax: read.csv(file, header, sep, dec) Parameters: file: the path to the file containing the data to be imported into R. header: logical value. If TRUE, read.csv() assumes that your file has a header row, so row 1 is the n
3 min read
Control Statements in R Programming
Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we'll discuss all the control statements with the examples. In R programming, there are 8 types of control statements
4 min read
Data visualization with R and ggplot2
Data visualization with R and ggplot2 in R Programming Language also termed as Grammar of Graphics is a free, open-source, and easy-to-use visualization package widely used in R Programming Language. It is the most powerful visualization package written by Hadley Wickham. It includes several layers on which it is governed. The layers are as follows
9 min read
R - Matrices
R-matrix is a two-dimensional arrangement of data in rows and columns. In a matrix, rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices: Creating a Matrix in RTo create a matrix in R you need to use the
12 min read
R - Lists
A list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional, heterogeneous data structures. The list can be a list of vectors, a list of matrices, a list of characters, a list of functions, and so on. A list is a vector but with heterogeneous data elements. A list in R is created with the us
8 min read
R Data Types
Different forms of data that can be saved and manipulated are defined and categorized using data types in computer languages, including R. Each R data type has unique properties and associated operations. What are R Data types?R Data types are used to specify the kind of data that can be stored in a variable. For effective memory consumption and pr
8 min read
R Factors
Factors in R Programming Language are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. The R factors may look similar to character vectors, they are integers and care must be taken while using
5 min read
Functions in R Programming
A function accepts input arguments and produces the output by executing valid R commands that are inside the function. Functions are useful when you want to perform a certain task multiple times. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and
8 min read
Getting started with Data Visualization in R
Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. Data Visualization in R Programming LanguageThe popular data visualizatio
6 min read
Data Structures in R Programming
A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values. R’s base data structures are often organized by their dimensionality (1D, 2D, or nD) and whether t
6 min read
R Vectors
R Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well.  Creating a vectorA vector is a basic data structure that
5 min read
R Operators
Operators are the symbols directing the compiler to perform various kinds of operations between the operands. Operators simulate the various mathematical, logical, and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. R Operators R supports majorly four kinds of binary operators between a set of
9 min read
R Programming Language - Introduction
The R Language stands out as a powerful tool in the modern era of statistical computing and data analysis. Widely embraced by statisticians, data scientists, and researchers, the R Language offers an extensive suite of packages and libraries tailored for data manipulation, statistical modeling, and visualization. In this article, we explore the fea
7 min read
Histograms in R language
A histogram contains a rectangular area to display the statistical information which is proportional to the frequency of a variable and its width in successive numerical intervals. A graphical representation that manages a group of data points into different specified ranges. It has a special feature that shows no gaps between the bars and is simil
3 min read
R - Bar Charts
Bar charts are a popular and effective way to visually represent categorical data in a structured manner. R stands out as a powerful programming language for data analysis and visualization. In this article, we'll look at how to make visually appealing bar charts in R. Bar Charts using RA bar chart also known as bar graph is a pictorial representat
5 min read
Simple Linear Regression in R
Regression shows a line or curve that passes through all the data points on the target-predictor graph in such a way that the vertical distance between the data points and the regression line is minimum What is Linear Regression?Linear Regression is a commonly used type of predictive analysis. Linear Regression is a statistical approach for modelli
12 min read
Article Tags :
three90RightbarBannerImg