I want to create a class in R, should I use S3 or S4 class?
I read a lot of different things about them, is there one superior to the other one?
S4 class is defined using the setClass() function. In R terminology, member variables are called slots. While defining a class, we need to set the name and the slots (along with class of the slot) it is going to have.
An S3 class is the most prevalent and used class in R programming. It is easy to implement this class and most of the predefined classes are of this type. An S3 object is basically a list with its class attributes assigned some names. And the member variable of the object created is the components of the list.
The class() function in R is used to return the values of the class attribute of an R object.
Unlike most other programming languages, R has a three-class system. These are S3, S4, and Reference Classes.
S3 can only dispatch on it's first argument, whereas S4 can dispatch on multiple arguments. If you want to be able to write methods for function foo
that should do different things if given an object of class "bar"
or given objects of class "bar"
and "foobar"
, or given objects of class "barfoo"
and "foobar"
, then S4 provides a far better way to handle such complexities.
S3 is very simple and easy to implement, but isn't really a formal object oriented system. That simplicity comes at the cost of enforcing that objects belonging to a class have the correct components/slots etc. With S3 I can do things like class(obj) <- "lm"
and method dispatch will use methods for the "lm"
class when passed obj
, but there is no guarantee that obj
really is an object of class "lm"
.
S3 is easy to implement, document and requires less extra knowledge on the part of the programmer.
Which to use can only be something you can decide. Doug Bates (2003) has said, for example, that for new projects he would use S4 over S3. I haven't yet had a need to use anything other than S3 methods.
So I would sit down and think about the sorts of classes and methods you want to operate on those classes. Think about the functionality you want, and that will probably point towards one system or the other.
Douglas Bates. Converting packages to S4. R News, 3(1):6-8, June 2003
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With