6 Methods (part 2)

6.1 Introduction

In this chapter you will learn how to create common S3 class methods such as print(), summary(), and plot().

6.3 Summary Method

For most purposes the standard print method will be sufficient output. However, sometimes a more extensive display is required. This can be done with a summary function. To define this type of method we use the function summary().

The way you declare a summary method is similar to the way you declare a print method. You need to specify summary.toss, indicating that there will be a new summary method for objects of class "toss". The summary will return an object of class "summary.toss", which is typically a list (although you can return any other type of data object).

Here’s the summary.toss() function:

Let’s test it:

When implementing summary methods for specific classes, there’s actually one more method that you typically have to create: a sibling print.summary method. The reason why you need these pair of methods is because an object "summary.toss"—returned by summary()—will very likely need its own print method, thus requiring a print.summary.toss() function.

Let’s test it:

You can actually store the output of summary() and inspect its contents:

6.4 Plot Method

We can also define a plot method for objects of class "toss":

What we want to plot of an object "toss" is the series of realtive frequencies (of either "heads" ot "tails"). This means we need to create a couple of auxiliary functions:

Here’s one way to define a plot() method for "toss" objects:

Let’s test our plot method:


Make a donation

If you find this resource useful, please consider making a one-time donation in any amount. Your support really matters.