The R6 package provides a type of class which is similar to R’s standard reference classes, but it is more efficient and doesn’t depend on S4 classes and the methods package.
R6 classes are similar to R’s standard reference classes, but are lighter weight, and avoid some issues that come along with using S4 classes (R’s reference classes are based on S4). For more information about speed and memory footprint, see the Performance vignette.
Unlike many objects in R, instances (objects) of R6 classes have reference semantics. R6 classes also support:
Why the name R6? When R’s reference classes were introduced, some users, following the names of R’s existing class systems S3 and S4, jokingly called the new class system R5. Although reference classes are not actually called R5, the name of this package and its classes takes inspiration from that name.
Here’s how to create a simple R6 class. The public
argument is a list of items, which can be functions and non-functions. Functions will be used as class methods.
library(R6)
Person <- R6Class("Person",
public = list(
name = NA,
hair = NA,
initialize = function(name, hair) {
if (!missing(name)) self$name <- name
if (!missing(hair)) self$hair <- hair
greet()
},
set_hair = function(val) {
hair <<- val
},
greet = function() {
cat(paste0("Hello, my name is ", name, ".\n"))
}
)
)
To instantiate an object of this class, use $new()
:
ann <- Person$new("Ann", "black")
#> Hello, my name is Ann.
ann
#> <Person>
#> Public:
#> greet: function
#> hair: black
#> initialize: function
#> name: Ann
#> self: environment
#> set_hair: function
The $new()
method creates the object and calls the initialize()
method, if it exists.
Inside methods of the class, self
refers to the object. Public members of the object (all you’ve seen so far) can be referred to with self$x
, and assignment can be done with self$x <- y
. Assignment can also be done with <<-
, as in x <<- y
– but in this case, the object member’s name must be different from the names of variables in the method.
Once the object is instantiated, you can access values and methods with $
:
ann$hair
#> [1] "black"
ann$greet()
#> Hello, my name is Ann.
ann$set_hair("red")
ann$hair
#> [1] "red"
Implementation note: The R6 object is basically an environment with the public members in it. The self
object is bound in that environment, and is simply a reference back to that environment.
In the previous example, all the members were public. It’s also possible to add private members:
Queue <- R6Class("Queue",
public = list(
initialize = function(...) {
for (item in list(...)) {
add(item)
}
},
add = function(x) {
queue <<- c(queue, list(x))
invisible(self)
},
remove = function() {
if (length() == 0) return(NULL)
# Can use private$queue for explicit access
head <- private$queue[[1]]
private$queue <- private$queue[-1]
head
}
),
private = list(
queue = list(),
length = function() base::length(queue)
)
)
q <- Queue$new(5, 6, "foo")
The public members can be accessed as usual:
# Add and remove items
q$add("something")
q$add("another thing")
q$add(17)
q$remove()
#> [1] 5
q$remove()
#> [1] 6
However, private members can’t be accessed directly:
q$queue
#> NULL
q$length()
#> Error: attempt to apply non-function
# Actually, there is a way:
q$private$queue
#> [[1]]
#> [1] "foo"
#>
#> [[2]]
#> [1] "something"
#>
#> [[3]]
#> [1] "another thing"
#>
#> [[4]]
#> [1] 17
Unless there’s a compelling reason otherwise, methods should return self
because it makes them chainable. For example, the add()
method returns self
so you can chain them together:
q$add(10)$add(11)$add(12)
On the other hand, remove()
returns the value removed, so it’s not chainable:
q$remove()
#> [1] "foo"
q$remove()
#> [1] "something"
q$remove()
#> [1] "another thing"
q$remove()
#> [1] 17
Implementation note: When private members are used, the public environment is a child of the private environment, and the private
object points to the private environment. Although public and private methods are bound (that is, they can be found) in their respective environments, the enclosing environment for all of those methods is the public environment. This means that private methods “run in” the public environment, so they will find public objects without needing an explicit self$xx
.
Active bindings look like fields, but each time they are accessed, they call a function. They are always publicly visible.
Numbers <- R6Class("Numbers",
public = list(
x = 100
),
active = list(
x2 = function(value) {
if (missing(value)) return(x * 2)
else self$x <- value/2
},
rand = function() rnorm(1)
)
)
n <- Numbers$new()
n$x
#> [1] 100
When an active binding is accessed as if reading a value, it calls the function with value
as a missing argument:
n$x2
#> [1] 200
When it’s accessed as if assigning a value, it uses the assignment value as the value
argument:
n$x2 <- 1000
n$x
#> [1] 500
If the function takes no arguments, it’s not possible to use it with <-
:
n$rand
## [1] 0.2648
n$rand
## [1] 2.171
n$rand <- 3
## Error: unused argument (quote(3))
Implementation note: Active bindings are bound in the public environment. The enclosing environment for these functions is also the public environment.
One R6 class can inherit from another. In other words, you can have super- and sub-classes.
Subclasses can have additional methods, and they can also have methods that override the superclass methods. In this example of a queue that retains its history, we’ll add a show()
method and override the remove()
method:
# Note that this isn't very efficient - it's just for illustrating inheritance.
HistoryQueue <- R6Class("HistoryQueue",
inherit = Queue,
public = list(
show = function() {
cat("Next item is at index", head_idx + 1, "\n")
for (i in seq_along(queue)) {
cat(i, ": ", queue[[i]], "\n", sep = "")
}
},
remove = function() {
if (length() - head_idx == 0) return(NULL)
head_idx <<- head_idx + 1
queue[[head_idx]]
}
),
private = list(
head_idx = 0
)
)
hq <- HistoryQueue$new(5, 6, "foo")
hq$show()
#> Next item is at index 1
#> 1: 5
#> 2: 6
#> 3: foo
hq$remove()
#> [1] 5
hq$show()
#> Next item is at index 2
#> 1: 5
#> 2: 6
#> 3: foo
hq$remove()
#> [1] 6
Superclass methods can be called with super$xx()
. The CountingQueue
(example below) keeps a count of the total number of objects that have ever been added to the queue. It does this by overriding the add()
method – it increments a counter and then calls the superclass’s add()
method, with super$add(x)
:
CountingQueue <- R6Class("CountingQueue",
inherit = Queue,
public = list(
add = function(x) {
total <<- total + 1
super$add(x)
},
get_total = function() total
),
private = list(
total = 0
)
)
cq <- CountingQueue$new("x", "y")
cq$get_total()
#> [1] 2
cq$add("z")
cq$remove()
#> [1] "x"
cq$remove()
#> [1] "y"
cq$get_total()
#> [1] 3
R6 classes provide capabilities that are common in other object-oriented programming languages. They’re similar to R’s built-in reference classes, but are simpler, smaller, and faster.