2.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 have done any object-oriented programming before, R6 should feel familiar. We focus on the parts of R6 that you need to know to use mlr3 here.

  • Objects are created by calling the constructor of an R6Class() object, specifically the $new() method. 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, which can be accessed through the dollar operator. We can access the bar value in the Foo class through foo$bar and set its value by assigning the field, e.g. foo$bar = 2.
  • In addition to fields, objects expose methods that may allow to inspect the object’s state, retrieve information, or perform an action that may change the internal state of the object. For example, the $train method of a learner changes the internal state of the learner by building and storing a trained model, which can then be used to make predictions given data.
  • Objects can have public and private fields and methods. In mlr3, you can only access the public variables and methods. Private fields and methods are only relevant to change or extend mlr3.
  • R6 variables are references to objects rather than the actual objects, which are stored in an environment. For example, foo2 = foo does not create a copy of foo in foo2, but another reference to the same actual object. Setting foo$bar = 3 will also change foo2$bar to 3 and vice versa.
  • To copy an object, use the $clone() method and the deep = TRUE argument for nested objects, for example, foo2 = foo$clone(deep = TRUE).

For further information see wiki for short descriptions and links to the respective repositories.

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