Skip to content
AgileLogics
5 min read

Factors

Prerequisites: Vectors

A factor stores categorical data — values from a fixed set of categories, such as sizes, days of the week, or survey answers. Factors matter in R because statistical models and charts treat them as groups.

Creating factors

sizes <- factor(c("medium", "small", "large", "small"))
sizes
levels(sizes)
table(sizes)
[1] medium small  large  small
Levels: large medium small
[1] "large"  "medium" "small"
sizes
 large medium  small
     1      1      2
  • The levels are the possible categories. By default they're in alphabetical order.
  • table() counts how often each level occurs.

Controlling the order

Alphabetical order is often wrong for categories that have a natural order. Set the levels explicitly:

sizes <- factor(c("medium", "small", "large", "small"),
                levels = c("small", "medium", "large"))
levels(sizes)
table(sizes)
[1] "small"  "medium" "large"
sizes
 small medium  large
     2      1      1

The level order controls the order of bars in charts and of groups in tables. With ordered = TRUE, comparisons like sizes > "small" also work.

Factors vs character vectors

Use a factor when the set of possible values is fixed and meaningful as groups (especially for modeling and plotting). For free text — names, comments — keep a character vector. The forcats package (part of the tidyverse) provides helpful functions for reordering and relabeling factor levels.

Common mistakes

  • Converting a factor of numbers with as.numeric(), which returns the level codes. Use as.numeric(as.character(f)).
  • Typos creating extra levels, such as "Small" and "small" as two categories. Clean text before creating factors.