Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice: Stata Regression, Panel and Programming Exercises

Ten graded Stata exercises on regression, factor variables, logit, panel data, time series, loops, programs and reporting, with solutions and Python stand-ins.

Reading about commands is not the same as using them. This page gives you ten exercises that cover the second half of the course: regression, panel and time series, programming and reporting. Each has a task, a hint you can try before looking, and a model solution. Do them in your own copy of Stata, using the built-in datasets (sysuse auto, sysuse nlsw88, webuse nlswork, webuse air2) so that nothing needs downloading.

Stata cannot run on this site, so Stata solutions are read-only and we print no Stata output. Where a calculation can be rehearsed, a Python stand-in checks the idea with simulated data. Always run the Stata solution yourself and compare with your own answer.

Exercise 1: regression basics

Task. Using auto, regress price on mpg and weight. Report the change in price for 1,000 extra pounds, and the share of variance explained.

Solution.

STATA
sysuse auto, clear
gen weight1000 = weight / 1000
regress price mpg weight1000
display "R-squared: " %5.3f e(r2)

The weight1000 coefficient is the effect of 1,000 pounds, holding mpg fixed. Rescaling is cleaner than multiplying later. See the regress lesson.

Exercise 2: factor variables

Task. Let the slope of mpg differ for foreign and domestic cars and report the slope for each group.

Solution.

STATA
regress price c.mpg##i.foreign weight
margins, dydx(mpg) over(foreign)

The two numbers are the group-specific slopes; the ## term is their difference (factor variables).

Exercise 3: diagnostics

Task. After exercise 1, test for heteroskedasticity and rerun with robust errors. Which numbers change?

Solution.

STATA
regress price mpg weight1000
estat hettest
regress price mpg weight1000, vce(robust)

Only the standard errors, t statistics, p-values and intervals change; the coefficients are identical (diagnostics).

Exercise 4: a binary outcome

Task. Model foreign using mpg and weight1000 with logit. Report the average marginal effect of mpg and the correct reading of its odds ratio.

Solution.

STATA
logit foreign mpg weight1000
margins, dydx(mpg)
logit, or

The marginal effect is a change in probability; the odds ratio multiplies the odds (logit lesson).

Exercise 5: panel structure

Task. Using webuse nlswork, declare the panel, check balance and find out which of ln_wage, union and race have within variation.

Solution.

STATA
webuse nlswork, clear
xtset idcode year
xtdescribe
xtsum ln_wage union race

race has zero within standard deviation; it cannot be estimated with fixed effects (panel lesson).

Exercise 6: fixed versus random

Task. Estimate ln_wage on age, ttl_exp and union with FE and RE and compare them with a Hausman test.

Solution.

STATA
xtreg ln_wage age ttl_exp union, fe
estimates store fe
xtreg ln_wage age ttl_exp union, re
estimates store re
hausman fe re

A small p-value favours fixed effects (FE and RE).

Exercise 7: time series

Task. With webuse air2, declare the series, take logs, plot, and fit an ARIMA(0,1,1) with a seasonal MA at lag 12.

Solution.

STATA
webuse air2, clear
tsset t
gen lnair = ln(air)
tsline lnair
arima lnair, arima(0,1,1) sarima(0,1,1,12)
predict res, residuals
wntestq res

The logs stabilise the growing seasonal swings (ARIMA lesson).

Exercise 8: loops

Task. For each of price, mpg and weight, create a standardised copy named z_<name> and check each has mean zero.

Solution.

STATA
foreach v of varlist price mpg weight {
    quietly summarize `v'
    generate z_`v' = (`v' - r(mean)) / r(sd)
    quietly summarize z_`v'
    assert abs(r(mean)) < 1e-6
}

See loops and macros.

Exercise 9: a program

Task. Write pctdiff that takes two variables and reports the mean percentage difference in r(pct).

Solution.

STATA
capture program drop pctdiff
program define pctdiff, rclass
    version 18
    syntax varlist(min=2 max=2 numeric) [if] [in]
    marksample touse
    tokenize `varlist'
    tempvar d
    quietly generate double `d' = 100 * (`2' - `1') / `1' if `touse'
    quietly summarize `d'
    return scalar pct = r(mean)
    display "Mean percentage difference: " %6.2f r(mean)
end
pctdiff price mpg

See programs.

Exercise 10: a table

Task. Store three nested models of price and export them as output/models.rtf with robust errors in parentheses.

Solution.

STATA
regress price mpg, vce(robust)
estimates store a
regress price mpg weight1000, vce(robust)
estimates store b
regress price mpg weight1000 i.foreign, vce(robust)
estimates store c
esttab a b c using "output/models.rtf", replace se star(* .1 ** .05 *** .01) label

See tables.

Rehearse exercise 9 in Python

The idea of exercise 9 (parse arguments, mark the sample, compute, return) is language-independent. This stand-in checks it on a few numbers you can verify by hand.

Python pctdiff stand-in (Python)

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.

Check your answers

A second stand-in lets you check regression answers you computed by hand for exercise 1: it fits a small dataset and prints the numbers you should expect from the same formulas.

Python Check a tiny regression by hand (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.

Going further

  • Repeat exercises 6 and 7 on your own data and write a do-file with a log and a seed.
  • Rerun the wage project with clustered errors.
  • Write a new program that wraps a loop from exercise 8.
  • Replicate the difference-in-differences project on a dataset of your choice and plot an event study.
  • Open the track page for the lessons on the basics and data management.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which change leaves regression coefficients unchanged but alters standard errors?

    Robust variance estimators change only the uncertainty measures.
  2. 2. A variable with zero within variation in xtsum

    Fixed effects uses only within-unit changes.
  3. 3. In the program of exercise 9, what does marksample touse provide?

    It combines if, in and missing-value filters into one indicator.
  4. 4. Which approach best prevents errors in tables of results?

    Code-generated tables are reproducible and free of transcription mistakes.

Summary

  • The ten exercises revisit regression, factor variables, diagnostics, logit, panel, ARIMA, loops, programs and tables.
  • Solutions use built-in datasets so you can run them without downloading anything.
  • Python stand-ins let you rehearse the logic; the Stata output is yours to produce.

Next: Back to the Stata track