This post was originally posted on Quantide blog. Read the full article here.

Introduction

R is an object-oriented (OO) language. This basically means that R is able to recognize the type of objects generate from analysis and to apply the right operation on different objects.

For example, the summary(x) method performs different operations depending on the so-called “class” of x:

the outputs reported, and the calculations performed, by the summary() method are really different for the x and the mdobjects.

This behavior is one of characteristics of OO languages, and it is called methods overloading.

The methods overloading can be applied not only for methods in “function form” (i.e., for methods like summary()), but also for operators; indeed, “behind the scenes”, the operators are functions/methods. For example, if we try to write + in the R console we obtain:

That means that the + operator actually is a function/method that requires two arguments: e1 and e2, which are respectively the left and right argument of operator itself.

The + operator is present in R base, and can be overloaded as well, like in ggplot2 package, where the + operator is used to “build” the graph characteristics, as in following example:

Methods_Overloading_fig1-1

 

The + operator, then, is applied differently with ggplot2 objects (with respect other object types), where it “concatenates” or “assembles” parts of final graph.

In this small post, and following ones, I would like to produce some “jokes” with objects, operators, overloading, and similar “oddities”..

C-language += operator and its emulation in R

In C language there are several useful operators that allow the programmer to save some typing and to produce some more efficient and easiest to read code. The first operator that I would like to discuss is the += one.

+= is an operator that does operations like: a = a + k.
In C, the above sentence can be summarized with a += k. Of course, the sentence can be something of more complex, like

a += (x-log(2))^2

In this case, the code line shall be “translated” to a = a + (x-log(2))^2.

If I would like to have in R a new operator that acts similarly to C’s +=, I whould have to create it.

Unfortunately, not all the names are allowed in R for new operators: if I want to produce a new operator name I can only use operators with names like %mynewoperator% where the % symbols are mandatory.

Indeed, for this example, I will create a new %+=% operator that acts similarly to the C’s +=.

This new operator has to be able to get the values of variables passed as arguments, to sum them, and then, more importantly, to update the value of the first variable with the new value.

Continue reading on Quantide blog...

Print Friendly, PDF & Email

Related Post

Share: