Type Coercion
in R
Learn how R automatically converts data types, the hidden rules that govern these transformations, and the common surprises that catch programmers off guard.
What is Type Coercion?
In R, every value has a type (also called a "mode" or "class"): logical, integer, double, character, and more. When you combine values of different types, R must decide on a single type for the result.
Type coercion is the process where R automatically converts one type into another so that operations can proceed. This happens silently: no warning, no error, just a quiet transformation behind the scenes.
R's Four Atomic Types
Implicit vs Explicit Coercion
The Coercion Hierarchy
How Logicals Become Numbers
One of the most useful coercion rules: TRUE becomes 1 and FALSE becomes 0. This lets you use logical vectors in arithmetic, which is a core R idiom.
Vectors vs Functions: Where Coercion Happens
| In Vectors (c()) | In Functions | |
|---|---|---|
| Trigger | Mixing types in c() | Passing wrong type to argument |
| Rule | Hierarchy: most general wins | Function-specific behavior |
| Warning? | Never: always silent | Sometimes: NAs introduced |
| Example | c(1, "a") → all character | as.numeric("x") → NA + warning |
How to Predict Coercion Results
Example 1: Mixing in c()
What happens when we combine a logical, an integer, and a character in a single vector?
Example 2: Arithmetic with Logicals
Arithmetic operators force logical values to become numbers. This enables a powerful counting pattern.
Example 3: Dangerous Coercion Surprises
Not all coercions are friendly. When R cannot convert a value meaningfully, it produces NA and sometimes a warning.
How NA Interacts with Coercion
NA (Not Available) is R's missing value. It is special: NA can exist in any type, and it coerces along with everything else.
Explicit Coercion Functions
Common Mistakes with Coercion
Coercion Quick Reference
| From → To | numeric | character | logical |
|---|---|---|---|
| TRUE | 1 | "TRUE" | TRUE |
| FALSE | 0 | "FALSE" | FALSE |
| 42L | 42 | "42" | TRUE |
| 3.14 | 3.14 | "3.14" | TRUE |
| 0 | 0 | "0" | FALSE |
| "hello" | NA | "hello" | NA |
| "1" | 1 | "1" | NA |
Question 1 of 5
What is the result of c(TRUE, 3L, 2.5) in R?
Question 2 of 5
What does sum(c(TRUE, FALSE, TRUE, TRUE)) return?
Question 3 of 5
What is the output of as.logical(0)?
Question 4 of 5
In R's coercion hierarchy, which type is the most general (i.e., all other types coerce toward it)?
Question 5 of 5
What does as.numeric("hello") return?