Arithmetic operations
2.1.1 Vectorised arithmetic operators
R have the classic operators (+
, -
, *
, /
, %/%
, %%
, ^
== **
) but they are vectorised:
## [1] 10 200 3000
## [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:
## [1] 0.0000000 0.3333333 0.6666667 1.0000000 1.3333333 1.6666667 2.0000000
## [8] 2.3333333
## [1] -1 2 -3 4 -5 6 -7 8 -9 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?
## 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:
## [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) !