The Wayback Machine - https://web.archive.org/web/20240828110658/https://www.geeksforgeeks.org/polymorphism-in-r-programming/
Open In App

Polymorphism in R Programming

Last Updated : 06 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

R language is evolving and it implements parametric polymorphism, which means that methods in R refer to functions, not classes. Parametric polymorphism primarily lets you define a generic method or function for types of objects you haven’t yet defined and may never do. This means that one can use the same name for several functions with different sets of arguments and from various classes. R’s method call mechanism is generics which allows registering certain names to be treated as methods in R, and they act as dispatchers. 

Generic Functions

Polymorphism in R can be obtained by the generics. It allows certain names to be treated as methods and they act as dispatchers. Let’s understand with the help of plot() function and summary function. In R programming the plot() and summary() functions return different results depending on the objects being passed to them and that’s why they are generic functions that implement polymorphism. 

plot() in R

plot() is one of the generic functions that implement polymorphism in R. It produces a different graph if it is given a vector, a factor, a data frame, etc. But have you ever wondered how does the class of vectors or factors determine the method used for plotting?  Let’s see the code for the plot function. 

Example: Code of plot function

R




plot


Output:

function (x, y, ...)
UseMethod("plot")

We can see that the body of the plot function contains only one expression and that is UseMethod(“plot”). Let’s see the definition of UseMethod with the help of help() function.

Example: Definition of the help() method.

R




help(UseMethod)


Output:

From the above output, we can see that UseMethod takes two parameters generic and object. 

  • The generic is the string name which is the name of the function (plot in this case). 
  • This is an object whose class will determine the method that will be “dispatched,” It means the object for which the generic method will be called.

The UseMethod then searches for the suitable plot function that is needed to be called by creating a string of the type plot.object. We can also see all the available methods for the plot function.

Example:

R




methods(plot)


Output:

plot function

Let’s see how plot() function taking arguments and displaying different outputs

Input is one numeric vector

In this example let’s take a single numeric vector inside plot() function as a parameter.

R




# R program to illustrate
# polymorphosim
 
# X Window System Graphics (X11)
X11(width = 15, height = 13)
 
# The runif() function generates
# random deviates of the uniform distribution
x <- 3 * runif(40) + (1:30)
par(mar = c(20, 20, 1, 1))
 
# type='l' is used  to connect the points
# of the scatter plots with lines.
plot(x, type = 'l', col = '#343deb')
 
# We can do  mouse click or enter pressed
z <- locator(1)


 Output:

plot function in r

Inputs are two numeric vectors

We need to pass two vector parameters and it produces a scatter plot accordingly.

R




# R program to illustrate
# polymorphosim
 
# X Window System Graphics (X11)
X11(width = 5, height = 3)
 
# The runif() function generates random
# deviates of the uniform distribution
x <- runif(20)
y <- runif(20) * x
par(mar = c(2, 2, 0.3, 0.3))
 
# type = 'p' means as points, the output comes as scattered
# pch stands for plot character. pch = 16 we get . character
plot(x, y, type = 'p', pch = 16, col = '#ab1ab0')
 
#Either mouse press or enter key press wait
z <- locator(1)


 Output:

plot function in r

Input is a factor

If we passed factor as arguments then we get a bar chart pattern. 

R




# R program to illustrate
# polymorphosim
 
# X Window System Graphics (X11)
X11(width = 5, height = 8)
 
# here fruits names are passed and barchart is produced as output
f <- factor(c('apple', 'orange', 'apple', 'pear', 'orange',
              'apple', 'apple', 'orange'))
par(mar = c(2, 2, 0.6, 0.6))
 
# Using plot()
plot(f, col = '#8f4c91')
z <- locator(1)


 Output:

plot function in r

Input is a data frame

The Plot function takes the data frame as an argument and each variable of the data frame is plotted against each other.

R




# R program to illustrate
# polymorphosim
 
# X Window System Graphics (X11)
X11(width = 6, height = 6)
 
set.seed(280870)
x <- c(4, 3, 1, 2, 2, 4, 6, 4, 5, 5,
       4, 4, 5, 4, 4, 8, 4, 1, 2, 7)
y <- x * rnorm(20, 1, 0.3)
z <- x * y
 
# Taking a data frame
df <- data.frame(x, y, z)
par(mar = c(0.1, 0.1, 0.1, 0.1))
 
# Using plot()
plot(df, col = '#a832a6', pch = 16, cex = 1.5)
z <- locator(1)


 Output:

plot function in r

summary() in R

It is also a generic function that implements polymorphism in R. It is used to produce result summaries of the results of various model fitting functions.

Example 1:

R




# R program to illustrate
# polymorphosim
 
# Rainbow colors and let us see summary of it
colors <- c("violet", "indigo", "blue", "green",
            "yellow", "orange", "red")
summary(colors)


 Output:

Length     Class      Mode 
  7      character character 

Example 2:

Let us check for summarized results for state.region. In R it usually displays what are the regions available under “Northeast”, “South”, “North Central”, and “West”. Using summary() function either one can pass state.region as 1st parameter and as a second step, (optionally) pass “maxsum” argument. “maxsum” indicates how many levels should be shown for factors in output.

R




# R program to illustrate
# polymorphosim
 
state.region
 
# Provides summarised results under each region
summary(state.region)
 
# As maxsum is given as 3, totally we should have 3 regions
# But here we have 4 regions and hence highest count region,
# next highest count region is displayed and the other
# regions are clubbed under Other
summary(state.region, maxsum = 3)


Output:

> state.region
 [1] South         West          West          South         West          West         
 [7] Northeast     South         South         South         West          West         
[13] North Central North Central North Central North Central South         South        
[19] Northeast     South         Northeast     North Central North Central South        
[25] North Central West          North Central West          Northeast     Northeast    
[31] West          Northeast     South         North Central North Central South        
[37] West          Northeast     Northeast     South         North Central South        
[43] South         West          Northeast     South         West          South        
[49] North Central West         
Levels: Northeast South North Central West

> summary(state.region) 
    Northeast         South North Central          West 
            9            16            12            13 
                        
> summary(state.region, maxsum = 3) 
  South    West (Other) 
     16      13      21 

Example 3:

If the data set is very large then let’s have a look at how the summary() function works.

R




# R program to illustrate
# polymorphosim
 
# 10 different data sets are taken using stats::rnorm
x <- stats::rnorm(10)
x
 
# Let us cut the dataset to lie between -3 and 3 and
# in this case, it will be
# (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]
c <- cut(x, breaks = -3:3)
c
 
# Summarized the available dataset under the given levels
summary(c)


 Output:

> x
 [1]  0.66647846 -0.29140286 -0.29596477 -0.23432541 -0.02144178  1.56640107  0.64575227
 [8] -0.23759734  0.73304657 -0.04201218
 
> c
 [1] (0,1]  (-1,0] (-1,0] (-1,0] (-1,0] (1,2]  (0,1]  (-1,0] (0,1]  (-1,0]
Levels: (-3,-2] (-2,-1] (-1,0] (0,1] (1,2] (2,3]

> summary(c)
(-3,-2] (-2,-1]  (-1,0]   (0,1]   (1,2]   (2,3] 
      0       0       6       3       1       0 

Till now, we have described the plot() and summary() function which is a polymorphic function. By means of different inputs, plot() function behavior is changing and producing outputs. Here we can see the polymorphism concept. Similarly, in summary(), function, by means of varying parameters, the same method is applicable to provide different statistical outputs. Now let’s create our own generic methods.

Creating Generic Method

Let’s create a class bank and let’s try to create our own display() method that will use the print() method and will display the content of the class in the format specified by us.

For doing this we first have to create a generic display() function that will use the UseMethod function.

R




display <- function(obj){
    UseMethod("print")
}


After creating the generic display function let’s create the display function for our class bank.

R




print.bank<-function(obj)
{
    cat("Name is ", obj$name, "\n")
    cat(obj$account_no, " is the Acc no of the holder\n ")
    cat(obj$saving, " is the amount of saving in the account \n ")
    cat(obj$withdrawn, " is the withdrawn amount\n")
}


Now, let’s see the output given by this function

R




x <- list(name ="Arjun", account_no = 1234,
        saving = 1500, withdrawn = 234)
class(x)<-"bank"
 
display <- function(obj){
    UseMethod("print")
}
 
print.bank<-function(obj)
{
    cat("Name is ", obj$name, "\n")
    cat(obj$account_no, " is the Acc no of the holder\n ")
    cat(obj$saving, " is the amount of saving in the account \n ")
    cat(obj$withdrawn, " is the withdrawn amount\n")
}
 
display(x)


Output:

Name is  Arjun 
1234  is the Acc no of the holder
 1500  is the amount of saving in the account 
 234  is the withdrawn amount


Previous Article
Next Article

Similar Reads

What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u &lt;- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N &lt;- 20 # Calling rf() Function y &lt;- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat &lt;- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x &lt;- c(1, 2, 3, 4) # Creating a list list1 &lt;- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read
Check for Presence of Common Elements between Objects in R Programming - is.element() Function
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value. Syntax: is.element(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of is.element() function # Vector 1 x1 &lt;- c(1, 2, 3) # Vector 2 x2
1 min read
AB Testing With R Programming
Split testing is another name of A/B testing and it's a common or general methodology. It's used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two w
7 min read
Check if Elements of a Vector are non-empty Strings in R Programming - nzchar() Function
nzchar() function in R Language is used to test whether elements of a character vector are non-empty strings. Syntax: nzchar(x) Parameters: x: character vector Example 1: # R program to illustrate # nzchar function # Initializing a character vector x &lt;- c(&quot;GFG&quot;, &quot;gfg&quot;) y &lt;- c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) #
1 min read
Finding the length of string in R programming - nchar() method
nchar() method in R Programming Language is used to get the length of a character in a string object. Syntax: nchar(string) Where: String is object. Return: Returns the length of a string. R - length of string using nchar() ExampleExample 1: Find the length of the string in R In this example, we are going to see how to get the length of a string ob
2 min read
Data Reshaping in R Programming
Generally, in R Programming Language, data processing is done by taking data as input from a data frame where the data is organized into rows and columns. Data frames are mostly used since extracting data is much simpler and hence easier. But sometimes we need to reshape the format of the data frame from the one we receive. Hence, in R, we can spli
5 min read
Plotting Graphs using Two Dimensional List in R Programming
List is a type of an object in R programming. Lists can contain heterogeneous elements like strings, numeric, matrices, or even lists. A list is a generic vector containing other objects. Two-dimensional list can be created in R programming by creating more lists in a list or simply, we can say nested lists. The list() function in R programming is
2 min read
Make Elements of a Vector Unique in R Programming - make.unique() Function
make.unique() function in R Language is used to return elements of a vector with unique names by appending sequence numbers to duplicates. Syntax: make.unique(names, sep)Parameters: names: Character vector with duplicate names sep: Separator to be used Example 1: C/C++ Code # R program to make unique vectors # Calling make.unique() Function make.un
1 min read
Get or Set Levels of a Factor in R Programming - levels() Function
levels() function in R Language is used to get or set the levels of a factor. Syntax: levels(x) Parameters: x: Factor Object Example 1: # R program to get levels of a factor # Creating a factor gender &lt;- factor(c(&quot;female&quot;, &quot;male&quot;, &quot;male&quot;, &quot;female&quot;)); gender # Calling levels() function # to get the levels l
1 min read
Compute the gamma value of a Non-negative Numeric Vector in R Programming - gamma() Function
gamma() function in R Language is used to compute the gamma value of a numeric vector using the gamma function. Gamma function is basically, gamma(x) = factorial(x - 1) Syntax: gamma(x) Parameters: x: Non-negative Numeric Vector Example 1: # R program to calculate the gamma value # Calling gamma Function gamma(2) gamma(3) gamma(5) Output: [1] 1 [1]
1 min read
Compute Choleski factorization of a Matrix in R Programming - chol() Function
chol() function in R Language is used to compute the Choleski factorization of a real symmetric positive-definite square matrix. Syntax: chol(x, ...)Parameters: x: an object for which a method exists. The default method applies to real symmetric, positive-definite matrices Example 1: C/C++ Code # R program to illustrate # chol function # Initializi
2 min read
Classes in R Programming
Classes and Objects are basic concepts of Object-Oriented Programming that revolve around the real-life entities. Everything in R is an object. An object is simply a data structure that has some methods and attributes. A class is just a blueprint or a sketch of these objects. It represents the set of properties or methods that are common to all obj
4 min read
Array Operations in R Programming
Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures. Now, let’s see how to create arrays in R. To create an array
4 min read
Basic Syntax in R Programming
R is the most popular language used for Statistical Computing and Data Analysis with the support of over 10, 000+ free packages in CRAN repository. Like any other programming language, R has a specific syntax which is important to understand if you want to make use of its powerful features. This article assumes R is already installed on your machin
3 min read
Absolute and Relative Frequency in R Programming
In statistics, frequency or absolute frequency indicates the number of occurrences of a data value or the number of times a data value occurs. These frequencies are often plotted on bar graphs or histograms to compare the data values. For example, to find out the number of kids, adults, and senior citizens in a particular area, to create a poll on
2 min read
Decision Tree in R Programming
Decision Trees are useful supervised Machine learning algorithms that have the ability to perform both regression and classification tasks. It is characterized by nodes and branches, where the tests on each attribute are represented at the nodes, the outcome of this procedure is represented at the branches and the class labels are represented at th
8 min read
Article Tags :