7 Additional Methods
Until now we have standard methods like
plot(). However, we can add more common (and not so common) methods such as:
7.2 Replacement Method
Replacement functions are those calls like
x <- 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 is the name of the class:
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
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. The function behind this expression is the extraction
"["() function. We can also create a extraction function for a given class.
Another common type of function for an object of a given class is
is.class()-like functions: e.g.
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:
"+" 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
# two more flips seven + 2 #> object "toss" #> sides: "heads", "tails" #> prob: "0.5", "0.5" #> total tosses: 9 #> num of heads: 4 #> num of tails: 5 # three more flips seven + 3 #> object "toss" #> sides: "heads", "tails" #> prob: "0.5", "0.5" #> total tosses: 10 #> num of heads: 6 #> num of tails: 4
Make a donation
If you find this resource useful, please consider making a one-time donation in any amount. Your support really matters.