Ordinal variables in R
The factor()
function also allows you to assign an order to the nominal variables, thus making them ordinal variables. This is done by setting the order
parameter to TRUE
and by assigning a vector with the desired level hierarchy to the argument levels
. Since we do not want to force you to rank order your family members, we'll illustrate this with a different example.
Consider the categorical variable temperature_vector
with the categories "Low"
, "Medium"
and "High"
. Here it's obvious that "Medium"
stands above "Low"
, and that "High"
stands above "Medium"
. Let's use R to create this rank ordering among weather observations.
This exercise is part of the course
Intro to Statistics with R: Introduction
Exercise instructions
Click "Submit Answer" to run the code and see how R constructs and prints ordinal variables.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a vector of temperature observations
temperature_vector <- c("High", "Low", "High", "Low", "Medium")
# Specify that they are ordinal variables with the given levels
factor_temperature_vector <- factor(temperature_vector, order = TRUE,
levels = c("Low", "Medium", "High"))
# Print the result to the console
factor_temperature_vector