R R6 classes
last modified November 19, 2026
R6 is a package that adds mutable objects with reference semantics to R. An R6 object is an environment with methods, so assigning it to a second name does not copy it: both names point to the same object, and a change made through one is visible through the other. That behaviour matches objects in Java, Python, and JavaScript, and it suits stateful programs such as counters, accounts, and simulations. This article covers class definitions, public and private members, initialization, cloning, active bindings, and inheritance. The examples use R6 2.6.1 with R 4.5.2.
The examples need the R6 package, which is not part of base R. Install it once
with install.packages("R6"); the
installing packages section of the
introduction explains the details.
A first class
R6Class takes a class name and a public list that
holds fields and functions. A field is a value stored in every object, and a
method is a function that receives the object as self.
Counter$new() creates an instance, and the methods are called
with $. Because the object is an environment, it is modified in
place rather than replaced.
library(R6)
Counter <- R6Class("Counter",
public = list(
value = 0,
increment = function(by = 1) {
self$value <- self$value + by
invisible(self)
}
)
)
first <- Counter$new()
first$increment()
first$increment(4)
cat("value:", first$value, "\n")
second <- first
second$increment()
cat("first after second increment:", first$value, "\n")
cat("same object:", identical(first, second), "\n")
The counter reaches 5 after the two increments. The assignment
second <- first copies the reference, not the object, so the
next increment through second changes first as well
and the value becomes 6. identical returns TRUE
because both names point to the same environment. A method returns
invisible(self) so that a call at the top level does not print
the object after the method has done its work.
$ Rscript counter.R value: 5 first after second increment: 6 same object: TRUE
Initialization and private members
initialize is a method that $new calls with the
arguments that were passed to it. Its usual job is to store the arguments in
fields. The private list holds members that outside code cannot
reach: a private field or method is visible only through private$
inside the class. R6 requires every name in the public, private, and active
lists to be unique, so a private field and a public method cannot share a
name.
library(R6)
Account <- R6Class("Account",
public = list(
owner = NULL,
initialize = function(owner, balance = 0) {
self$owner <- owner
private$funds <- balance
invisible(self)
},
deposit = function(amount) {
private$funds <- private$funds + amount
invisible(self)
},
balance = function() private$funds,
print = function(...) {
cat("Account:", self$owner, "-",
sprintf("%.2f EUR", private$funds), "\n")
invisible(self)
}
),
private = list(
funds = 0
)
)
account <- Account$new("Alice", 100)
account$deposit(50)
account$print()
cat("owner:", account$owner, "\n")
cat("balance:", account$balance(), "\n")
The private field is called funds because the public method owns
the name balance. After a deposit of 50 the balance method
returns 150, and the print method writes a line without exposing the field.
Code outside the class can read and write account$owner but has
no way to touch private$funds; the only route is through
deposit and balance. The print method returns
invisibly for the same reason as the counter method, so that the object is not
printed a second time when the call returns.
$ Rscript account.R Account: Alice - 150.00 EUR owner: Alice balance: 150
Copying and cloning
Because assignment copies a reference, a real copy needs clone.
A shallow clone creates a new object and copies the fields, but a field that
holds another R6 object still points to the original. A deep clone copies
those nested objects as well, provided their classes support deep cloning.
This distinction decides whether a change in a copy can leak back into the
original.
library(R6)
Account <- R6Class("Account",
public = list(
owner = NULL,
initialize = function(owner, balance = 0) {
self$owner <- owner
private$funds <- balance
invisible(self)
},
deposit = function(amount) {
private$funds <- private$funds + amount
invisible(self)
},
balance = function() private$funds
),
private = list(funds = 0)
)
Team <- R6Class("Team",
public = list(
lead = NULL,
initialize = function(lead) {
self$lead <- lead
invisible(self)
}
)
)
team <- Team$new(Account$new("Alice", 100))
shallow <- team$clone()
shallow$lead$deposit(50)
cat("after shallow clone:", team$lead$balance(), "\n")
deep <- team$clone(deep = TRUE)
deep$lead$deposit(10)
cat("after deep clone:", team$lead$balance(), "\n")
cat("deep copy balance:", deep$lead$balance(), "\n")
The shallow clone shares the lead account, so its deposit raises the original
balance to 150. The deep clone gets its own account, so the later deposit of
10 leaves the original at 150 and only the copy reaches 160. The team object
is a container, and the account inside it is the value that matters; a plain
list field would be copied on modification because lists follow R's
copy-on-modify rule, but an environment field is shared. When a class holds
other R6 objects, clone(deep = TRUE) is usually the safe choice.
$ Rscript clone.R after shallow clone: 150 after deep clone: 150 deep copy balance: 160
Active bindings
An active binding looks like a field but runs a function on every read or
write. The function receives value when the binding is assigned
and leaves it missing when the binding is read, so missing(value)
separates the two cases. Active bindings are the place for computed
properties and for validation that must run on every assignment.
library(R6)
Account <- R6Class("Account",
public = list(
owner = NULL,
initialize = function(owner, balance = 0) {
self$owner <- owner
private$funds <- balance
invisible(self)
},
deposit = function(amount) {
private$funds <- private$funds + amount
invisible(self)
}
),
private = list(funds = 0),
active = list(
balance = function(value) {
if (missing(value)) {
return(private$funds)
}
private$funds <- max(0, value)
}
)
)
account <- Account$new("Alice", 100)
cat("balance:", account$balance, "\n")
account$balance <- 250
cat("after set:", account$balance, "\n")
account$balance <- -40
cat("after negative set:", account$balance, "\n")
Reading account$balance runs the getter and returns 100, without
parentheses. Assigning 250 runs the setter and stores the value, and assigning
a negative number stores zero because the setter clamps it. The rule lives in
one place, so every assignment passes through it, including assignments made
by other methods. A computed property, such as a balance converted to another
currency, would use the same pattern and would not need a stored field.
$ Rscript active.R balance: 100 after set: 250 after negative set: 0
Inheritance
inherit names the parent class. The subclass receives every
public and private member, and super$ calls the parent version of
a method. The class attribute of the object is a vector that
starts with the subclass name and continues with the parent and
R6, so inherits works as it does for S3 objects.
library(R6)
Account <- R6Class("Account",
public = list(
owner = NULL,
initialize = function(owner, balance = 0) {
self$owner <- owner
private$funds <- balance
invisible(self)
},
deposit = function(amount) {
private$funds <- private$funds + amount
invisible(self)
},
balance = function() private$funds,
print = function(...) {
cat(sprintf("%s: %s - %.2f EUR\n",
class(self)[1], self$owner, private$funds))
invisible(self)
}
),
private = list(funds = 0)
)
SavingsAccount <- R6Class("SavingsAccount",
inherit = Account,
public = list(
rate = NULL,
initialize = function(owner, balance = 0, rate = 0.02) {
super$initialize(owner, balance)
self$rate <- rate
invisible(self)
},
add_interest = function() {
super$deposit(self$balance() * self$rate)
invisible(self)
}
)
)
savings <- SavingsAccount$new("Bob", 1000, rate = 0.03)
savings$add_interest()
savings$print()
cat("rate:", savings$rate, "\n")
cat("is account:", inherits(savings, "Account"), "\n")
The savings account adds a rate field and an interest method, and it reuses
the constructor and the deposit method of the parent through
super$. A balance of 1000 at a rate of 0.03 grows to 1030. The
print method is inherited, and class(self)[1] makes it write the
actual class name, so the same method prints both accounts and savings
accounts correctly. The private field is inherited too, but a subclass still
reaches it only through the parent's methods, which keeps the encapsulation
intact.
$ Rscript inheritance.R SavingsAccount: Bob - 1030.00 EUR rate: 0.03 is account: TRUE
A bank of accounts
An R6 object can hold other R6 objects in its fields. The next script adds a
Bank class whose accounts field is a list of
Account objects. The open method creates an account,
appends it to the list, and returns it invisibly, and total sums
the balances with vapply, which returns a numeric vector.
library(R6)
Account <- R6Class("Account",
public = list(
owner = NULL,
initialize = function(owner, balance = 0) {
self$owner <- owner
private$funds <- balance
invisible(self)
},
deposit = function(amount) {
private$funds <- private$funds + amount
invisible(self)
},
balance = function() private$funds,
print = function(...) {
cat(sprintf("%s: %s - %.2f EUR\n",
class(self)[1], self$owner, private$funds))
invisible(self)
}
),
private = list(funds = 0)
)
Bank <- R6Class("Bank",
public = list(
name = NULL,
accounts = list(),
initialize = function(name) {
self$name <- name
invisible(self)
},
open = function(owner, balance = 0) {
account <- Account$new(owner, balance)
self$accounts[[length(self$accounts) + 1]] <- account
invisible(account)
},
total = function() {
sum(vapply(self$accounts,
function(account) account$balance(), numeric(1)))
}
)
)
bank <- Bank$new("ZetCode Bank")
bank$open("Alice", 1200)
bob <- bank$open("Bob", 800)
bob$deposit(150)
cat("accounts:", length(bank$accounts), "\n")
cat("total:", bank$total(), "\n")
The caller keeps the account returned for Bob and deposits 150 into it. The
deposit is visible through the bank as well, because the list holds a
reference to the same object rather than a copy, so the total is 1200 plus
950. The vapply template numeric(1) makes the call
fail if a method ever returns something other than a single number.
$ Rscript accounts-list.R accounts: 2 total: 2150
A complete example
The final script adds the savings account to the bank. The open
method gains a flag that selects the class to create, and a new
print method calls each account's own print method. Composition
like this is the usual way to build a larger object from smaller R6 objects.
library(R6)
Account <- R6Class("Account",
public = list(
owner = NULL,
initialize = function(owner, balance = 0) {
self$owner <- owner
private$funds <- balance
invisible(self)
},
deposit = function(amount) {
private$funds <- private$funds + amount
invisible(self)
},
balance = function() private$funds,
print = function(...) {
cat(sprintf("%s: %s - %.2f EUR\n",
class(self)[1], self$owner, private$funds))
invisible(self)
}
),
private = list(funds = 0)
)
SavingsAccount <- R6Class("SavingsAccount",
inherit = Account,
public = list(
rate = NULL,
initialize = function(owner, balance = 0, rate = 0.02) {
super$initialize(owner, balance)
self$rate <- rate
invisible(self)
},
add_interest = function() {
super$deposit(self$balance() * self$rate)
invisible(self)
}
)
)
Bank <- R6Class("Bank",
public = list(
name = NULL,
accounts = list(),
initialize = function(name) {
self$name <- name
invisible(self)
},
open = function(owner, balance = 0, savings = FALSE) {
account <- if (savings) {
SavingsAccount$new(owner, balance)
} else {
Account$new(owner, balance)
}
self$accounts[[length(self$accounts) + 1]] <- account
invisible(account)
},
total = function() {
sum(vapply(self$accounts,
function(account) account$balance(), numeric(1)))
},
print = function(...) {
cat("Bank:", self$name, "with", length(self$accounts),
"accounts\n")
for (account in self$accounts) {
account$print()
}
cat("total:", sprintf("%.2f EUR", self$total()), "\n")
invisible(self)
}
)
)
bank <- Bank$new("ZetCode Bank")
bank$open("Alice", 1200)
savings <- bank$open("Bob", 800, savings = TRUE)
savings$add_interest()
bank$print()
cat("average:", round(bank$total() / length(bank$accounts), 2), "\n")
The bank opens a plain account for Alice and a savings account for Bob, and
open returns the new account so that the caller can keep using
it; assigning an invisible result still works, and only printing is
suppressed. Bob's 800 earns two percent and becomes 816, so the total is 2016
and the average is 1008. The print loop relies on each account knowing how to
print itself, so plain and savings accounts need no special handling.
$ Rscript bank.R Bank: ZetCode Bank with 2 accounts Account: Alice - 1200.00 EUR SavingsAccount: Bob - 816.00 EUR total: 2016.00 EUR average: 1008
Next steps
The S3 classes article covers the value-based system
that most of base R uses, and the S4 classes article
adds typed slots and validity checks. The
packages article explains how R6 is installed
and attached, and the apply family article
covers the vapply call used by the bank. The
functions article explains the closures and
argument matching that make R6 methods work.
Source
In this article we have created R6 classes with public fields and methods, and
seen that assignment copies a reference rather than an object. We hid state in
private members, initialized objects in initialize, and compared
shallow and deep clones. Active bindings gave a field-like interface with a
validation rule, inheritance reused the parent constructor and methods, and
the final bank combined the classes in a container. The object-oriented
section ends here; the creating packages
article shows how a package with an S3 method is built, documented, and
checked, and the packages article explains how
R6 and the other add-on packages are installed and attached.
Author
List all R Language tutorials.