Numbers and Arithmetic
Prerequisites: Data types
R works like a powerful calculator.
Example
7 + 2
7 - 2
7 * 2
7 / 2
7 %/% 2
7 %% 2
2 ^ 10
10 / 3
Expected output
[1] 9
[1] 5
[1] 14
[1] 3.5
[1] 3
[1] 1
[1] 1024
[1] 3.333333
/always gives the exact result, including decimals.%/%is integer division (drops the remainder);%%gives the remainder — handy for checking whether a number is even.^raises to a power.- R prints numbers to 7 significant digits by default, so
10 / 3shows3.333333— but the full precision is kept internally.
Useful math functions
round(3.14159, 2)
signif(123456, 2)
ceiling(3.2)
floor(3.8)
abs(-5)
sqrt(16)
exp(1)
log(100, base = 10)
[1] 3.14
[1] 120000
[1] 4
[1] 3
[1] 5
[1] 4
[1] 2.718282
[1] 2
Special values
1 / 0
-1 / 0
0 / 0
sqrt(2)^2 == 2
isTRUE(all.equal(sqrt(2)^2, 2))
[1] Inf
[1] -Inf
[1] NaN
[1] FALSE
[1] TRUE
Infis infinity;NaNmeans "not a number".- Decimal numbers are approximate on every computer, so
sqrt(2)^2isn't exactly 2. Compare decimals withall.equal(), which allows for tiny rounding differences.
Common mistakes
- Comparing decimals with
==. Useall.equal()(wrapped inisTRUE()insideif). - Forgetting that printed values are rounded for display.
Practice
A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and the exact share rounded to two decimals.
Show solution
slices <- 8
people <- 3
slices %/% people
slices %% people
round(slices / people, 2)
[1] 2
[1] 2
[1] 2.67