3.1 Quick R6 Intro for Beginners

R6 is one of R’s more recent dialects for object-oriented programming (OO). It addresses shortcomings of earlier OO implementations in R, such as S3, which we used in mlr. If you are not familiar with OO programming, it might take a bit to find your way around, but if you have done OO in another language, R6 should feel familiar. We focus on the parts of R6 that you need to know to use mlr3 here without going into further detail.

  • Objects are created by calling the constructor of an R6Class() object. For example foo = Foo$new(bar = 1) creates a new object of class Foo, setting the bar argument of the constructor to 1.
  • Classes have mutable state which is encapsulated in their fields. Continuing with the previous example, assuming that the constructor sets the public field bar to 1, we can access its value through the dollar operator: foo$bar or foo$bar = 2.
  • In addition to fields, objects expose methods that may allow to inspect the object’s state or retrieve information and perform an action that may change the internal state of the object. As an example, the $train method of a learner changes the internal state by producing and storing a trained model.
  • Objects can have public and private fields and methods. As a user of mlr3, you can only access the public variables and methods – the private are only relevant if you want to change or extend mlr3.
  • R6 variables are references to the actual object in the environment; they do not hold the object itself. For example foo2 = foo does not create a copy of foo and store it in foo2, but only the reference to the actual object. foo and foo2 refer to the same object, and setting foo$bar = 3 will also change foo2$bar to 3.
  • To copy an object, use the $clone() method; use the deep = TRUE argument for nested objects, for example foo2 = foo$clone(deep = TRUE).

For more details on R6, have a look at the R6 vignettes.