You might wonder what happens when you try to compare elements of a factor. In factor_survey_vector
you have a factor with two levels: "Male"
and "Female"
. But how does R value these relative to each other?
Read the code in the editor and click 'Submit Answer' to test if male
is greater than (>
) female
.
# Build factor_survey_vector with clean levels
survey_vector <- c("M", "F", "F", "M", "M")
factor_survey_vector <- factor(survey_vector)
levels(factor_survey_vector) <- c("Female", "Male")
# Male
male <- factor_survey_vector[1]
# Female
female <- factor_survey_vector[2]
# Battle of the sexes: Male 'larger' than female?
male > female
# Build factor_survey_vector with clean levels
survey_vector <- c("M", "F", "F", "M", "M")
factor_survey_vector <- factor(survey_vector)
levels(factor_survey_vector) <- c("Female", "Male")
# Male
male <- factor_survey_vector[1]
# Female
female <- factor_survey_vector[2]
# Battle of the sexes: Male 'larger' than female?
male > female
msg = "Do not change anything about the code; simply hit Submit Answer and look at the result."
test_object("survey_vector", undefined_msg = msg, incorrect_msg = msg)
test_object("factor_survey_vector", eq_condition = "equal", undefined_msg = msg, incorrect_msg = msg)
test_object("male", undefined_msg = msg, incorrect_msg = msg)
test_object("female", undefined_msg = msg, incorrect_msg = msg)
test_output_contains("male > female", incorrect_msg = msg)
success_msg("How interesting! By default, R returns `NA` when you try to compare values in a factor, since the idea doesn't make sense. Next you'll learn about ordered factors, where more meaningful comparisons are possible.")
Just click 'Submit Answer' and have a look at output that gets printed to the console.