What does “S3 methods” mean in R?

前端 未结 6 1366
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-11-28 18:11

    To get you started with S3, look at the code for the median function. Typing median at the command prompt reveals that it has one line in its body, namely

    UseMethod("median")
    

    That means that it is an S3 method. In other words, you can have a different median function for different S3 classes. To list all the possible median methods, type

    methods(median) #actually not that interesting.  
    

    In this case, there's only one method, the default, which is called for anything. You can see the code for that by typing

    median.default
    

    A much more interesting example is the print function, which has many different methods.

    methods(print)  #very exciting
    

    Notice that some of the methods have *s next to their name. That means that they are hidden inside some package's namespace. Use find to find out which package they are in. For example

    find("acf")  #it's in the stats package
    stats:::print.acf
    

提交回复
热议问题