Type Conversion
Prerequisites: Missing values: NA and NULL
The as.*() functions convert values from one type to another.
as.numeric("3.5")
as.integer("42")
as.integer(3.99)
as.character(42)
as.logical("TRUE")
as.logical(0)
as.numeric(TRUE)
[1] 3.5
[1] 42
[1] 3
[1] "42"
[1] TRUE
[1] FALSE
[1] 1
as.integer(3.99)truncates (drops the decimals) rather than rounding. Useround()first if you want the nearest whole number.- Numbers convert to logicals as
0→FALSE, anything else →TRUE.
When conversion fails
Text that isn't a valid number becomes NA, with a warning:
as.numeric(c("10", "20", "n/a", "40"))
[1] 10 20 NA 40
Warning message:
NAs introduced by coercion
This is extremely common when importing data: a numeric column
containing a stray "n/a" or "-" is read as text. After converting,
check how many NAs appeared — they point to the problem cells.
Checking before converting
is.*() functions check a type: is.numeric(), is.character(),
is.logical(), is.na().
Common mistakes
- Converting a factor (Level 1's Factors lesson) straight to numbers:
as.numeric(factor(c("10", "20")))gives1 2(the category codes), not10 20. Convert to character first:as.numeric(as.character(f)).