Unlocking the Power of Reference Classes in R Programming
What are Reference Classes?
If you’re familiar with object-oriented programming in languages like C++, Java, or Python, you’ll feel right at home with R’s reference classes. Unlike S3 and S4 classes, methods in reference classes belong to the class itself, not generic functions. Internally, reference classes are implemented as S4 classes with an added environment.
Defining a Reference Class
Defining a reference class is similar to defining an S4 class. Instead of using setClass()
, you use the setRefClass()
function. Any member variables, or fields, must be included in the class definition. Fields are analogous to slots in S4 classes.
For example, let’s define a Student
class with three fields: name
, age
, and GPA
.
Creating Reference Objects
The setRefClass()
function returns a generator function, which is used to create objects of that class. This allows you to create multiple objects from a single class definition.
Accessing and Modifying Fields
Fields can be accessed using the $
operator, and modified by reassignment. However, be aware that R objects are copied when assigned to a new variable or passed to a function (pass by value). This is not the case with reference objects, where only a single copy exists and all variables reference the same copy. To make a copy, use the copy()
method.
Reference Methods
Methods are defined for a reference class and do not belong to generic functions. All reference classes inherit from the superclass envRefClass
, which provides predefined methods like copy()
, field()
, and show()
. You can also create your own methods during class definition by passing a list of function definitions to the methods
argument of setRefClass()
.
In our example, we defined two methods, inc_age()
and dec_age()
, which modify the age
field. Note the use of the non-local assignment operator <<-
to ensure that the age
field is modified correctly.
Putting it all Together
With reference classes, you can create powerful, flexible objects that simplify your R programming workflow. By understanding how to define, create, and manipulate reference objects, you can unlock new possibilities for your data analysis and visualization tasks.