0Pricing
R Academy · Lesson

Coercion Pitfalls and Best Practices

Identify and avoid data loss from unexpected implicit coercion.

What is Implicit Coercion?

Implicit coercion happens automatically when R combines different types. R silently converts all elements to the most complex type present in a vector, following the hierarchy: logical < integer < double < complex < character.

# Combining different types triggers implicit coercion
v1 <- c(TRUE, 1L, 2.5)   # logical < integer < double => double
v2 <- c(1, 2, 'three')    # double < character => character
v3 <- c(FALSE, 0L, 0.0)   # all become double

cat('c(TRUE,1L,2.5)   :', v1, '| typeof:', typeof(v1), '
')
cat('c(1,2,"three")   :', v2, '| typeof:', typeof(v2), '
')
cat('c(FALSE,0L,0.0)  :', v3, '| typeof:', typeof(v3), '
')

Logical to Integer Coercion

When a logical vector is placed in an integer context, TRUE becomes 1L and FALSE becomes 0L. This is intentional in R and is used in expressions like sum(condition_vector).

flags <- c(TRUE, FALSE, TRUE, TRUE, FALSE)
result <- c(flags, 10L)
cat('c(logicals, 10L):', result, '
')       # 1 0 1 1 0 10
cat('typeof:          ', typeof(result), '
') # integer

# Adding an integer to a logical vector
cat('flags + 1L:', flags + 1L, '
')  # 2 1 2 2 1

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