Tutorials › Exam PA - Predictive Analytics › Ordered Factors and Ordered Contrasts

Exam PA · Categorical Encoding and Interactions · Tutorial 240 of 966

Ordered Factors and Ordered Contrasts

Learn to set factor order deliberately, inspect polynomial contrast columns in R, and interpret trend coefficients on the model’s linear-predictor scale.

Intermediate 11 min read

What You'll Learn

  • Distinguish ordered factors, nominal factors, and numeric predictors
  • Set and verify level order in R before fitting a model
  • Interpret the linear, quadratic, and higher-order columns from contr.poly
  • Explain trend coefficients on the model’s linear-predictor scale
  • Recognize how unequal spacing and unbalanced data affect interpretation
  • Avoid treating an ordered-contrast coefficient as an adjacent-level change

Why Order Is Not the Same as a Numeric Predictor

Categories such as policy tiers, clinical severity bands, or service ratings can have a meaningful order. That order contains information, but it does not automatically tell us that the gaps between categories are equal. A model must distinguish “low, medium, high” from unrelated labels such as region names, and it must also distinguish an ordered category from a numeric variable whose one-unit changes have a defined meaning.

In R, an ordered factor records a sequence of levels. Polynomial contrasts provide a set of columns that can describe linear and higher-order patterns across that sequence. These columns are a choice of model-matrix basis: their coefficients describe components of the fitted pattern, not necessarily changes from one category to the next.

Definition: A nominal factor has categories with no inherent ordering. An ordered factor has categories with a substantive order, but the order alone does not assert equal spacing. An ordered polynomial contrast is a contrast column that represents a polynomial component across the ordered levels, such as a linear, quadratic, or cubic pattern.

For a factor with \(k\) levels, a full set of polynomial contrasts has \(k-1\) columns, in addition to the model intercept. R labels these columns with suffixes such as `.L`, `.Q`, and `.C`: linear, quadratic, and cubic. For a factor with more than four levels, further polynomial columns are available. The column values depend on the level order and the scores supplied to R.

A nominal factor should not be assigned an order merely because its labels can be sorted alphabetically. Conversely, an ordered factor should not be treated as numeric unless a numerical scale and the meaning of its unit steps are justified. The earlier material on factor contrasts establishes how a model matrix represents categories; here the key question is what the ordered contrast columns mean.

Creating and Inspecting Ordered Contrasts in R

Set the level sequence explicitly. For example, the R expression `ordered(x, levels = c("Basic", "Enhanced", "Premier"))` creates an ordered factor with Basic below Enhanced and Enhanced below Premier. Explicit levels protect against accidental alphabetical ordering and make the intended order visible in the analysis.

R commonly uses polynomial contrasts by default for ordered factors, but contrast settings can be changed. To make the choice reproducible, assign them explicitly: `contrasts(tier) <- contr.poly(3)`. The function `contr.poly(3)` creates contrasts for three ordered levels scored equally as 1, 2, and 3. The model matrix can be inspected using `model.matrix(~ tier, data = dat)`; its columns reveal exactly which values enter the model.

Worked Example: Reading a Three-Level Model Matrix

A hypothetical service team records a response score for four cases in each of three ordered service tiers. The mean scores are 4 for Basic, 5 for Enhanced, and 10 for Premier. The response is modeled with a Gaussian distribution and identity link, so the fitted mean equals the linear predictor. Use equally spaced ordered scores and interpret the coefficients from the full factor model.

Method. Create an ordered factor in the stated order, assign `contr.poly(3)`, and fit the full model `lm(score ~ tier, data = dat)`. The three-level contrast matrix has linear and quadratic columns:

$$ \begin{array}{c|rr} & .L & .Q\\ \text{Basic} & -1/\sqrt{2} & 1/\sqrt{6}\\ \text{Enhanced} & 0 & -2/\sqrt{6}\\ \text{Premier} & 1/\sqrt{2} & 1/\sqrt{6} \end{array} $$

The fitted intercept is the average of the three tier means because each tier has the same number of cases: \( (4+5+10)/3 = 19/3 = 6.3333\). The linear coefficient is the sum of each tier mean multiplied by its `.L` value: \(4(-1/\sqrt{2})+5(0)+10(1/\sqrt{2})=6/\sqrt{2}=4.2426\).

The quadratic coefficient is \(4(1/\sqrt{6})+5(-2/\sqrt{6})+10(1/\sqrt{6})=(4-10+10)/\sqrt{6}=4/\sqrt{6}=1.6330\). Thus the model’s fitted means are 6.3333 plus the corresponding linear and quadratic contributions. For Basic, \(6.3333-3+0.6667=4\); for Enhanced, \(6.3333+0-1.3333=5\); and for Premier, \(6.3333+3+0.6667=10\). The fitted means reproduce all three observed means, as a full two-column contrast representation should.

Check and common mistake. The calculation reproduces the three tier means. The `.L` coefficient 4.2426 is not the increase from Basic to Enhanced or from Enhanced to Premier; those actual differences are 1 and 5. It is the coefficient multiplying a normalized linear-contrast column.

What the Trend Coefficients Mean

With a Gaussian identity-link model, a factor’s fitted mean at level \(j\) is formed by adding the intercept and the relevant contrast contributions. The `.L` coefficient describes the linear component in the chosen contrast basis. A `.Q` coefficient describes a quadratic component: a departure from a straight-line pattern across the scores. Higher-order columns represent further departures. A coefficient’s sign indicates the direction of that component relative to the signs in R’s contrast column.

For a generalized linear model, the same contrast columns enter the linear predictor. If the response has mean \(\mu_j\) at a level and link function \(g\), then \(g(\mu_j)\) is represented by the intercept plus the contrast contributions. The coefficient is therefore on the link scale. For example, in a binomial model with a logit link, it describes a component of the log odds, not a direct change in probability. Translating a coefficient into a probability difference requires evaluating the inverse link at specified predictor values.

Important interpretation: A full set of \(k-1\) ordered polynomial contrast columns represents arbitrary fitted values at \(k\) levels; it does not force the pattern to be linear. A model retaining only the `.L` column does impose a linear pattern in the model’s linear predictor across the chosen scores. Adding `.Q` or further columns allows progressively more complex patterns.

The columns from `contr.poly(k)` are normalized and mutually orthogonal across the \(k\) levels when levels are equally weighted. For three levels, for example, the `.L` values sum to zero, the `.Q` values sum to zero, and the sum of their pairwise products is zero. Normalization matters: it sets the numerical scale of coefficients. Using a different contrast basis to represent the same fitted values changes coefficient values, even though fitted means may remain unchanged.

Why the Balanced-Data Formula Works

The projection interpretation can be derived directly for a balanced Gaussian identity-link model. Let \(c_{jr}\) be the value of contrast column \(r\) at level \(j\), and let \(\bar y_j\) be the response mean at that level. Suppose there are \(m\) observations at every level, the contrast columns are centered and orthonormal across levels, and the model includes the intercept and all \(k-1\) contrast columns. Thus, \(\sum_j c_{jr}=0\) and \(\sum_j c_{jr}c_{js}=1\) when \(r=s\), or 0 otherwise.

The model predicts \(\bar y_j = \alpha+\sum_r\beta_r c_{jr}\). Minimizing the sum of squared residuals gives the normal equation for coefficient \(r\): the sum of the residuals multiplied by \(c_{jr}\), across all observations, equals zero. Since there are \(m\) observations at each level, this equation is

$$ m\sum_{j=1}^{k} c_{jr} \left(\bar y_j-\alpha-\sum_{s=1}^{k-1}\beta_s c_{js}\right)=0. $$

The intercept term vanishes because the contrast is centered. Orthogonality makes every cross-term vanish except the one involving \(\beta_r\). Dividing by \(m\) leaves

$$ \beta_r=\sum_{j=1}^{k} c_{jr}\bar y_j. $$

This is why, in the balanced example, each coefficient was calculated by multiplying level means by contrast values and summing. The result does not apply in this simple form to unequal replication, non-identity links, or a model containing other predictors: the estimation then uses the model’s actual design and, for a generalized linear model, its likelihood and link.

Unequal Spacing and the Choice of Scores

Default polynomial contrasts treat successive levels as equally spaced. That may be appropriate for ordered bands deliberately defined as consecutive steps, but not for every ordered variable. Suppose ordered categories correspond to actual scores 1, 2, and 5. The order is clear, but the gap from 2 to 5 is larger than the gap from 1 to 2. R can construct polynomial contrasts using those scores: `contr.poly(3, scores = c(1, 2, 5))`. This changes the contrast columns and therefore the coefficient scale and interpretation.

Using scores is a modeling decision, not a way to make the data automatically more informative. If a variable genuinely has measured numerical values, fitting it as numeric may be more direct. If categories only have an order and no defensible distances, a numeric spacing assumption should not be smuggled in. A full ordered-factor model with all \(k-1\) columns can represent any set of level means; a reduced trend model makes stronger assumptions about the shape of the pattern.

Worked Example: Irregular Scores Versus a Numeric Predictor

A hypothetical risk review uses three ordered bands with scores 1, 2, and 5. In a balanced Gaussian identity-link analysis, the average response is 3, 5, and 11 in those bands, respectively. Calculate the polynomial contrast coefficients using the stated scores, then compare the linear coefficient with the slope from treating the score as numeric.

Method. Use `contr.poly(3, scores = c(1, 2, 5))`. The centered scores are \(-5/3,-2/3,7/3\), and their squared lengths sum to \(26/3\). Hence the normalized linear column is \((-5,-2,7)/\sqrt{78}\). The quadratic column is \((3,-4,1)/\sqrt{26}\); it sums to zero and is orthogonal to the linear column.

The linear coefficient is \( [(-5)(3)+(-2)(5)+(7)(11)]/\sqrt{78}=52/\sqrt{78}=5.8878\). The quadratic coefficient is \( [3(3)+(-4)(5)+(1)(11)]/\sqrt{26}=(9-20+11)/\sqrt{26}=0\). The intercept is the equally weighted average, \( (3+5+11)/3=19/3=6.3333\).

The numeric relationship is exactly response \(=1+2(\text{score})\), because the three points satisfy \(3=1+2(1)\), \(5=1+2(2)\), and \(11=1+2(5)\). Its numeric slope is therefore 2 response units per score unit. The ordered `.L` coefficient, 5.8878, is not that slope: it is the slope component multiplied by the normalized length of the centered scores, \(\sqrt{26/3}\). Multiplying \(2\sqrt{26/3}\) gives \(5.8878\), confirming the relationship.

Check and common mistake. The zero quadratic coefficient is consistent with the exact straight-line pattern on scores 1, 2, and 5. Do not report 5.8878 as a response increase per score unit; that interpretation belongs to the numeric slope, which is 2.

Unbalanced Data, Model Scope, and Practical Checks

Orthogonality describes the contrast columns across levels, not necessarily the columns as they appear in the observed sample. When level counts differ, the sample model-matrix columns need not be orthogonal under the observation-level inner product. In a Gaussian model with unequal counts, coefficient estimates are not generally obtained by applying the simple balanced-data formula to unweighted level means. A generalized linear model also estimates coefficients on its link scale, using the response distribution and the model’s fitting procedure.

Before interpreting a trend, check four things: the factor’s level order; the scores used to build the contrasts; which contrast columns are included in the fitted model; and the response scale on which the coefficients operate. In R, inspecting `levels(tier)`, `contrasts(tier)`, and `model.matrix(...)` helps confirm the first three. Then identify the model family and link to establish the fourth.

Ordered contrasts are useful when the ordering is meaningful and the question concerns a trend across levels. They can summarize a pattern compactly, or impose a trend structure when only selected columns are included. They are not a substitute for checking the data, and they do not establish that a trend is practically important or statistically reliable. In particular, a positive linear component does not guarantee that every adjacent-level difference is positive when higher-order components are also present.

Key takeaway: An ordered factor records an order; polynomial contrasts encode components of a pattern across that order. Interpret coefficients using the actual contrast values, included columns, factor scores, and model link—not as automatic adjacent-category changes.

Check Your Understanding

For each problem, identify the contrast or scale interpretation before calculating.

  1. A balanced Gaussian identity-link model has three ordered levels with means 2, 6, and 10. Using default `contr.poly(3)`, find the `.L` coefficient. (Answer: \(8/\sqrt{2}=5.6569\))
  2. A nominal predictor has levels North, Central, and South. A colleague orders them alphabetically and assigns polynomial contrasts. What is the modeling concern? (Answer: No substantive ordering has been established; polynomial trends depend on an arbitrary order.)
  3. Three equally represented ordered levels have means 3, 7, and 11. Using default three-level polynomial contrasts, calculate the quadratic coefficient. (Answer: \( (3-14+11)/\sqrt{6}=0\))
  4. For ordered scores 1, 2, and 5, response means are 4, 6, and 12. Under the balanced Gaussian identity-link model, what is the numeric slope and what is the `.L` coefficient using `scores = c(1, 2, 5)`? (Answer: Numeric slope \(=2\); `.L` coefficient \(=2\sqrt{26/3}=5.8878\).)
  5. A binomial model uses a logit link and includes only the `.L` column for a four-level ordered factor. What scale is the trend linear on, and what does that restriction assert? (Answer: The log-odds scale; the fitted log odds follow a linear pattern across the equally spaced ordered scores.)
Clinical Biostats