R6 Classes in R Programming
Last Updated :
28 Apr, 2025
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
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
ASCII Values Alphabets ( A-Z, a-z & Special Character Table ) ASCII (American Standard Code for Information Interchange) is a standard character encoding used in telecommunication. The ASCII pronounced 'ask-ee', is strictly a seven-bit code based on the English alphabet. ASCII codes are used to represent alphanumeric data. The code was first published as a sta
7 min read
What is a Neural Network? Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
What is an Operating System? An Operating System is a System software that manages all the resources of the computing device. Acts as an interface between the software and different parts of the computer or the computer hardware. Manages the overall resources and operations of the computer. Controls and monitors the execution o
9 min read
What is DFD(Data Flow Diagram)? Data Flow Diagram is a visual representation of the flow of data within the system. It help to understand the flow of data throughout the system, from input to output, and how it gets transformed along the way. The models enable software engineers, customers, and users to work together effectively d
9 min read
COCOMO Model - Software Engineering The Constructive Cost Model (COCOMO) It was proposed by Barry Boehm in 1981 and is based on the study of 63 projects, which makes it one of the best-documented models. It is a Software Cost Estimation Model that helps predict the effort, cost, and schedule required for a software development project
15+ min read
What is LSTM - Long Short Term Memory? Long Short-Term Memory (LSTM) is an enhanced version of the Recurrent Neural Network (RNN) designed by Hochreiter and Schmidhuber. LSTMs can capture long-term dependencies in sequential data making them ideal for tasks like language translation, speech recognition and time series forecasting. Unlike
5 min read
Advanced Encryption Standard (AES) Advanced Encryption Standard (AES) is a highly trusted encryption algorithm used to secure data by converting it into an unreadable format without the proper key. It is developed by the National Institute of Standards and Technology (NIST) in 2001. It is is widely used today as it is much stronger t
7 min read
Clustering in Machine Learning In real world, not every data we work upon has a target variable. Have you ever wondered how Netflix groups similar movies together or how Amazon organizes its vast product catalog? These are real-world applications of clustering. This kind of data cannot be analyzed using supervised learning algori
9 min read
Supervised Machine Learning Supervised machine learning is a fundamental approach for machine learning and artificial intelligence. It involves training a model using labeled data, where each input comes with a corresponding correct output. The process is like a teacher guiding a studentâhence the term "supervised" learning. I
12 min read