0Pricing
R Academy · Lesson

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), '
')       # 4

All lessons in this course

  1. R's Type System Overview
  2. Converting Between Numeric Types
  3. Logical and Character Conversion
  4. Coercion Pitfalls and Best Practices
← Back to R Academy