Type Conversion — as.*() and Coercion
Coercion converts values to a common type when an operation requires it. The as.* functions request conversions explicitly; behavior for invalid values depends on the target type.
Inspect coercion when values of different types are combined.
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 fix