1. The Object Factory
The R6 system provides a way of storing data and objects within the same variable.
2. teapot
Recall the teapot from Chapter 1. This contains the teapot-related data fields like the capacity, and teapot functionality like pour and refill methods.
The first step in working with R6 is to create a class generator for each of your objects.
3. class generators
A class generator is a template that describes what data can be stored in the object, and what functions can be applied to the object. It is also used to create the specified objects. For this reason, I like to call class generators
4. class generators
"factories". For the rest of the course, the terms "class generator" and "factory" will be used interchangeably.
Throughout the next three chapters, we're going to look at
5. microwave
a real-world example of a microwave oven. The class generator
6. factory
is our microwave oven factory, and
7. factory
the factory is used to create microwave oven objects.
Lets look at some code.
8. library(R6)
Factories are defined using the R6Class function.
The first argument to R6Class is the name of the class. By convention, this should be in UpperCamelCase.
The second argument you need to know about is called "private". This stores the object's data. It is always a list, and each of the elements of the list must be named. Here you can see that the thing has two fields.
9. Coming soon ...
There are two more arguments, named "public" and "active", that I'll describe in later videos.
10. a_thing
The second step to working with R6 is to create some objects. You do this by calling the new method of the factory. Since it is a factory, you can churn out as many of these objects as you like.
11. Summary
To summarize, you need to load the R6 package to work with R6. You define what the object contains using the R6Class function. This takes a string naming the class, which should be UpperCamelCase. Data fields for the object are stored in a named list variable called private. To create an object, you call the factory's new method.
12. Let's practice!