Numbers — Double, Integer and Complex
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
Lfor an integer,ifor 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) # FALSEDouble (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.
The shortcut
Look at how the value was made. A plain literal (8, 12.5) is double. An L suffix, a whole-number colon sequence or a count is integer. An i suffix is complex. When you do arithmetic, mixing integer and double gives double, and / always gives double.
Build the sequence
1:3is the integer vector 1 2 3.
Integer division %/% is the exception that keeps integers: 7L %/% 2L is the integer 3.
Drills
Answer fast — trust the rule.
What is typeof(12.5)?
What does is.integer(5) return?
What is typeof(5L / 5L)?
What does 0.1 + 0.2 == 0.3 return?
What is sqrt(as.complex(-4))?
Remember
- Plain numbers are doubles; add
Lfor an integer,ifor complex. - Shortcut: look at how the value was made, and remember
/always gives a double. - Trap:
class()says "numeric" buttypeof()says "double", and never test decimals with==.
