Converting Between Numeric Types
Use as.integer(), as.double(), and as.numeric() safely.
Integer vs Double in R
R has two numeric types: integer (whole numbers, created with the L suffix) and double (floating-point, the default for numeric literals). Most of the time R uses double, but distinguishing them matters for type safety and memory efficiency.
x_dbl <- 5 # double by default
x_int <- 5L # integer (L suffix)
cat('typeof(5): ', typeof(x_dbl), '
') # double
cat('typeof(5L): ', typeof(x_int), '
') # integer
cat('5 == 5L: ', x_dbl == x_int, '
') # TRUE (values equal)
cat('identical: ', identical(x_dbl, x_int), '
') # FALSE (types differ)as.integer() — Convert to Integer
as.integer(x) converts a value to integer by truncating (not rounding) the decimal part. This means 3.9 becomes 3, not 4. The L suffix is syntactic sugar for integer literals.
cat('as.integer(3.7): ', as.integer(3.7), '
') # 3 (truncated, not 4)
cat('as.integer(3.2): ', as.integer(3.2), '
') # 3
cat('as.integer(-2.9): ', as.integer(-2.9), '
') # -2 (toward zero)
cat('as.integer(10.9): ', as.integer(10.9), '
') # 10
# Compare with round
cat('round(3.7): ', round(3.7), '
') # 4All lessons in this course
- R's Type System Overview
- Converting Between Numeric Types
- Logical and Character Conversion
- Coercion Pitfalls and Best Practices