Chapter 8. S3
You may have noticed that your slot machine results do not look the way I promised they would. I suggested that the slot machine would display its results like this:
play()
## 0 0 DD
## $0
But the current machine displays its results in a less pretty format:
play()
## "0" "0" "DD"
## 0
Moreover, the slot machine uses a hack to display symbols (we call print
from within play
). As a result, the symbols do not follow your prize output if you save it:
one_play<-
play()
## "B" "0" "B"
one_play## 0
You can fix both of these problems with Râs S3 system.
The S3 System
S3 refers to a class system built into R. The system governs how R handles objects of different classes. Certain R functions will look up an objectâs S3 class, and then behave differently in response.
The print
function is like this. When you print a numeric vector, print
will display a number:
num<-
1000000000
print(
num)
## 1000000000
But if you give that number the S3 class POSIXct
followed by POSIXt
, print
will display a time:
class(
num)
<-
c(
"POSIXct"
,
"POSIXt"
)
print(
num)
## "2001-09-08 19:46:40 CST"
If you use objects with classesâand you doâyou will run into Râs S3 system. S3 behavior can seem odd at first, but is easy to predict once you are familiar with it.
Râs S3 system is built around three components: attributes (especially the class
attribute), generic functions, and methods.
Attributes
In Attributes, you learned that many R objects come with attributes, pieces of extra information that are given ...
Get Hands-On Programming with R now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.