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
R6::R6Class()object, specifically the initialization method
$new(). For example,
foo = Foo$new(bar = 1)creates a new object of class
Foo, setting the
barargument of the constructor to the value
1. Most objects in mlr3 are created through special functions (e.g. ‘lrn(“regr.rpart”)’) that are also referred to as sugar functions.
- Objects have mutable state, which is encapsulated in their fields, which can be accessed through the dollar operator.
We can access the
barvalue in the
foo$barand 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
$trainmethod 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. The public fields and methods define the API to interact with the object. Private methods are only relevant for you if you want to extend mlr3, e.g. with new learners.
- R6 objects are internally environments, and as such have reference semantics.
foo2 = foodoes not create a copy of
foo2, but another reference to the same actual object. Setting
foo$bar = 3will also change
3and vice versa.
- To copy an object, use the
$clone()method and the
deep = TRUEargument for nested objects, for example,
foo2 = foo$clone(deep = TRUE).