Coerce it
It is important to remember that a vector can only be composed of one data type. This means that you cannot have both a numeric and a character in the same vector. If you attempt to do this, the lower ranking type will be coerced into the higher ranking type.
For example: c(1.5, "hello")
results in c("1.5", "hello")
where the numeric 1.5 has been coerced into the character data type.
The hierarchy for coercion is:
logical < integer < numeric < character
Logicals are coerced a bit differently depending on what the highest data type is. c(TRUE, 1.5)
will return c(1, 1.5)
where TRUE is coerced to the numeric 1 (FALSE would be converted to a 0). On the other hand, c(TRUE, "this_char")
is converted to c("TRUE", "this_char")
.
The vectors a, b, and c have been defined for you from the following commands:
a <- c(1L , "I am a character")
b <- c(TRUE, "Hello")
c <- c(FALSE, 2)
Which statement is correct about type conversion?
This exercise is part of the course
Introduction to R for Finance
Hands-on interactive exercise
Turn theory into action with one of our interactive exercises
