R6 Classes in R Programming

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

In Object-Oriented Programming (OOP) of R Language, encapsulation means binding the data and methods inside a class. The R6 package is an encapsulated OOP system that helps us use encapsulation in R. R6 package provides R6 class which is similar to the reference class in R but is independent of the S4 classes. In R6, you define a class by creating a new R6Class object, with the name of the class and a list of its properties and methods. Properties can be any R object, while methods are functions that can be called on objects of the class.

To create an instance of an R6 class, you use the $new() method of the class object, passing in any initial values for the properties. Once you have an object instantiated from the class, you can call its methods and access or modify its properties using the $ operator.

One key feature of R6 is that it allows for encapsulation and information hiding, meaning that the internal workings of an object can be hidden from the user. This can make it easier to create more complex and robust programs.

Overall, R6 provides a powerful way to organize your code and create custom objects with their own properties and behaviors, making it a useful tool for building more advanced R programs. Along with the private and public members, R6 Classes also support inheritance even if the classes are defined in different packages. Some of the popular R packages that use R6 classes are dplyr and shiny

Example: 

R




library(R6)
 
Queue <- R6Class("Queue",
 
# public members of the class
# that can be accessed by object
public = list(
     
# constructor/initializer
initialize = function(...)
{
    private$elements = list(...)
},
 
# add to the queue
enqueue = function(num)
{
    private$elements <- append(private$elements, num)
},
 
# remove from the queue
dequeue = function()
{
    if(self$size() == 0)
    stop("Queue is empty")
    element <- private$elements[[1]]
    private$elements <- private$elements[-1]
    element
},
 
# get the size of elements
size = function()
{
    length(private$elements)
}),
 
private = list(
     
# queue list
elements = list())
)
 
# create an object
QueueObject = Queue$new()
 
# add 2
QueueObject$enqueue(2)
 
# add 5
QueueObject$enqueue(5)
 
# remove 2
QueueObject$dequeue()
 
# remove 5
QueueObject$dequeue()


Output:

[1] 2
[1] 5

Both public and private members can be used. The queue (elements) is private so that the object can not modify it externally. The initialize function is the constructor for initializing the object. object$member is used for accessing the public members outside the class whereas private$member is used for accessing the private members inside the class methods. self refers to the object that has called the method.

The following example is a demonstration of Inheritance in R6 classes by creating another class childQueue that inherits the class Queue.

Example

R




childQueue <- R6Class("childQueue",
 
# inherit Queue class which is the super class
inherit = Queue,
public = list(
initialize = function(...)
{
    private$elements <- list(...)
},
size = function()
{
    # super is used to access methods from super class
    super$size()
}
))
 
childQueueObject <- childQueue$new()
childQueueObject$enqueue(2)
childQueueObject$enqueue(3)
childQueueObject$dequeue()
childQueueObject$dequeue()


Output:

[1] 2
[1] 3

childQueue class can use enqueue() and dequeue() functions from the Queue superclass. size method overrides the size() from the super class Queue but calls the size() of Queue internally using super. These classes can be inherited across packages.



Similar Reads

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
Can you Create Classes in the R Programming Language?
Yes, you can create classes in the R programming language. R supports object-oriented programming (OOP) through several systems, including S3, S4, and Reference Classes (RC), allowing you to define classes, create objects, and implement methods. Each system has its own characteristics and levels of complexity, making R flexible in handling differen
3 min read
Difference between Functional Programming and Object Oriented Programming
What is Functional Programming?In functional programming, we have to build programs using functions. An example of functional programming is Haskell language. What is Object Oriented Programming?Object-oriented programming is built by using classes and objects. In this, we have concepts of encapsulation, inheritance, polymorphism, and Data abstract
3 min read
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
Classes and Object in MATLAB
A class is a blueprint that defines the variables and the methods which provide a commonly shared basis for its corresponding objects. It defines an object that encapsulates data and the operations performed on that data. classdef is a keyword used to define MATLAB classes. Syntax to define a class: classdef (Attributes) ClassName < SuperclassNa
4 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
What are the Two Broad Classes of Middleware in Client Server Environment?
Server: A server is a computer program that provides services, data, information to other computer programs. Client: A client is a host computer, requests services or information from the server. the client is also called a user. In a computer system, a client is a computer program that asks something from the server and the server gives the inform
5 min read
Different Classes of CPU Registers
In Computer Architecture, the Registers are very fast computer memory that is used to execute programs and operations efficiently. This is done by giving access to commonly used values, i.e., the values that are at the point of operation/execution at that time. So, for this purpose, there are several different classes of CPU registers that work in
7 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 <- 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 <- 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 <- 20 # Calling rf() Function y <- 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 <- 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 <- c(1, 2, 3, 4) # Creating a list list1 <- 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
Introduction to SAS programming
Statistical Analysis System (SAS) is a software suite that has been developed by SAS Institute, one of the leaders in analytics. It is useful for performing advanced analytics, multivariate analyses, business intelligence, data management functions, and also for conducting predictive analytics. Use of SAS: SAS is used by many top organizations whic
3 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 <- 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 <- c("GFG", "gfg") y <- c("a", "b", "c") #
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
three90RightbarBannerImg