Object Oriented Programming in R with S4

The R language is used for data analysis. There are three main ways to do OOP in R. The techniques have cryptic names S3, S4, and R6. The S4 technique is the most common.

RLanguageOOPwithS4

Whenever I’m trying to figure out OOP in some language, my first example is always to define a Person class. In S4 one possibility is:

# personDef.R

Person = setClass(
 "Person",

 representation(
  lastName = "character",
  age = "integer",
  payRate = "numeric"
 ),

 prototype = list(
  lastName = "NONAME",
  age = as.integer(-1),
  payRate = 0.0
 )
) # Person

# --- methods

setGeneric(name="bumpRate",
 def=function(obj, percent) {
  standardGeneric("bumpRate")
 }
)

setMethod(f="bumpRate",
 signature="Person",
 definition=function(obj, percent) {
   obj@payRate = obj@payRate * (1.0 + percent)
   return(obj)
 }
)

After this file is saved, Person objects could be created like so:

source("personDef.R")
p1 = new("Person")
p2 = new("Person", lastName="Smith",
          age=as.integer(30),
          payRate=33.33)

print(p1)
print(p2)

All fields and methods are public and accessible using the ‘@’ token so code like this works:

p1@lastName = "Jones"
p1@age = as.integer(26)
p1@payRate = 22.45

p2 = bumpRate(p2, 0.07)

Notice that the bumpRate() method is called quite differently that most other languages.

Bottom line: OOP in R using S4 is completely usable but a bit clunkier than OOP in more modern languages such as C# and Python.

Advertisements
This entry was posted in Machine Learning. Bookmark the permalink.