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?
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
What about Reference Classes? it's not S3 and some consider it syntactical sugar on top of S4, but it's a lot of sugar.
For a short example, check this answers to a question I asked here a few months ago.
I still have to find out how to write Rd files for such classes.
来源:https://stackoverflow.com/questions/6450803/class-in-r-s3-vs-s4