Chapter 15 S3 Classes

So far, we’ve only done functional programming with R. This means we’ve created variables and functions and manipulated them. However, we can do object oriented programming in R, too! Object-oriented programming (OOP) is a computer programming practice in which programmers can define custom data structures. Such a data structure usually contains some data to store (so called attributes), as well as methods. We call this data structure a class. We can think of a class like a blueprint of something, say a student. A class “student” has attributes like a name, an age, a field of study, some grades, and so on. In addition, a class has methods that act on these attributes. Methods can be seen as “skills” of a class. For example, a student is able to say his name, age and field of study, or to compute his mean grade.

A class is a blueprint for an object. From our class “student” we can hence create an actual student object that would have a specific name, say Liam. Actually, we can create as many student objects as we want from the blueprint class “student”. We could therefore create more student objects from our class, for example Susan, Paul, Carl etc. The class is the abstract blueprint, the object is the actual instance of a class.

While most programming languages have a single class system, R has three class systems. Namely, S3, S4 and more recently Reference class systems. In this tutorial, we’ll focus on S3 classes, as this is the most popular and prevalent class.