R Language OOP using R6

The R language is used mostly by statisticians and data people. There are at least four, quite different, ways to write object oriented code in R — S3, S4, R5, R6. By far my favorite approach is to use the relatively new R6 version 2 (released October 2014).

Compared to the alternatives, the R6 OOP approach and syntax is closest to OOP in languages like C# and Python. Here’s a quick example. First, I created a text file that defines a Car class and saved it as CarClass.R on my machine:

# CarClass.R


Car <- R6Class("Car",
  public = list(
    make = NULL,
    price = NULL,
    initialize = function(ma, pr) {
      self$make <- ma
      self$price <- pr
    setMake = function(ma) { self$make <- ma },
    # setPrice = function(pr) { self$price <- pr },
    display = function() {
      cat("Make = ", self$make,
        " Price = ", self$price, "\n")

In even this tiny demo, there’s a lot going on. The R6 package was pre-installed in the R version 3.1.2 I was using. The Car class has public fields “make” and “price”, a constructor named initialize, and methods “setMake” and “display”. Because the fields are public, I don’t really need function setMake.


To call the Car class, I did this:

> setwd("C:\\Data\\Junk\\RStuff")
> source("CarClass.R")

By running the CarClass.R script, the definition of a Car class is created and can be used. To create a Car object and display it:

> someCar = Car$new("Audi", 40000)
> # display using class defined display()
> someCar$display()
Make =  Audi  Price =  40000 
> # display using built-in print()
> print(someCar)

Objects created using R6 get a built-in print() capability. To modify the Car object:

> someCar$setMake("BMW")
> someCar$price  = 50000
> someCar$display()
Make =  BMW  Price =  50000

I modified the Car make field using the set-function, but modified the public price field directly. R6 objects are reference objects so you have to be careful when assigning one object to another. My bottom line: R6, very nice.

This entry was posted in Machine Learning, Miscellaneous. Bookmark the permalink.