Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Regression

Factor Variables, Interactions and margins

Use Stata's i. and c. prefixes and ## operator to add dummies, interactions and polynomials to regressions, then interpret them with margins and contrast.

Real datasets contain categories: region, industry, treatment group. Putting a category code such as region = 1, 2, 3, 4 straight into a regression treats it as a number, which is almost never what you mean. Stata solves this with factor-variable notation. A prefix on the variable name tells Stata to create indicator (dummy) variables on the fly, build interactions, or square a variable, without you having to generate anything.

Stata cannot run on this site, so the Stata commands below are read-only. The runnable blocks are Python stand-ins that build the same design matrix so you can see what i. and ## create behind the scenes.

The i. prefix: indicators

STATA
sysuse auto, clear
regress price mpg i.foreign
regress price mpg i.rep78

i.foreign creates an indicator for each level of foreign and omits the lowest level as the base. The coefficient on 1.foreign is the difference in expected price between foreign and domestic cars at the same mileage. Change the base with ib3.rep78 (level 3), ib(first).rep78, ib(last).rep78 or ib(freq).rep78 (most common level).

Stata labels the rows by value label when the variable has one, which makes tables readable. Run label list to see the codes. A variable must be an integer to be used with i.; use egen id = group(name) first if it is a string.

The c. prefix and the ## operator

c. marks a variable as continuous, which matters when you build interactions. The operator # creates an interaction only, while ## creates the main effects plus the interaction:

STATA
regress price c.mpg##i.foreign

This is the same as regress price mpg i.foreign i.foreign#c.mpg. It lets the slope of mpg differ between domestic and foreign cars. Polynomials work the same way, and Stata remembers the relationship between the terms:

STATA
regress price c.mpg##c.mpg

That fits price = b0 + b1*mpg + b2*mpg^2. The advantage over typing gen mpg2 = mpg^2 is that postestimation commands know mpg2 moves when mpg moves.

If you write regress price mpg i.foreign#c.mpg with only one # you get the interaction without the main effect of foreign. That model forces both groups to share one intercept, which is rarely justified. Prefer ## unless you have a reason.

What the design matrix looks like

The stand-in below builds the columns that c.mpg##i.foreign creates, fits them, and shows how the slope in each group is the sum of two coefficients.

Python Interaction design matrix (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first row of output is the model Stata would show; the lines after it are the two group slopes that margins computes for you (next section).

margins: turning coefficients into answers

With interactions, single coefficients are hard to read. margins computes predicted values and marginal effects directly:

STATA
regress price c.mpg##i.foreign
margins foreign, at(mpg=(15 20 25))
marginsplot
margins, dydx(mpg) over(foreign)

The first call gives average predicted prices at three mileages for each origin; marginsplot graphs them with confidence intervals. The third returns the slope of mpg in each group, matching the sum of coefficients you calculated by hand. margins by default averages over the observed values of the other covariates (average marginal effects). Use atmeans to hold them at their means instead, and always say which one you reported.

Another helpful command is contrast, which tests a whole factor at once:

STATA
regress price i.rep78
contrast rep78
pwcompare rep78, mcompare(bonferroni)

contrast gives the joint F test that all levels have the same mean; pwcompare lists every pairwise difference, with an optional multiple-comparison correction.

Predicted values at chosen points

This second stand-in computes predictions from the model above at chosen mileages, which is what margins foreign, at(mpg=(15 20 25)) produces (without the confidence limits).

Python Predictions at chosen values (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The gap between groups grows with mileage because the interaction coefficient is positive. A plain coefficient on foreign would only describe the gap at mpg = 0, which is not even a real car. This is why centering a continuous variable (gen mpg_c = mpg - r(mean) after summarize mpg) or using margins makes interaction results interpretable.

Tips

  • Use fvset base 3 rep78 to set a base level permanently for the session.
  • Add allbaselevels to show the omitted level in the table.
  • Factor notation works in regress, logit, xtreg, margins, predict and most estimators, but not in summarize or correlate.
  • Collinearity is handled for you: Stata omits redundant dummies and tells you.

You will use these tools again in the diagnostics and logit lessons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does c.mpg##i.foreign include?

    The double hash adds the main effects of both variables plus their interaction; a single hash adds only the interaction.
  2. 2. How do you make level 3 the base category of rep78?

    The ib prefix followed by a level chooses the base; ib(freq) picks the most frequent level.
  3. 3. Why use margins after a model with an interaction?

    With interactions the effect of one variable depends on another, so margins reports effects at specific values or averaged over the sample.
  4. 4. What is wrong with regress price mpg i.foreign#c.mpg?

    A single # gives the interaction term only; the main effect of foreign is missing unless you list it.

Summary

  • i. makes indicators, ib#. picks the base, c. marks continuous variables.
  • ## adds main effects and interaction; # adds the interaction alone.
  • margins, marginsplot, contrast and pwcompare turn coefficients into interpretable results.
  • The Python blocks are stand-ins that show the design matrix and arithmetic.

Next: Regression diagnostics