class in R: S3 vs S4

喜欢而已 提交于 2019-11-29 19:40:19

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

mariotomo

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!