4 Methods (part 1)

4.1 Introduction

We describe our methods in this chapter.

4.2 Improving toss()

From chapter 2, we ended up with the following toss() function:

The issue with the way toss() has been defined so far, is that you can pass it any type of vector (not necessarily of class "coin"), and it will still work:

To create a function toss() that only works for objects of class "coin", we could add a stop() condition that checks if the argument x is of the right class:

A more formal strategy, and one that follows OOP principles, is to create a toss method. In R, many functions are actually methods: e.g. print(), summary(), plot(), str(), etc.

These types of functions are not really one unique function, they typically comprise a collection or family of functions for printing objects, computing summaries, plotting, etc. Depending on the class of the object, a generic method will look for a specific function for that class:

4.3 Generic Method toss

When implementing new methods, you begin by creating a generic method with the function UseMethod():

The function UseMethod() allows you to declare the name of a method. In this example we are telling R that the function toss() is now a generic "toss" method. Note the use of "..." in the function definition, this will allow you to include more arguments when you define specific methods based on "toss".

A generic method alone is not very useful. You need to create specific cases for the generic. In our example, we only have one class "coin", so that is the only class we will allow toss to be applied on. The way to do this is by defining toss.coin():

The name of the method, "toss", comes first, followed by a dot ".", followed by the name of the class, "coin". Notice that the body of the function toss.coin() does not include the stop() command anymore.

To use the toss() method on a "coin" object, you don’t really have to call toss.coin(); calling toss() is enough:

How does toss() work? Becasue toss() is now a generic method, everytime you use it, R will look at the class of the input, and see if there is an associated "toss" method. In the previous example, coin1 is an object of class "coin", for which there is a specific toss.coin() method. Thus using toss() on a "coin" object works fine.

Now let’s try toss() on the character vector c('tic', 'tac', 'toe'):

When you try to use toss() on an object that is not of class "coin", you get a nice error message.

Because an object "coin" already contains an element prob, the toss.coin() function does not really an argument prob. Instead, we can pass this value from the coin object. Here’s a new definition of toss.coin():

Let’s toss a loaded coin:

Make a donation

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