1. Learn
  2. /
  3. Courses
  4. /
  5. Data Science R Basics

Exercise

Coercion

The concept of coercion is a very important one. Watching the video, we learned that when an entry does not match what an R function is expecting, R tries to guess what we meant before throwing an error. This might get confusing at times.

As we've discussed in earlier questions, there are numeric and character vectors. The character vectors are placed in quotes and the numerics are not.

We can avoid issues with coercion in R by changing characters to numerics and vice-versa. This is known as typecasting. The code, as.numeric(x) helps us convert character strings to numbers. There is an equivalent function that converts its argument to a string, as.character(x).

Let's practice doing this!

Instructions

100 XP
  • Define the following vector:
x <- c(1, 3, 5,"a")
  • Notice that x has been coerced into a character string.
  • If we assign something new to a vector that we've already created, the new definition replaces whatever was previously assigned to the vector.
    • Convert x to a vector of numbers using the as.numeric() function. (Note that you will get a warning message, but that is okay!)