官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 石狮市| 庆云县| 三河市| 景东| 如皋市| 陕西省| 尖扎县| 逊克县| 洪泽县| 贵溪市| 平度市| 泰顺县| 双鸭山市| 无锡市| 广德县| 阿拉善右旗| 襄城县| 湘潭市| 英山县| 南平市| 义乌市| 丹东市| 潼关县| 子洲县| 耒阳市| 泊头市| 陇西县| 剑川县| 泗洪县| 白城市| 合水县| 资溪县| 杭锦旗| 比如县| 湖南省| 封丘县| 古浪县| 隆回县| 巴林右旗| 乐陵市| 新平|