R Language OOP Classes using RC

There are several ways to write object oriented programming code in the R language. You can simulate OOP using a list of variables and functions. You can use the old S3 or S4 mechanisms. You can use the current standard technique of Reference Classes (RC). Or you can use the new add-on R6 package.


I coded up a Person class demo using the RC mechanism. The key calling code is:

cat("\nBegin R reference class demo \n\n")

p = PersonClass$new(lastName = "Smith",
      dateBirth = "1990-03-17",
      height = 68.5,
      weight = as.integer(175))
a = p$getAge()

a = p$getAge()
cat("Age today = ", a, "\n")

cat("\nEnd demo \n")

The associated output is:

Begin R reference class demo 

Last name  :  Smith 
Birth date :  1990-03-17 
Height     :  68.5 in 
Weight     :  175 lbs 

Last name  :  Smith 
Birth date :  1990-03-17 
Height     :  174 cm 
Weight     :  79 kg 

Age today =  26 

End demo

It was very easy for me to use RC classes because I have a ton of experience with OOP in other languages (C#, Java, Python in particular) and RC OOP somewhat resembles other OOP models.

The bottom line is that RC is my OOP mechanism of choice for the R language.

This entry was posted in R Language. Bookmark the permalink.