R Numbers
R has three numeric types: numeric (double-precision decimals, the default), integer and complex. In everyday code you mostly use numeric values and let R take care of the rest.
a <- 12.5 # numeric
b <- 7L # integer
c_val <- 3+4i # complex
class(a); class(b); class(c_val)
Mod(c_val) # length of the complex number[1] "numeric"
[1] "integer"
[1] "complex"
[1] 5
Numeric (double)
Numeric values are 64-bit floating-point numbers, so they hold decimals and very large or small numbers. You can write them in scientific notation with e:
x <- 1.5e3 # 1.5 * 10^3
y <- 2e-4
x
y
.Machine$double.eps # the smallest step after 1
.Machine$integer.max # the largest integer[1] 1500
[1] 2e-04
[1] 2.220446e-16
[1] 2147483647
Integers
Integers take the L suffix. Sequences made with : are integers too. Integer arithmetic stays integer for +, - and *, but / always returns a double:
n <- 10L
class(n + 5L)
class(n / 2L)
class(1:3)
n %/% 3L # integer division
n %% 3L # remainder[1] "integer"
[1] "numeric"
[1] "integer"
[1] 3
[1] 1
Floating-point surprises
Decimals are stored in binary, so some values can't be represented exactly. Compare decimals with a tolerance using all.equal() instead of ==:
0.1 + 0.2 == 0.3
isTRUE(all.equal(0.1 + 0.2, 0.3))
print(0.1 + 0.2, digits = 17)
sqrt(2)^2 == 2[1] FALSE
[1] TRUE
[1] 0.30000000000000004
[1] FALSE
How numbers are printed
By default R shows 7 significant digits. Use print(x, digits = n), round(), signif() or format() to control it:
third <- 1 / 3
third
print(third, digits = 3)
signif(123456, 2)
format(0.000012345, scientific = TRUE)
format(2, nsmall = 2)[1] 0.3333333
[1] 0.333
[1] 120000
[1] "1.2345e-05"
[1] "2.00"
Type conversion and checks
as.integer("42") + 1L
as.numeric("1e3")
is.integer(5)
is.integer(5L)
is.numeric(5L)[1] 43
[1] 1000
[1] FALSE
[1] TRUE
[1] TRUE
Tip: Don't worry too much about integer vs. numeric. Most functions accept both, and R converts as needed. Integers matter mainly for memory in very large datasets and for code that interfaces with other languages.
Test yourself
What is class(5L / 5L)?
- "integer"
- "numeric"
- "complex"
- An error
Why is 0.1 + 0.2 == 0.3 FALSE?
- R has a bug
- Decimal fractions are stored as approximate binary values
- == does not work on numbers
- 0.3 is an integer
What does 2e3 mean?
- 2 × 3
- 2³
- 2000
- 0.002