The R programming language has several ways to write object oriented code, including list encapsulation, S3, S4, RC, and R6. In general, the best approach is to use the RC (“reference classes”) technique.

Somewhat surprisingly, there are very few what I consider good examples of how to write S3 code. By good I mean skipping unneeded chit-chat and showing example code.

Here I define a Person class where the object will have a lastName, an age, and a height. The “this” is a variable to reference the object and isn’t a reserved word so I could have used “me” or “self”. Notice that an S3 class is a function definition with a bit of extra plumbing with “class” and “append” keywords. (Note: I’m using ‘=’ instead of the preferred arrow operator so my annoying blog software doesn’t go crazy trying to interpret as HTML).

The class doesn’t have any methods. Methods in S3 are optional but useful so next my demo script adds a display method:

Each method in S3 needs (at least) two functions. The first of the pair essentially registers the name (here, “display”) of the method. The second function contains the implementation code. Notice the wacky “methodName.className” pattern of display.Person(). That’s just the magic syntax to use.

Next the demo script adds a method to set the value of a Person lastName: