R Tutorial: Object-Oriented Programming in R: S3 & R6 (part 3)
Part 3 of our course video for Object-Oriented Programming in R: S3 & R6 by Richie Cotton. Learn more about the course here: https://www.datacamp.com/courses/object-oriented-programming-in-r-s3-and-r6 Learn how to define R6 classes, and to create R6 objects. You'll also learn about the structure of R6 classes, and how to separate the user interface from the implementation details. The R6 system provides a way of storing data and objects within the same variable. 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. 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 "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 a real-world example of a microwave oven. The class generator is our microwave oven factory, and the factory is used to create microwave oven objects. Lets look at some code. 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. There are two more arguments, named "public" and "active", that I'll describe in later videos. 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. 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.
Download
0 formatsNo download links available.