- Simulation for Data Science with R
- Matthias Templ
- 293字
- 2021-07-14 11:17:07
Generic functions, methods, and classes
R has different class systems, the most important ones are S3
and S4
classes. Programming with S3
classes is easy living, it's easier than S4
. However, S4
is clean and the use of S4
can make packages very user-friendly.
In any case, in R each object is assigned to a class (the attribute class
). Classes allow object-oriented programming and overloading of generic functions. Generic functions produce different output for objects of different classes as soon as methods are written for such classes.
This sounds complex, but with the following example it should get clearer.
As an example of a generic function, we will use the function summary
. summary
is a generic function used to produce result summaries. The function invokes particular methods that depend on the class of the first argument:
## how often summary is overloaded with methods ## on summary for certain classes (the number depends on loaded packages) length(methods(summary)) ## [1] 137 class(Cars93$Cylinders) ## [1] "factor" summary(Cars93$Cylinders) ## 3 4 5 6 8 rotary ## 3 49 2 31 7 1 ## just to see the difference, convert to class character: summary(as.character(Cars93$Cylinders)) ## Length Class Mode ## 93 character character
From this previous example one can see that the summary is different, depending on the class of the object. R internally looks as if a method is implemented for the given class of the object. If yes, this function is used, if not, the function summary.default
is used. This procedure is called method dispatch.
In the last line of the previous example, R looked as if a function summary.factor
was available, which was true.
Note
You can easily write your own generic functions, and define print, summary, and plot functions for objects of certain classes.
- 從零開始構建企業級RAG系統
- Learning Bayesian Models with R
- Java 9 Programming Blueprints
- 新編Premiere Pro CC從入門到精通
- HTML5+CSS3+JavaScript Web開發案例教程(在線實訓版)
- Building Minecraft Server Modifications
- JavaScript 程序設計案例教程
- C語言程序設計教程
- C語言程序設計上機指導與習題解答(第2版)
- MongoDB,Express,Angular,and Node.js Fundamentals
- Mastering C++ Multithreading
- Python趣味編程與精彩實例
- Python網絡爬蟲實例教程(視頻講解版)
- MongoDB Administrator’s Guide
- Apache Solr for Indexing Data