Type Conversion — as.*() and Coercion
The garden's new web form sends every weight as text, and one volunteer typed "six" instead of 6. Somewhere between the form and your average, types have to change. R changes them for you in some places, silently, and you change them on purpose in others. Knowing both keeps numbers from vanishing without notice.
The rule
Mix types and R climbs: logical, integer, double, character.
A vector holds one type. When you combine values of different types, R converts them all to the type that can represent everything, which is the highest rung on this ladder:
logical → integer → double → (complex) → character
c(TRUE, 2L) # 1 2 integer
c(TRUE, 2L, 3.5) # 1.0 2.0 3.5 double
c(1, "2", TRUE) # "1" "2" "TRUE" character
TRUE + TRUE # 2, logicals climb to numbers in arithmeticThis is implicit coercion: R does it without asking, because a vector cannot hold two types at once. Character sits at the top because any value can be written as text, but text cannot always become a number.
Explicit conversion uses the as. family:
as.numeric("12.5") # 12.5
as.integer(12.9) # 12, the decimals are cut off, not rounded
as.character(45) # "45"
as.logical("TRUE") # TRUE ("T", "true" and "True" also work)
as.logical("yes") # NA
as.logical(0) # FALSE; any non-zero number gives TRUE
as.numeric("3.5 kg") # NA, with a warningWhen a value cannot be converted, you get NA plus a warning: NAs introduced by coercion. R never guesses that "six" means 6. That warning is important: it means data has just been lost.
The matching is. functions test types (is.numeric(), is.character(), is.logical()), and typeof() names the type outright.
Here is the form data in practice:
raw <- c("12.5", "8", "15", "3.5 kg", "six")
kg <- as.numeric(raw) # 12.5 8.0 15.0 NA NA, with a warning
raw[is.na(kg)] # "3.5 kg" "six", the entries to fixThe shortcut
For implicit coercion, find the highest type in the mix: everything becomes that type. For explicit conversion, ask: "Is this value already a clean example of the target type?" If yes, it converts. If not, expect NA and a warning.
List the types
logical, integer, double, character.
The trap is a single stray value. One text entry in a column of numbers turns the whole column into character, and then mean() gives NA with a warning instead of an average.
Drills
Answer fast — trust the rule.
What does c(1, "2", TRUE) produce?
What does as.numeric("3.5 kg") return?
What is as.integer(12.9)?
What is TRUE + TRUE + FALSE?
What does as.logical("yes") return?
Remember
- Mix types and R climbs: logical, integer, double, character.
- Shortcut: implicit goes to the highest type; explicit converts clean values and gives NA otherwise.
- Trap: ignoring "NAs introduced by coercion", which is data quietly disappearing.
