Comparing ordered factors

Having a bad day at work, 'data analyst number two' enters your office and starts complaining that 'data analyst number five' is slowing down the entire project. Since you know that 'data analyst number two' has the reputation of being a smarty-pants, you first decide to check if his statement is true.

The fact that factor_speed_vector is now ordered enables us to compare different elements (the data analysts in this case). You can simply do this by using the well-known operators.

# Create factor_speed_vector speed_vector <- c("medium", "slow", "slow", "medium", "fast") factor_speed_vector <- factor(speed_vector, ordered = TRUE, levels = c("slow", "medium", "fast")) # Factor value for second data analyst da2 <- # Factor value for fifth data analyst da5 <- # Is data analyst 2 faster than data analyst 5? # Create factor_speed_vector speed_vector <- c("medium", "slow", "slow", "medium", "fast") factor_speed_vector <- factor(speed_vector, ordered = TRUE, levels = c("slow", "medium", "fast")) # Factor value for second data analyst da2 <- factor_speed_vector[2] # Factor value for fifth data analyst da5 <- factor_speed_vector[5] # Is data analyst 2 faster data analyst 5? da2 > da5 msg = "Do not change anything about the commands that define `speed_vector` and `factor_speed_vector`!" test_object("speed_vector", undefined_msg = msg, incorrect_msg = msg) test_object("factor_speed_vector", eq_condition = "equal", undefined_msg = msg, incorrect_msg = msg) msg <- "Have you correctly selected the factor value for the %s data analyst? You can use `factor_speed_vector[%s]`." test_object("da2", eq_condition = "equal", incorrect_msg = sprintf(msg, "second", "2")) test_object("da5", eq_condition = "equal", incorrect_msg = sprintf(msg, "fifth", "5")) test_output_contains("da2 > da5", incorrect_msg = "Have you correctly compared `da2` and `da5`? You can use the `>`. Simply print out the result.") success_msg("Bellissimo! What do the result tell you? Data analyst two is complaining about the data analyst five while in fact they are the one slowing everything down! This concludes the chapter on factors. With a solid basis in vectors, matrices and factors, you're ready to dive into the wonderful world of data frames, a very important data structure in R!")
  • To select the factor value for the third data analyst, you'd need factor_speed_vector[3].
  • To compare two values, you can use >. For example: da3 > da4.

Previous: 4-8 | Ordered factors (2)

Next: 5-1 | What's a data frame?

Back to Main