Do you remember that when you added 5 + "six"
, you got an error due to a mismatch in data types? You can avoid such embarrassing situations by checking the data type of a variable beforehand. You can do this with the class()
function, as the code on the right shows.
Complete the code in the editor and also print out the classes of my_character
and my_logical
.
# Declare variables of different types
my_numeric <- 42
my_character <- "universe"
my_logical <- FALSE
# Check class of my_numeric
class(my_numeric)
# Check class of my_character
# Check class of my_logical
# Declare variables of different types:
my_numeric <- 42
my_character <- "universe"
my_logical <- FALSE
# Check class of my_numeric
class(my_numeric)
# Check class of my_character
class(my_character)
# Check class of my_logical
class(my_logical)
msg <- "Do not change the declaration of the variables!"
lapply(c("my_numeric", "my_character", "my_logical"), test_object, undefined_msg = msg, incorrect_msg = msg)
patt <- "Have you included `class(%1$s)` to print out the data type of `%1$s`?"
test_output_contains("class(my_numeric)",
incorrect_msg = "Do not remove the code that prints out the type of `my_numeric`.")
test_output_contains("class(my_character)",
incorrect_msg = sprintf(patt, "my_character"))
test_output_contains("class(my_logical)",
incorrect_msg = sprintf(patt, "my_logical"))
success_msg("Congratulations! This was the last exercise for this chapter. Head over to the next chapter to get immersed in the world of vectors!")
The code that prints the data type of my_numeric
is already included; do similar things for my_character
and my_logical
.