The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← Regression and Business Forecasting

Unit 4

Categorical variables and interactions

Learning objectives

  • Explain categorical variables and interactions in your own words.
  • Apply the principle to the worked business case.
  • Evaluate the answer and identify an assumption that could change it.

Categorical variables and interactions

Indicator variables represent categories relative to a reference group. An interaction allows one predictor's association to depend on another. Interpret main effects at the reference values, which may need centering to be meaningful.

Worked example

A model includes job size, emergency status, and their interaction. The size slope can differ for emergencies.

Current on-site learning

Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.

Work through the reasoning

Define the population, sampling or assignment process, variables, estimator, and intended inference. For this unit, connect the explanation of categorical variables and interactions to the worked example before answering the practice question.

Check the limits

Check dependence, selection, uncertainty, and whether the evidence supports description, prediction, or causation. If the source model and the practical example use different assumptions, state the difference rather than applying the formula or rule mechanically.

Apply it independently

What does the interaction allow? Write an answer before opening the model response. Show the calculation or explain the causal or logical steps. Change one material assumption and say whether your conclusion changes. This practice is optional; you can read every part of the course without submitting work.

Original Academy expansion: categories, interactions and transformations

An indicator encodes a category as 0 or 1. With an intercept and K mutually exclusive categories, include K - 1 category indicators, leaving one reference category. Including all K indicators alongside the intercept creates exact redundancy because their sum equals the intercept column. The reference category is a parameterization choice; choosing a different reference changes coefficient labels but not fitted values when the same model is represented correctly. Always name the reference group in a report.

An interaction permits one modeled association to depend on another variable. In hours = 2 + 0.5A + 3E + 0.2AE, A is area in hundreds of square feet and E indicates an emergency. For routine jobs, E = 0, giving hours = 2 + 0.5A. For emergencies, E = 1, giving hours = 5 + 0.7A. The emergency difference is 3 + 0.2A, rather than a constant 3. The main emergency coefficient describes the difference at A = 0; that may be an unobserved and unhelpful comparison.

Worked investigation: interpret every coefficient

At A = 10, the routine prediction is 7 hours and the emergency prediction is 12 hours. The gap is 5 hours. A one-unit area increase adds 0.5 fitted hours for routine work and 0.7 for emergency work. Center area at 10: let C = A - 10. Substitution gives hours = 7 + 0.5C + 5E + 0.2CE. The emergency main effect is now the difference at a 1,000-square-foot job. The interaction remains 0.2 because centering changes the location of the reference comparison, not the difference between slopes.

If the interaction estimate has a wide interval, the data may not distinguish the group slopes precisely. Removing the interaction imposes a shared slope, which may improve predictive stability or may conceal a meaningful difference. Compare evidence and performance rather than deleting terms solely to obtain a desired p-value. Retain the associated main terms when interpreting a conventional interaction specification; dropping them imposes special zero-value restrictions that require justification.

Transformations change the question's scale. If log(Y) = b0 + b1 X + error, a one-unit increase in X multiplies the fitted exponentiated linear predictor by exp(b1). The percent difference is 100[exp(b1) - 1]; 100b1 is an approximation for small coefficients. Exponentiating a fitted log mean does not generally recover the arithmetic mean of Y. Under an appropriate normal log-error model with variance sigma squared, the arithmetic mean includes the factor exp(sigma squared/2). Other distributions require other adjustments. The distinction matters when budgeting totals rather than describing typical multiplicative differences.

In a log-log specification, log(Y) = b0 + b1 log(X) + error, b1 is an elasticity of the modeled log relationship. An increase from X to 1.1X changes the exponentiated predictor by a factor 1.1 raised to b1. Do not insert zeros into a log or silently discard them. Zero sales may be an economically meaningful state. Choosing a two-part model, a count model, another transformation, or an explicit restricted population requires subject reasoning.

Curvature can be represented with a squared term. If Y = b0 + b1X + b2X squared, the slope with respect to X is b1 + 2b2X. A negative squared coefficient does not imply negative marginal effects at every observed X. Calculate effects in the region supported by the data. Beyond that region a quadratic can produce implausible reversals or negative predictions. Functional flexibility must be checked against the measurement scale and decision range.

Progressive practice

  1. Foundation: compute routine and emergency predictions at A = 5 and A = 15.
  2. Application: re-express the interaction model after centering A at 5. Identify the new intercept and emergency coefficient.
  3. Transfer: a fitted log-outcome coefficient is 0.2. Calculate its exact multiplicative and percent interpretation and explain why it is not exactly 20%.
  4. Critique: a report says a squared coefficient of -0.01 means every additional advertising dollar reduces sales. State what information is missing.

Worked reasoning for the practice

At A = 5, the predictions are 4.5 and 8.5, a gap of 4. At A = 15, they are 9.5 and 15.5, a gap of 6. With C = A - 5, the intercept becomes 4.5 and the emergency coefficient becomes 4; the two slope terms stay 0.5 and 0.2. Exp(0.2) is approximately 1.2214, corresponding to 22.14%. The 20% interpretation uses a first-order approximation. For the quadratic claim, obtain the linear coefficient, predictor units, observed range, and specification. The local slope is b1 - 0.02X, whose sign cannot be determined from the squared term alone.

Reading alignment for this expansion

The earlier introductory links remain background reading. Use the complete current on-site studios; publisher links are optional provenance. The original Academy worked records above are not quotations from those sources.

Open the runnable laboratory

Extended text lesson

Continue with Make the reference point and the interaction explicit for the full worked case, source readings and optional progressive practice.

Complete current conceptual preparation

Categorical contrasts, curvature and predictions on a transformed scale

A coding scheme defines the comparison

With an intercept and three categories, use two indicators, for example B and C with A as the reference. The model y=a+bx+cB+dC estimates a shared slope and level shifts c,d. At a fixed x, B-minus-C is c-d. Its variance is Var(c)+Var(d)-2 Cov(c,d), not the sum of standard errors. All three indicators plus an intercept are redundant because A+B+C=1. Dropping the intercept gives a different parameterization that can represent the same fitted category means, but it changes coefficient and R-squared conventions. Record the coding and test contrasts on the fitted surface.

With an interaction y=a+bx+cD+d*xD, D=0 has slope b and D=1 slope b+d. The group difference at x 0 is c+d*x 0. Recenter x at k by z=x-k; the equation becomes (a+bk)+bz+(c+dk)D+d*zD. Predictions stay fixed. This is why the preserved branch case moves its group coefficient from 10 at x 0=0 to 4 at x 0=2 without changing a fitted observation. Centering can improve interpretation; it neither removes collinearity arising from missing information nor creates overlap between groups observed at disjoint x ranges.

Worked contrast with uncertainty

Preserve the original eight-observation cumulative fixture: A at x=0,1,2,3 has y=11,11,13,17; B has 14,15,18,23. Its fitted coefficients are 10,2,3,1, SSE 8 and residual df 4. Its separate group fits use Sxx 5 and xbar 1.5. At x=2, each fitted group mean has variance 2*(1/4+.5²/5)=.6; because their observations are independent under the model, the B-minus-A contrast 5 has variance 1.2. The supplied t 4 multiplier 2.776445 yields a margin about 3.04144. A new B individual has fitted value 19 and variance 2.6, adding the residual variance 2 to its fitted mean variance. Do not substitute this individual interval for the group contrast interval.

Now change the operating point to x=1. The contrast is 4 and its variance remains 1.2 because 1 and 2 are equally far from 1.5. At x=0, the contrast is 3 and variance 2*(2*(1/4+2.25/5))=2.8. A group contrast's uncertainty can depend on x even when one coefficient table is printed. For a collection of selected x values, pointwise intervals do not establish simultaneous coverage. The existing curved residual pattern in this synthetic fixture challenges the linear mean; calculations are conditional demonstrations, not an assertion that the model is ready for deployment.

Curvature is compatible with linear regression

In y=a+bx+cx², the slope is b+2 cx, so c alone does not identify whether y rises at a given x. If y=10+4 x-.5 x², the local slope is 4-x and the stationary point is x=4. With negative second derivative -1 it is a model maximum, but only if that point is in the relevant domain and the fitted form is justified there. Predictions at x=2,4,6 are 16,18,16. A symmetric curve can be almost invisible to a single Pearson correlation. Include the hierarchy of lower-order terms unless imposing their exclusion is substantively justified. A flexible interpolation in a tiny sample is not honest validation.

Logs require an explicit retransformation target

If log(Y)=a+bx+epsilon, b is a change in the modeled log mean per unit x. Exponentiating a fitted log value produces a geometric-mean scale quantity, and under median-zero log errors also the conditional median. It is generally not E(Y|x). Under normal log errors with variance sigma², E(Y|x)=exp(a+bx+sigma²/2). This factor follows from the exponential moment of a normal variable and assumes the variance and distribution apply at the prediction point. When errors are heteroskedastic or nonnormal, a single global factor need not be valid.

For an original illustration let log(Y)=log(100)+.2 x+epsilon with sigma=.4. At x=0 the median is 100 and mean is 100*exp(.08), approximately 108.328707. At x=1 the median is 100*exp(.2), approximately 122.140276, and mean 100*exp(.28), approximately 132.312981. With constant sigma the one-unit mean ratio and median ratio are both exp(.2), a 22.140276% increase. This is not exactly 20%, and it is not an intervention effect without identification. If sigma changes from.4 at x 0 to.6 at x 1, the mean ratio becomes exp(.2+(.36-.16)/2)=exp(.3), approximately 1.349858808, even though the fitted log-location coefficient stays.2.

If individual log errors are normal with known sigma=.4 and the log-location coefficients are stipulated known, a central 95% interval at x=0 is 100*exp(plus-or-minus 1.96*.4), approximately[45.6576,219.020]. This is an asymmetric original-scale interval obtained by transforming log endpoints; add parameter uncertainty if coefficients are estimated. Subtracting the transformed mean from symmetric dollar endpoints would describe another procedure. Original-scale totals require original-scale means and cross-unit dependence, not summing fitted medians. Simulation can implement a specified joint model but cannot prove the real process follows it.

For nonnormal errors a training-only smearing factor estimates the average exp(residual). With residuals -log(2),0,log(2), that factor is(.5+1+2)/3=7/6. A fitted exponentiated log location 100 then gives 116.666667 as a smearing-based mean estimate under a suitable stable error-distribution assumption. The mean residual here is zero while mean exp(residual)>1. That is the retransformation issue, not an arithmetic inconsistency. Re-estimate factors within training folds and consider predictor-dependent errors; never use held-out residuals to improve the historical prediction claimed for them.

Log-log y specifications interpret b as elasticity of modeled log location with respect to log x. A 10% x increase multiplies the exponentiated fitted location by 1.1^b, rather than increasing it by exactly 10 b percent. At b=.5 the change is sqrt(1.1)-1, approximately 4.880885%. Zero or negative inputs cannot be logged. Adding an arbitrary constant changes the question and elasticity interpretation. Specify a restricted target or an appropriate two-part/other model instead of silently deleting meaningful zero-sales cases.

Optional practice

Guided model: move the contrast reference

For the preserved 8-case model 10+2 x+3 D+xD, centering at 1 gives 12+2 z+4 D+zD. Group difference at originalx 2 remains 5. Changed fact: use B as reference. Atx 0 the baseline becomes 13 with slope 3, A indicator coefficient-3 and interaction-1. Predictions are unchanged. A sign reversal from recoding is not new evidence.

Independent model: median is not mean

For log location log 100 atx 0 and known normal logSD.4, median 100 differs from mean 100 exp(.08)=108.328707. For 100 independent comparable units, expected total is 10832.8707, not 10000. Changed fact: units share shocks. Linearity still gives the expected total if the marginal means remain valid, but total variance must include covariance. An unchanged expected sum does not justify an independent-error interval.

Transfer model: zeros and an attractive elasticity

A model drops all zero-sales branches then reports elasticity.5 for the whole chain. Its supported target is the retained positive-sales population; the omission may be selective and decision-relevant. Changed fact: the business genuinely targets only established positive-sales branches under a predeclared rule. State that scope, examine support and validate for that group; do not generalize the result to openings or closures without evidence.

Unit rubric: 20 points

Four points each: complete coding/reference; covariance-based contrast and df; curvature/domain interpretation; mean/median/retransformation with exact arithmetic; changed-fact and validation boundaries. Complete model retains all eight original observations, the conditional contrast 5 withvariance 1.2, and log-normal mean 108.328707 at location 100, while declining causal and extrapolation claims. All examples are self-contained and optional practice does not require software.

Optional source summary: the forecasting toolbox distinguishes transformations and bias adjustment from point forecasting and evaluation. Its organization was checked; this studio's branch contrasts, lognormal numerical records and smearing fixture are original Academy teaching. NIST's least-squares explanation confirms that squared or transformed predictors may remain linear in coefficients.

Apply the idea

A model includes job size, emergency status, and their interaction. The size slope can differ for emergencies.

What does the interaction allow? Explain your reasoning, then identify one changed fact that could alter the conclusion.

Expanded transfer investigation: A log-outcome coefficient is 0.2. What is the exact percent change in the exponentiated linear predictor for a one-unit increase?

Show the calculation or argument, identify the information available at the decision time, and state which assumption supports your conclusion. The four progressive tasks in the Learn stage provide additional practice.

Read the worked reasoning

Different size slopes by emergency status. An interaction changes the modeled relationship across conditions. In an independent response, state the given facts, identify the governing relationship, work through the calculation or comparison, and distinguish the conclusion from assumptions that still need evidence.

Expanded transfer reasoning: Calculate 100(exp(0.2)-1). This is not automatically the arithmetic-mean effect without further assumptions.

Progressive practice reasoning: At A = 5, the predictions are 4.5 and 8.5, a gap of 4. At A = 15, they are 9.5 and 15.5, a gap of 6. With C = A - 5, the intercept becomes 4.5 and the emergency coefficient becomes 4; the two slope terms stay 0.5 and 0.2. Exp(0.2) is approximately 1.2214, corresponding to 22.14%. The 20% interpretation uses a first-order approximation. For the quadratic claim, obtain the linear coefficient, predictor units, observed range, and specification. The local slope is b1 - 0.02X, whose sign cannot be determined from the squared term alone.

Check understanding

In hours=2+0.5A+3E+0.2AE, what is the emergency-minus-routine difference at A=10?

  1. 5 hours
    Feedback

    Correct. The difference is 3+0.2(10)=5.

  2. 3 hours
    Feedback

    Incorrect. The main indicator term is the difference at A=0, not A=10.

  3. 0.2 hours
    Feedback

    Incorrect. The interaction coefficient is a difference in slopes, not the entire level difference.

Further reading

Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.

My learning →