在R:S3 vs S4 [英] class in R: S3 vs S4

查看:131
本文介绍了在R:S3 vs S4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中创建一个类,我应该使用S3还是S4类?



我读了很多不同的东西,另一个?

解决方案

S3只能调度它的第一个参数,而S4可以调度多个参数。如果你想能够写函数 foo 的方法,如果给定类bar或给定类bar 的对象foobar对象barfoofoobar,那么S4提供了一个更好的方法来处理这种复杂性。 / p>

S3非常简单易于实现,但并不是真正的面向对象的系统。这种简单性是以强制执行属于类的对象具有正确的组件/槽等为代价的。使用S3我可以做 class(obj)< - lm和方法分派将在传递 obj 时使用lm类的方法,但不能保证 obj 真的是类lm的对象。



S3很容易实现,记录和需要程序员方面的额外知识。



哪些使用只能是你可以决定。例如,道格·贝茨(Doug Bates,2003)曾表示,对于新项目,他将使用S4而不是S3。我还没有需要使用除了S3方法之外的任何东西。



所以我坐下来想想要操作的类和方法的类型这些类。想想你想要的功能,这可能指向一个系统或其他系统。



Douglas Bates。 将包转换为S4 。 R News,3(1):6-8,2003年6月


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

这篇关于在R:S3 vs S4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆