Encoding Categorical Variables
Maya runs a small used-car listing site. She wants to predict a car's resale price from its details, and her data describes each car with words: transmission is manual or automatic, the body is sedan, hatchback, or SUV, the condition runs poor to excellent, and the brand is one of dozens of makes. A model, though, only does arithmetic. It cannot multiply the word "automatic" by anything.
Encoding is how we hand a model those words as numbers, and doing it carelessly teaches the model things that are not true. By the end of this lesson you will be able to:
- Explain why numbering categories
1, 2, 3can mislead a model - One-hot, dummy, and ordinal encode variables in R, and read the result
- Pick an encoding for a column with hundreds of categories, and say what it costs
Prerequisites: you can run R and read its output, and you know what a model, a feature, and a train/test split are (from Train, Validation, Test, and Data Leakage).
There is no single right encoding, only the right one for the kind of category. Here is the whole map; we spend the lesson earning it.
A model only multiplies numbers
Picture the simplest price model Maya could fit, a straight-line one. It predicts a car's price by multiplying each feature by a learned weight and adding them up:
\[ \hat{y} \;=\; \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_p x_p. \]
Here \(\hat{y}\) is the predicted price, each \(x_j\) is one feature (a number), each \(\beta_j\) is the weight the model learns for it, and \(\beta_0\) is the intercept, a baseline constant that belongs to no feature. The whole machine is multiplication and addition. So every \(x_j\) has to be a number. The word "automatic" has no value to multiply, and the same is true of every tree, boosting, or neural model underneath: somewhere they all reduce a row to numbers.
Each lesson runs in a fresh R session, so let us build Maya's listings right here and look at what we are dealing with.
Four of the five columns are text. Encoding is the job of turning those four into numbers, and the next steps are about doing it without lying to the model.
Numbering categories invents an order
The fastest fix looks obvious: just hand each category a number. Let hatchback = 1, sedan = 2, SUV = 3, and feed that one column to the model. This is called label or integer encoding, and for a column with no inherent order it is a trap.
Look at what the model now believes. It will treat that column as an ordinary number, so it reads SUV (3) as three times hatchback (1), and sedan (2) as sitting exactly halfway between them. You invented an order (hatchback before sedan before SUV) and an even spacing (each step worth the same) that the body styles never had. A body style is a name, not a rank.
What goes wrong here?
Maya encodes brand as Toyota = 1, Ford = 2, Honda = 3, Kia = 4, BMW = 5 and puts that single column into a linear price model. Brand has no natural order. What has she accidentally told the model?
One-hot and dummy encoding
If a category has no order, give the model no order. One-hot encoding replaces one categorical column with several 0/1 columns, one per category, each answering a yes/no question: "is this car a sedan?", "is it an SUV?". Formally, for a feature with levels \(c_1, c_2, \dots, c_k\), one-hot creates \(k\) indicator columns
\[ x_j \;=\; \mathbf{1}[\,\text{level} = c_j\,], \qquad j = 1, \dots, k, \]
where \(\mathbf{1}[\cdot]\) is 1 when the row is level \(c_j\) and 0 otherwise, and \(k\) is the number of categories. No category is larger than another; each just gets its own switch.
There is one subtlety. The \(k\) indicator columns always sum to 1 for every row (a car is exactly one body style, so \(\sum_{j} x_j = 1\)). That makes the last column perfectly predictable from the others, which is redundant and, for a linear model with an intercept, breaks the fit (the columns are perfectly collinear). The cure is dummy encoding: keep only \(k-1\) columns and let the dropped category be the baseline (or reference). Every other column's weight is then read as a difference from that baseline. Leaving all \(k\) columns in is the classic mistake known as the dummy-variable trap.
Build the columns yourself
Good news: in R you rarely one-hot by hand, because lm(), glm(), and friends turn a factor into dummy columns automatically (they keep \(k-1\) and use the first level as the baseline). But it pays to see the columns explicitly with model.matrix().
The formula ~ body gives you the dummy columns (R drops the baseline and adds an intercept). Adding - 1 removes the intercept, which forces R to keep all the columns, the full one-hot set. Fill in the blank so this produces one column per body style.
Show answer
cars$body <- factor(cars$body, levels = c("hatchback", "sedan", "SUV"))
onehot <- model.matrix(~ body - 1, data = cars)
head(onehot)
#> bodyhatchback bodysedan bodySUV
#> 1 1 0 0
#> 2 0 1 0
#> 3 0 0 1
#> 4 0 1 0
#> 5 0 0 1
#> 6 1 0 0Ordinal encoding: keep the ranking
Sometimes a category does have an order, and throwing it away would lose real information. Maya's condition runs poor, fair, good, excellent. An excellent car really is worth more than a poor one, in that order. One-hot encoding would scatter that ranking across four unrelated 0/1 columns and make the model relearn the obvious.
For a genuinely ordered category, ordinal encoding is the honest move: map the levels to ranked integers in their true order. In R you state the order once with an ordered factor, then convert to integers.
poor, fair, good, excellent as 1, 2, 3, 4 tells the model the jump from poor to fair is worth exactly as much as the jump from good to excellent. If that is roughly true, ordinal encoding is compact and powerful. If the gaps are uneven, keep the order but let the model find the spacing (one-hot the levels, or use an ordered factor with a method that does not assume even steps).Which column may be integer-coded?
Maya has two columns left to encode: brand (Toyota, Ford, Honda, ...) and a survey field satisfaction (low, medium, high). Which one is a fair candidate for ordinal (integer) encoding, and why?
satisfaction is ordinal: the levels rank naturally, so 1, 2, 3 keeps real information (as long as the steps are roughly even). brand is nominal and must not be integer-coded.brand is exactly the label-encoding trap. Only satisfaction has a real order to preserve.High cardinality: too many levels
One-hot encoding is honest, but it has a cost: it adds one column per category. For transmission (2 levels) or body (3) that is nothing. For a real brand or model column with 200 distinct makes, one-hot creates 200 sparse columns, most of them almost always 0. That bloats the model, invites overfitting, and creates a nasty production bug: a brand that appears only in the test set (or in next month's data) has no column to land in, so the encoding breaks on data it has never seen.
When a column is high-cardinality, you shrink it before encoding. Two simple, leak-safe options:
Each choice buys something and costs something:
| Strategy | What it does | The cost |
|---|---|---|
| One-hot every level | one 0/1 column per category | hundreds of sparse columns; breaks on unseen levels |
| Lump rare levels | keep the top few, fold the rest into "Other" | loses detail inside "Other" |
| Frequency encoding | replace level by how common it is | two equally common brands collide on the same number |
| Target encoding (next lesson) | replace level by its average outcome | strongest, but leaks the answer if done carelessly |
The most powerful high-cardinality method, target encoding, replaces each category with the average price of cars in that category. It is also the easiest to get wrong, because it peeks at the answer. That leak, and how to encode out-of-fold so it cannot happen, is the whole of Lesson 2.
Match the column to its encoding
Maya is finalizing her pipeline. For three columns, which encoding fits each best: transmission (manual / automatic), condition (poor to excellent), and model (180 distinct values)?
transmission and model invents an order they do not have. Only condition is genuinely ordered.References
Authoritative places to take this further:
- Kuhn and Johnson, Feature Engineering and Selection (free book) - the definitive practitioner treatment of encoding categorical predictors and what each method costs.
- Kuhn and Silge, Tidy Modeling with R, recipes chapter - how to encode inside a modeling pipeline so the recipe learns on train and applies to test.
- recipes: step_dummy() reference - the tidymodels step that one-hot and dummy encodes a factor.
- forcats: fct_lump() reference - collapsing rare levels of a high-cardinality factor into "Other".
Lesson 1 complete
You can now read a column's kind and encode it honestly: one-hot or dummy encode nominal categories so the model invents no order, ordinal-encode genuinely ranked categories while remembering the equal-spacing assumption you buy, and shrink a high-cardinality column by lumping rare levels or frequency-encoding instead of exploding it into hundreds of sparse columns. Maya's word-columns are now numbers a model can actually use.
Next, Lesson 2: Target Encoding Without Leakage. You will meet the most powerful way to encode a high-cardinality column, replacing each category with its average outcome, and the subtle leak that makes it dangerous. You will learn to do it out-of-fold, so the encoding never sees the rows it scores.