TExcelTAD
Home › R › R Math

R Math

R was designed for numerical work, so it comes with a complete set of arithmetic operators and mathematical functions. Most of them are vectorised: they work on every element of a vector at once.

Arithmetic operators

Operator Meaning Example Result
+ - * / the usual four 7 / 2 3.5
^ or ** power 2 ^ 5 32
%% remainder (modulo) 17 %% 5 2
%/% integer division 17 %/% 5 3
r · try it yourself
17 %% 5
17 %/% 5
-7 %% 3     # the result has the sign of the divisor
2 ^ 0.5
(1 + 2) * 3 ^ 2
[1] 2
[1] 3
[1] 2
[1] 1.414214
[1] 27

Precedence follows mathematics: ^ first, then * and /, then + and -. Parentheses override everything.

Common functions

r · try it yourself
sqrt(81)
abs(-12.5)
exp(1)
log(100)         # natural log
log10(100)
log(8, base = 2)
factorial(5)
choose(5, 2)     # ways to choose 2 out of 5
[1] 9
[1] 12.5
[1] 2.718282
[1] 4.60517
[1] 2
[1] 3
[1] 120
[1] 10

Rounding

There are several ways to drop decimals, and they differ for negative numbers:

r · try it yourself
x <- c(-2.7, -2.5, 2.5, 2.7, 3.14159)
round(x)
round(3.14159, 3)
ceiling(x)   # up
floor(x)     # down
trunc(x)     # toward zero
[1] -3 -2  2  3  3
[1] 3.142
[1] -2 -2  3  3  4
[1] -3 -3  2  2  3
[1] -2 -2  2  2  3

round(-2.5) and round(2.5) give -2 and 2: R rounds halves to the nearest even number (the IEC 60559 standard), which avoids a systematic upward bias in large sums.

Working on whole vectors

The functions above all apply to each element. Summary functions reduce a vector to a single value:

r · try it yourself
v <- c(4, 9, 16, 25)
sqrt(v)
sum(v)
prod(1:5)
max(v); min(v)
range(v)
cumsum(v)
[1] 2 3 4 5
[1] 54
[1] 120
[1] 25
[1] 4
[1]  4 25
[1]  4 13 29 54

Trigonometry and constants

Angles are in radians. pi is a built-in constant:

r · try it yourself
pi
sin(pi / 2)
cos(0)
deg <- 60
round(sin(deg * pi / 180), 4)
[1] 3.141593
[1] 1
[1] 1
[1] 0.866

Test yourself

What is 23 %% 4?

  1. 5
  2. 3
  3. 5.75
  4. 0

What does floor(-1.2) return?

  1. -1
  2. -2
  3. 1
  4. -1.2

What does sqrt(c(1, 4, 9)) return?

  1. 14
  2. An error
  3. 1 2 3
  4. 3.741657