I am a python programmer, and this is my first day working with R.
I am trying to write a class with a constructor and three methods, and I am struggling.
In python, it’s easy:
class MyClass:
def __init__(self):
self.variableA = 1
self.variableB = 2
def hello(self):
return "Hello"
def goodbye(self):
return "Goodbye"
def ohDear(self):
return "Have no clue"
I can’t find anything that shows me how to do something as simple as this in R. I would appreciate it if someone could show me one way to do this ?
Many thanks
R actually has lots of different object oriented implementations. The three native ones (as mentioned by @jthetzel) are S3, S4 and Reference Classes.
S3 is a lightweight system that allows you to overload a function based upon the class of the first argument.
Reference Classes are designed to more closely resemble classes from other programming languages. They more or less replace S4 classes, which do the same thing but in a more unwieldy fashion.
The R.oo package provides another system, and the proto package allows prototype-oriented programming, which is like lightweight OOP. There was a sixth system in the OOP package, but that is now defunct. The more recent R6 package “is a simpler, faster, lighter-weight alternative to R’s built-in reference classes”.
For new projects, you’ll usually only want to use S3 and Reference classes (or possibly R6).
python classes most easily translate to reference classes. They are relatively new and (until John Chambers finishes his book on them) the best reference is the
?ReferenceClassespage. Here’s an example to get you started.To define a class, you call
setRefClass. The first argument is the name of the class, and by convention this should be the same as the variable that you assign the result to. You also need to passlists to the arguments “fields” and “methods”.There are a few quirks.
initialize.<<-).This creates a class generator:
Then you create instances of the class by calling the generator object.
Further reading: the OO field guide chapter of Advanced R.