Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

Numbers — Double, Integer and Complex

Numeric 12 minR has double, integer and complex numeric types. Numeric literals normally create doubles, an L suffix requests an integer, and an imaginary component uses i.

r programming / Numbers — Double, Integer and Complex

Explore each scene at your own pace.

01 · The rule

The rule

Numbers — Double, Integer and Complex

R has double, integer and complex numeric types. Numeric literals normally create doubles, an L suffix requests an integer, and an imaginary component uses i.

Inspect numeric representations and the consequences for exactness and arithmetic.

The harvest weights are decimals like 12.5, the plot count is a whole number like 5, and one day an engineering volunteer asks about square roots of negative numbers. R stores these differently, and knowing which type you have explains results that otherwise look like bugs.

The rule

Plain numbers are doubles; add L for an integer, i for complex.

typeof() tells you how R stores a value:

typeof(12.5)     # "double"
typeof(8)        # "double"   (no decimal point, still a double)
typeof(8L)       # "integer"
typeof(1:5)      # "integer"  (a colon sequence of whole numbers)
typeof(3 + 2i)   # "complex"

class(8)         # "numeric"
is.numeric(8L)   # TRUE
is.integer(8)    # FALSE

Double (short for double-precision floating point) is R's default number. It holds decimals with about 15 significant digits, plus the special values Inf (1/0), -Inf and NaN, "not a number" (0/0). Because doubles are stored in binary, some decimals are not exact: 0.1 + 0.2 == 0.3 is FALSE. Compare decimals with isTRUE(all.equal(0.1 + 0.2, 0.3)), which allows a tiny tolerance.

Integer holds whole numbers only, from about -2.1 billion to +2.1 billion. You get one from the L suffix, from 1:5, and from functions such as length() and seq_along(). Going past the limit does not wrap around: .Machine$integer.max + 1L gives NA with a warning.

"Numeric" is an umbrella word. class() calls a double "numeric", and is.numeric() is TRUE for both doubles and integers. So when you need the exact storage type, ask typeof().

Complex numbers have a real and an imaginary part, written with i: 3 + 4i. Re() and Im() pull the two parts apart, and Mod() gives the size: Mod(3 + 4i) is 5. R will not invent them for you: sqrt(-4) gives NaN with a warning, while sqrt(as.complex(-4)) gives 0+2i.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.