Arithmetic operations

2.1.1 Vectorised arithmetic operators

R have the classic operators (+, -, *, /, %/%, %%, ^ == **) but they are vectorised:

c(1, 2, 3) * c(10, 100, 1000)
## [1]   10  200 3000
`*`(c(1, 2, 3), c(10, 100, 1000))
## [1]   10  200 3000

2.1.2 Recycling rule

+ & co are called operators and c(1, 2, 3) is an operands.

When operands have different length they are recycled:

0:7 /3
## [1] 0.0000000 0.3333333 0.6666667 1.0000000 1.3333333 1.6666667 2.0000000
## [8] 2.3333333
1:10 * c(-1, 1)
##  [1] -1  2 -3  4 -5  6 -7  8 -9 10
2 ^ (0:10)
##  [1]    1    2    4    8   16   32   64  128  256  512 1024

But what happens if one operands can’t be recycled in its entirety?

c(1, 10 , 100) * 1:8
## Warning in c(1, 10, 100) * 1:8: longer object length is not a multiple of
## shorter object length
## [1]   1  20 300   4  50 600   7  80

Most of the time it is used for vector scalar operations but it can be used in usefull in other schemes.

pmin and pmax have similar behavior:

pmin(3, 1:5)
## [1] 1 2 3 3 3

2.1.3 Operator precedence

Rules that govern the order of computation:

I prefer them in from highest to lowest precedence:

  • ^

  • - and + (unary)

  • :

  • %% and %/%

  • * and /

  • - and + (binary)

  • <-

Usually left to right except ^ and <-

In doubt you can always use some bracket () (it makes also the code more readable) !

2.1.4 Accumulating

Sometimes you do not want element-wise operations:

You can then use the cumsum()/ cumprod() family of functions.

cumsum(1:8)
## [1]  1  3  6 10 15 21 28 36
cummin(c(3, 2, 4, 5, 1, 6, 0))
## [1] 3 2 2 2 1 1 0

diff is very interesting function that return lagged differences

2.1.5 Aggregating

Sometimes we just want the last “cumulants” that summarise all the imputs.

We can then use sum(), prod(), min().

You also have mean(), var() and sd() that are very hany

Note var() is sum((x- mean(x))^2) / (length(x) - 1)