What does “S3 methods” mean in R?

前端 未结 6 1373
情深已故
情深已故 2020-11-28 17:50

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 possi

6条回答
  •  旧时难觅i
    2020-11-28 18:12

    Try

    methods(residuals)
    

    which lists, among others, "residuals.lm" and "residuals.glm". This means when you have fitted a linear model, m, and type residuals(m), residuals.lm will be called. When you have fitted a generalized linear model, residuals.glm will be called. It's kind of the C++ object model turned upside down. In C++, you define a base class having virtual functions, which are overrided by derived classed. In R you define a virtual (aka generic) function and then you decide which classes will override this function (aka define a method). Note that the classes doing this do not need to be derived from one common super class. I would not agree to generally prefer S3 over S4. S4 has more formalism (= more typing) and this may be too much for some applications. S4 classes, however, can be de defined like a class or struct in C++. You can specify that an object of a certain class is made up of a string and two numbers for example:

    setClass("myClass", representation(label = "character", x = "numeric", y = "numeric"))
    

    Methods that are called with an object of that class can rely on the object having those members. That's very different from S3 classes, which are just a list of a bunch of elements.

    With S3 and S4, you call a member function by fun(object, args) and not by object$fun(args). If you are looking for something like the latter, have a look at the proto package.

提交回复
热议问题