The R6 Class System

[This article was first published on Revolutions, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R is an object-oriented language with several object-orientation systems. There's the original (and still widely-used) S3 class system based on the “class” attribute. There's the somewhat stricter, signature-based S4 class system. There are reference classes (also called R5), which provide R objects with multiple references without duplicating data in memory. And now there's the R6 class system, implemented as an R package by Winston Chang,

So why yet another class system for R? As Winston explains in his useR!2017 talk embedded below, the S3 and S4 class systems are functional object-oriented systems, where class methods are separate from objects, and objects are not mutable (that is, they can't be modified directly by methods; you have to assign modified values to the object directly). The R6 system, by contrast, is an encapsulated object oriented system akin to those in Java or C++, where objects contain methods in addition to data, and those methods can modify objects directly. 

The big advantage of R6 is that it makes it much easier to implement some common data structures in a user-friendly manner. For example, to implement a stack “pop” operation in S3 or S4 you have to do something like this:

x <- topval(mystack)
mystack <- remove_top(mystack)

In R6, the implementation is much simpler to use:

x <- mystack$pop()

That single statement both returns the top value (as x) from the stack mystack, but also modifies the stack in the process (minus the popped element).

Despite being first released over 3 years ago, the R6 isn't widely known. It is widely used, however: it's used to manage session state in Shiny and mrsdeploy, to manage database connections in dplyr, and to represent system processes in the processx package. In fact, the R6 package is the most downloaded CRAN package, according according to Rdocumentation Trends.

The R6 package is available on CRAN, and it also comes pre-installed in Microsoft R. If you'd like to start using R6, the vignette Introduction to R6 Classes is a great place to start. You can also check out the development of R6 at the R6 Github repository.

To leave a comment for the author, please follow the link and comment on their blog: Revolutions.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)