Get Started

Ordered factors (2)

speed_vector should be converted to an ordinal factor since its categories have a natural ordering. By default, the function factor() transforms speed_vector into an unordered factor. To create an ordered factor, you have to add two additional arguments: ordered and levels.

factor(some_vector,
       ordered = TRUE,
       levels = c("lev1", "lev2" ...))

By setting the argument ordered to TRUE in the function factor(), you indicate that the factor is ordered. With the argument levels you give the values of the factor in the correct order.

This is a part of the course

“Introduction to R”

View Course

Exercise instructions

From speed_vector, create an ordered factor vector: factor_speed_vector. Set ordered to TRUE, and set levels to c("slow", "medium", "fast").

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Create speed_vector
speed_vector <- c("medium", "slow", "slow", "medium", "fast")

# Convert speed_vector to ordered factor vector
factor_speed_vector <-

# Print factor_speed_vector
factor_speed_vector
summary(factor_speed_vector)

This exercise is part of the course

Introduction to R

BeginnerSkill Level
4.7+
595 reviews

Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.

Data often falls into a limited number of categories. For example, human hair color can be categorized as black, brown, blond, red, grey, or white—and perhaps a few more options for people who color their hair. In R, categorical data is stored in factors. Factors are very important in data analysis, so start learning how to create, subset, and compare them now.

Exercise 1: What's a factor and why would you use it?Exercise 2: What's a factor and why would you use it? (2)Exercise 3: What's a factor and why would you use it? (3)Exercise 4: Factor levelsExercise 5: Summarizing a factorExercise 6: Battle of the sexesExercise 7: Ordered factorsExercise 8: Ordered factors (2)
Exercise 9: Comparing ordered factors

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free