← Back to R Course | Chapter 2: Variables & Types | Lesson 7 of 7

Type Checking and Conversion

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

markup
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")
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.