← Back to R Course | Chapter 7: Data Structures | Lesson 4 of 7

Factors

In this page:

  1. Factors

Factors

A factor represents categorical data with a fixed, known set of possible values (called levels), such as "low", "medium", "high". Factors are created with factor() and store the data more efficiently than plain strings while also enabling proper statistical treatment of categories. levels() lists the distinct categories a factor can take.

Note: Use factor(x, levels = c(...), ordered = TRUE) when the categories have a meaningful order, like small < medium < large.

Example: Factors

markup
sizes <- factor(c("small", "large", "medium", "small"),
                levels = c("small", "medium", "large"))

print(sizes)
print(levels(sizes))
print(table(sizes))
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.