R Numbers
R treats all plain numbers as double-precision decimals by default, and provides a family of functions to inspect, round, and do arithmetic with them.
Numeric Type by Default
In R, any number you type — whole or fractional — is stored as a double (double-precision floating point) unless you explicitly ask for something else. Even x <- 10 is stored as a double, not an integer, until you tell R otherwise.
Example
x <- 10
y <- 3.14
class(x)
# "numeric"
class(y)
# "numeric"Arithmetic Operators
R supports the standard arithmetic operators (+, -, *, /, ^), plus two that often surprise newcomers: %% for the remainder after division (modulo) and %/% for integer division, which drops any fractional part of the result.
Example
7 %% 2
# 1
7 %/% 2
# 3
2^10
# 1024Rounding Functions
- round(x, digits) rounds to the nearest value, using the given number of decimal places
- ceiling(x) always rounds up to the next whole number
- floor(x) always rounds down to the previous whole number
- trunc(x) simply removes the decimal part, without rounding
Example
round(4.567, 2)
# 4.57
ceiling(4.1)
# 5
floor(4.9)
# 4
trunc(4.9)
# 4Special Numeric Values
Note: Use is.finite(x) to filter out Inf, -Inf, NaN, and NA all at once, or is.na(x) specifically when you only care about missing values.
Exercise: R Numbers
How do you explicitly create an integer literal in R instead of a double?