logo

Finding Quotients and Remainders in R 📂R

Finding Quotients and Remainders in R

Overview

In the syntax of programming languages, what really lacks unity are the quotient and remainder operators. At first glance, they all seem to look alike, which contributes to the confusion. C uses / for quotient and % for remainder, while Python uses // for quotient and % for remainder, and there are plenty more examples of this confusion.

One might wonder where the need to calculate quotients and remainders arises in R, which is focused on statistics and matrix calculations. Surprisingly, modulo operations appear fairly frequently in coding related to seasonality or when handling categorical data. The quotient is obtained with %/%, and the remainder with %%. Let’s take a look at the example below.

Example

20171111_152354.png

Dividing $13$ by $5$, the quotient is $2$ and the remainder is $3$, which is accurately calculated. In R, besides the five basic operations +, -, *, /, ^, and logical operators, everything else involves placing something between % to create new operators. Thinking of %% as putting nothing between % is a rule that applies without exception, so it should be easy to remember.

Fortunately, logical operators share the common forms used in other languages, such as ==, >, <, !=, &, |.

It’s worth mentioning, though often unknown due to R users mainly focusing on statistical analysis, that R implements complex numbers. 20171111_164130.png Examining the structure with the str function, it can be identified as cplx (complex number). These complex numbers can also be calculated without any issues using the basic operators.