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

Factors

A factor stores categories from a fixed set, like T-shirt sizes small, medium, and large. R keeps track of the allowed choices and their order.

In this page:

  1. Factors
Syntax
r
factor_name <- factor(c("level1", "level2"), levels = c("level1", "level2"))
levels(factor_name)

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))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Converting a factor of numbers with as.numeric(f), which returns the level codes, not the original values.
  2. Assigning a value that is not one of the levels, such as sizes[1] <- "huge", which gives NA with a warning.
  3. Forgetting to set levels in order, so "large" sorts before "medium" and "small" alphabetically.
🔒

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.