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!
This exercise is part of the course
Data Science R Basics
Exercise instructions
- 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 theas.numeric()
function. (Note that you will get a warning message, but that is okay!)
- Convert
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define the vector x
x <- c(1, 3, 5,"a")
# Note that the x is character vector
x
# Redefine `x` to typecast it to get an integer vector using `as.numeric`.
# You will get a warning but that is okay