A factor stores categorical data โ a fixed set of possible categories, such as Low/Medium/High. Factors tell R that a variable is categorical, which matters for both memory efficiency and statistical modelling.
Creating a Factor
R Code
sizes <- factor(c("Medium", "Small", "Large", "Medium")) sizes levels(sizes) nlevels(sizes)
Output
[1] Medium Small Large Medium Levels: Large Medium Small [1] "Large" "Medium" "Small" [1] 3
💡 Tip
By default R sorts factor levels alphabetically, which is why Large comes before Medium and Small above, even though that is not the natural size order. Fix this with ordered factors, shown below.Behind the Scenes: Integer Codes
A factor is actually stored as integers, with a separate table of labels attached. This makes factors far more memory-efficient than storing repeated text.
R Code
as.integer(sizes) # the underlying integer codes as.character(sizes) # convert back to plain text
Output
[1] 2 3 1 2 [1] "Medium" "Small" "Large" "Medium"
Ordered Factors
When categories have a natural order (Low < Medium < High), create an ordered factor so R understands the ranking, not just the labels.
R Code
sizes2 <- factor( c("Medium", "Small", "Large"), levels = c("Small", "Medium", "Large"), ordered = TRUE ) sizes2 sizes2[1] > sizes2[2] # Medium > Small? now this works!
Output
[1] Medium Small Large Levels: Small < Medium < Large [1] TRUE
Counting Categories with table()
R Code
table(sizes)Output
sizes
Large Medium Small
1 2 1 Renaming or Combining Levels
R Code
levels(sizes)[levels(sizes) == "Medium"] <- "Mid" sizes
Output
[1] Mid Small Large Mid Levels: Large Mid Small
Why Factors Matter for Modelling
🚀 Advanced Example
When a factor is used as a predictor in lm() or glm(), R automatically converts it into dummy (indicator) variables, using the first level as the baseline for comparison.R Code
grp <- factor(c("control","control","treated","treated")) response <- c(4.1, 4.3, 6.0, 6.4) model <- lm(response ~ grp) coef(model)
Output
(Intercept) grptreated
4.20 2.10Key Points
- A factor represents a fixed, known set of categories โ internally stored as integers plus labels.
- Use
ordered = TRUEwhen categories have a meaningful rank. table()is the fastest way to count how many observations fall in each category.- Statistical modelling functions automatically treat factors as categorical predictors.