Type Checking and Conversion
Type checking asks what kind of thing a value is, like asking whether it is a fruit or a vegetable. Conversion changes it into another kind, such as turning the text 5 into the number 5.
In this page:
Syntax
class(x)
typeof(x)
as.numeric(x)
as.character(x)
is.numeric(x)
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
as.numeric("abc")and expecting an error, when it givesNAwith a warning. - Reading numbers from a column stored as a factor with
as.numeric(), which gives the factor codes; useas.numeric(as.character(x)). - Relying on
class()alone, whentypeof()shows the underlying storage such asdouble.
Chapter Summary
- Assignment operators store values in variables, and R has numeric, integer, character, logical, and complex types.
- You can check the type of a value and convert it to another type.
- Understanding types helps you predict how operations behave.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: