7 Additional Methods

7.1 Introduction

Until now we have standard methods like print(), summary(), and plot(). However, we can add more common (and not so common) methods such as:

  • replacement: "[<-.toss"
  • extraction: "[.toss"
  • testing: is.toss()
  • addition: "+.toss"

7.2 Replacement Method

Replacement functions are those calls like x[1] <- 3. The function behind this expression is the replacement "[<-"() function. We can also create a replacement function for a given class using the notation "[<-.class", where class is the name of the class:

Test it:

What about replacing out of the original range?

Or something like this?

Because, in general, it does not make sense to replace if index is out of the original length, we can add a stop() condition:

Now we cannot replace if index is out of the original length:

7.3 Extraction Method

What if you want to know what is the value of toss in position 3? You could type something like this:

Or you could create an extraction method that allows you to type x[3]. The function behind this expression is the extraction "["() function. We can also create a extraction function for a given class.

Test it:

7.4 Is "toss"

Another common type of function for an object of a given class is is.class()-like functions: e.g. is.list(), is.numeric(), is.matrix(). This type of functions allow you to test or check whether an object is of a given class.

We can create our own is.toss() to check whether a given R object is of class "coss". Here’s how to define such a function:

7.5 Addition Method

R comes with generic Math methods (see ?Math). Among these generic methods we can find the "+" operator. This means that we can define our own plus method for objects of class "toss". The idea is to be able to call a command like this:

Here’s one implementation of "+.toss()" in which the first argument is an object of class "toss", and the second argument is a single positive number that will play the role of additional tosses:

Remember that "+" is a binary operator, which means that writing a "+" method requires a function with two arguments. Let’s try it:

Let’s add a couple of more tosses to seven:


Make a donation

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