Type Checking and Conversion
In this page:
Type Checking and Conversion
class() and typeof() report a value's type, while functions like as.numeric(), as.character(), and as.logical() convert between types. Conversion that doesn't make sense, like as.numeric("abc"), produces NA with a warning rather than an error. Checking types explicitly avoids subtle bugs when mixing data from different sources.
Warning: Converting a non-numeric string with as.numeric(), like as.numeric("abc"), returns NA with a warning instead of stopping the script.
Example: Type Checking and Conversion
x <- "42"
converted <- as.numeric(x)
cat(class(x), "->", class(converted), "\n")
cat(converted + 8, "\n")
bad <- as.numeric("abc")
cat(is.na(bad), "\n")
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: