3.9 Type Check (S)

Purpose: Checks whether a column of the student’s tibble has the correct data type (e.g., numeric, character).

Motivation: Some questions involve the conversion of a column from one data type to another. This Check detects an incorrectly converted (or unconverted) column and can hint at its correct conversion (e.g., using as.numeric()). This Check is especially useful for questions that rely on a column being numeric to perform computations.

#Type Check Example

#For a numeric column...
else if(!is.numeric(variable_name$column_name)){
  test.results[2, 4] <- "`column_name` is not numeric. (Any additional feedback as needed.)"
}

#For a character column...
else if(!is.character(variable_name$column_name)){
  test.results[2, 4] <- "`column_name` is not character string. (Any additional feedback as needed.)"
}

Technicals

Since the Type Check assumes that the student’s answer has the correct column name, it is essential that the Column Name Check is placed beforehand.

For examples of how to check multiple columns simultaneously, see below.

#Dynamic Type Check Examples 

#Example 1: Checking two columns, column_A (character) and column_B (numeric)
else if(typeof(variable_name$column_A) != typeof(variable_name_test$column_A) | 
        typeof(variable_name$column_B) != typeof(variable_name_test$column_B)){
    
  typeof_check <- c(typeof(variable_name$column_A) != typeof(variable_name_test$column_A),
                    typeof(variable_name$column_B) != typeof(variable_name_test$column_B))
    
  typeof_names <- paste0(paste0(c("`column_A` (correct: character)", 
                                  "`column_B` (correct: numeric)")
                                [typeof_check], collapse = " "), 
                                ". (Any additional feedback as needed.)") 
    
  test.results[2, 4] <- paste0("The following column(s) have the incorrect data type: ", typeof_names, ".")
}

#Example 2 (Experimental): Checking every column in a tibble 
else if(!all(sapply(variable_name, typeof)[order(names(sapply(variable_name_test, typeof)))] ==
             sapply(variable_name_test, typeof)[order(names(sapply(variable_name_test, typeof)))])){
  
  typeof_check <- c(sapply(variable_name, typeof)[order(names(sapply(variable_name_test, typeof))) ==
                    sapply(variable_name_test, typeof)[order(names(sapply(variable_name_test, typeof)))]) 
  
  typeof_names <- c(sapply(variable_name_test, typeof)[order(names(sapply(variable_name_test, typeof)))] |> names())
    
  typeof_names_check <- paste0(typeof_names[!typeof_check], collapse = " ")
    
  typeof_correct_check <- paste0(sapply(typeof_names[!typeof_check], function(names) typeof(variable_name_test[[names]])), collapse = " ")
    
  test.results[2, 4] <- paste0("The following column(s) have the incorrect data type: ", typeof_names_check, ". They should be of type: ", typeof_correct_check, ". (Any additional feedback as needed.)")
}