“S3 方法"是什么?在 R 中是什么意思? [英] What does "S3 methods" mean in R?
问题描述
由于我对 R 比较陌生,所以我不知道 S3 方法和对象是什么.我发现有 S3 和 S4 对象系统,如果可能的话,有些人建议在 S4 上使用 S3(请参阅 Google 的 R 样式指南 http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html)*.但是,我不知道 S3 方法/对象的确切定义.
Since I am fairly new to R, I do not know what the S3 methods and objects are. I found that there are S3 and S4 object systems, and some recommend to use S3 over S4 if possible (See Google's R Style Guide at http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html)*. However, I do not know the exact definition of S3 methods/objects.
更新:自 2019 年起,Google 的 R 风格指南超链接现位于此处.
Update: As of 2019, Google's R Style Guide hyperlink is now here.
推荐答案
大部分相关信息可以通过查看?S3
或?UseMethod
找到,但在简而言之:
Most of the relevant information can be found by looking at ?S3
or ?UseMethod
, but in a nutshell:
S3 指的是一种方法调度方案.如果您使用过一段时间 R,您会注意到有 print
、predict
和 summary
方法用于许多不同的类型对象.
S3 refers to a scheme of method dispatching. If you've used R for a while, you'll notice that there are print
, predict
and summary
methods for a lot of different kinds of objects.
在 S3 中,这是通过以下方式工作的:
In S3, this works by:
- 设置对象的类利息(例如:a 的返回值对方法
glm
的调用具有类glm
) - 提供一种具有一般性的方法名称(例如
print
),然后是一个点,以及然后是类名(例如:print.glm
) - 必须进行一些准备完成这个通用名称(
print
)为了这个工作,但如果你只是想让自己符合现有的方法名称,你不需要这个(见我提到的帮助如果你这样做,请早点).
- setting the class of objects of
interest (e.g.: the return value of a
call to method
glm
has classglm
) - providing a method with the general
name (e.g.
print
), then a dot, and then the classname (e.g.:print.glm
) - some preparation has to have been
done to this general name (
print
) for this to work, but if you're simply looking to conform yourself to existing method names, you don't need this (see the help I refered to earlier if you do).
对于旁观者,尤其是新创建的时髦模型拟合包的用户来说,能够输入 predict(myfit, type="class")
比 predict.mykindoffit(myfit, type="class")
.
To the eye of the beholder, and particularly, the user of your newly created funky model fitting package, it is much more convenient to be able to type predict(myfit, type="class")
than predict.mykindoffit(myfit, type="class")
.
它还有很多,但这应该会让你开始.这种基于对象的属性(类)调度方法的方式有很多缺点(C 纯粹主义者可能会因为害怕它而彻夜难眠),但在很多情况下,它工作得很好.在当前版本的 R 中,已经实现了更新的方法(S4 和参考类),但大多数人仍然(仅)使用 S3.
There is quite a bit more to it, but this should get you started. There are quite a few disadvantages to this way of dispatching methods based upon an attribute (class) of objects (and C purists probably lie awake at night in horror of it), but for a lot of situations, it works decently. With the current version of R, newer ways have been implemented (S4 and reference classes), but most people still (only) use S3.
这篇关于“S3 方法"是什么?在 R 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!