TExcelTAD
Home › R › R Numbers

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.

r · try it yourself
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:

r · try it yourself
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:

r · try it yourself
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 ==:

r · try it yourself
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:

r · try it yourself
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

r · try it yourself
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)?

  1. "integer"
  2. "numeric"
  3. "complex"
  4. An error

Why is 0.1 + 0.2 == 0.3 FALSE?

  1. R has a bug
  2. Decimal fractions are stored as approximate binary values
  3. == does not work on numbers
  4. 0.3 is an integer

What does 2e3 mean?

  1. 2 × 3
  2. 2³
  3. 2000
  4. 0.002