Session Ready
Exercise

Coercion: Taming your data

It is possible to transform your data from one type to the other. Next to the class() function, you can use the as.*() functions to enforce data to change types. For example,

var <- "3"
var_num <- as.numeric(var)

converts the character string "3" in var to a numeric 3 and assigns it to var_num. However, keep in my that it is not always possible to convert the types without losing information or getting errors.

as.integer("4.5")
as.numeric("three")

The first line will convert the character string "4.5" to the integer 4. The second one will convert the character string "three" to an NA.

Instructions
100 XP
  • var1 is logical. Convert it to character and assign it to the variable var1_char.
  • Next, see whether var1_char actually is a character by using the is.character() function on it.
  • var2 is numeric. Convert it logical and assign it to the variable var2_log.
  • Inspect the class of var2_log using class().
  • Finally, var3 is of type character. Convert it to numeric and assign the result to var3_num. Was it successful?