Instant PDF download, name-and-email checkout. Complete Book Bundle: every Economics, Statistics, Mathematics, Econometrics and Research Methods book
Econometrics

How to Run a Regression in Stata, R and Python: Side-by-Side Guide

Run a regression in Stata, R and Python side by side: load data, fit OLS, add robust standard errors and read the real output, with a command map table.

In 30 seconds
  • A regression takes three steps in any language: load the data, fit the model, then ask for the right standard errors.
  • Stata uses regress, R uses lm() and Python uses smf.ols() from statsmodels. All three give the same OLS coefficients.
  • Robust standard errors are one option away: vce(robust) in Stata, vcovHC(type = “HC1”) in R, cov_type=”HC1″ in Python.
  • On 1,000 workers, one more year of education goes with about 11.1% higher hourly pay, holding experience, tenure and gender fixed.
  • A command table at the end maps 14 everyday tasks across Stata, R and Python, so you can switch languages without starting again.

The problem: your first regression, and three different languages

Your module says “use any software you like”. The lecture slides are in Stata, your supervisor works in R, and the tutorials you found use Python. The coursework is due in two weeks.

The good news: the econometrics is the same in all three. Ordinary least squares (OLS) gives the same coefficients whether you type it in Stata, R or Python. Only the words change.

This guide runs one wage equation, side by side, in all three languages. You will load the data, fit the model, switch to robust standard errors and read the output. The Python output shown is the real output from the code. The R and Stata code is shown so you can run it yourself; it fits the same model with the same estimator, so the coefficients and the HC1 robust standard errors match the Python results.

The model: a wage equation

We use the wages file that comes with the Econometrics Made Simple textbook. It holds 1,000 workers with hourly wage (in dollars), years of education, years of experience, years with the current employer (tenure) and a dummy for female. The data are simulated to realistic values, so every result can be reproduced exactly. The average wage is $20.48 and the median is $17.61; average schooling is 11.64 years.

Wages are skewed to the right, so economists model the log of the wage. The equation is:

\[ \log(\text{wage}_i) = \beta_0 + \beta_1\,\text{educ}_i + \beta_2\,\text{exper}_i + \beta_3\,\text{tenure}_i + \beta_4\,\text{female}_i + u_i \]

Each slope is a partial effect: the change in log wage from one more unit of that variable, holding the others fixed. With a log outcome, \(100 \times \beta\) is roughly the percentage change in the wage. The exact percentage is \(100 \times (e^{\beta} – 1)\). Our guide to interpreting log coefficients explains why.

Key termOrdinary least squares (OLS): the method that picks the coefficients \(\hat\beta_0, \dots, \hat\beta_k\) that make the sum of squared residuals \(\sum_i \hat u_i^2\) as small as possible. Every package solves the same minimisation, so they all report the same coefficients for the same data and model.[1]
Econometrics Made Simple textbook coverEconometrics Made Simple explains every regression with real data and Python, R and Stata code.Get the textbook · $15

Step 1: load the data

Put wages.csv in your working folder. Then read it in and create the log wage.

Stata

import delimited using "wages.csv", clear
summarize wage educ exper tenure female
generate lwage = ln(wage)

R

wages <- read.csv("wages.csv")
summary(wages[, c("wage", "educ", "exper", "tenure", "female")])
wages$lwage <- log(wages$wage)

Python

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

wages = pd.read_csv("wages.csv")
print(wages[["wage", "educ", "exper", "tenure", "female"]].describe())
wages["lwage"] = np.log(wages["wage"])

Always look at the summary first: the number of rows (1,000), the range of each variable and any missing values. The lowest wage is $4.33, so the log is fine.

Step 2: run the regression

The command is short in every language. Stata lists the outcome first and then the regressors. R and Python use a formula with a tilde: outcome ~ regressors.

Stata

regress lwage educ exper tenure female

R

m <- lm(lwage ~ educ + exper + tenure + female, data = wages)
summary(m)

Python

model = smf.ols("lwage ~ educ + exper + tenure + female", data=wages)
usual = model.fit()
print(usual.summary())

All three add an intercept: _cons in Stata, (Intercept) in R, Intercept in Python.

Step 3: robust standard errors

The default standard errors assume the error variance is the same for every worker (homoskedasticity). With wage data that is rarely true: pay varies more among the highly educated. Heteroskedasticity-robust standard errors, from White (1980), stay valid either way.[3] Most applied economists use them by default.

Stata’s robust option gives the version called HC1, which scales White’s estimator by \(n/(n-k-1)\). To match Stata, ask for HC1 in R and Python too.

Stata

regress lwage educ exper tenure female, vce(robust)

R

library(sandwich)
library(lmtest)
coeftest(m, vcov = vcovHC(m, type = "HC1"))

Python

robust = model.fit(cov_type="HC1", use_t=True)
print(robust.summary())

In Python, use_t=True makes statsmodels report t statistics and t-based p-values, as Stata does. Without it you get z statistics. The standard errors are the same either way.[4] Our full guide to heteroskedasticity shows how to test for it first.

Common mistakeMixing up HC1 and HC3. R’s vcovHC() uses HC3 if you do not set type, so R and Stata then give slightly different robust standard errors and students think one package is wrong. Neither is wrong: they are different small-sample corrections. Write type = “HC1” when you want to match Stata, and say which one you used in your table notes.

The output: real Python results

Here is the real output from the Python code above, run on the companion data. First the header and the usual (non-robust) coefficients, then the coefficients with HC1 robust standard errors.

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                  lwage   R-squared:                       0.233
Model:                            OLS   Adj. R-squared:                  0.230
Method:                 Least Squares   F-statistic:                     75.58
Date:                Wed, 11 Nov 2026   Prob (F-statistic):           5.54e-56
Time:                        01:14:54   Log-Likelihood:                -619.93
No. Observations:                1000   AIC:                             1250.
Df Residuals:                     995   BIC:                             1274.
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
==============================================================================
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept      1.5285      0.096     16.004      0.000       1.341       1.716
educ           0.1053      0.008     13.758      0.000       0.090       0.120
exper          0.0057      0.002      2.877      0.004       0.002       0.010
tenure         0.0158      0.003      4.953      0.000       0.010       0.022
female        -0.1578      0.029     -5.526      0.000      -0.214      -0.102
==============================================================================
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
Intercept      1.5285      0.090     16.939      0.000       1.351       1.706
educ           0.1053      0.007     14.229      0.000       0.091       0.120
exper          0.0057      0.002      2.784      0.005       0.002       0.010
tenure         0.0158      0.003      4.958      0.000       0.010       0.022
female        -0.1578      0.029     -5.536      0.000      -0.214      -0.102
==============================================================================

The header gives the sample (1,000 workers), the fit (R-squared 0.233) and the overall F test (75.58, p-value 5.54e-56, so the four regressors are jointly significant). The table gives one row per coefficient: the estimate, its standard error, the t statistic, the p-value and the 95% confidence interval. Our guide on how to read regression output explains every number in the header.

Compare the two tables. The coefficients are identical; only the standard errors move. The robust standard error on educ is 0.007 instead of 0.008. Here the change is small; in other data it can be large.

Effect on hourly wage (%, with robust 95% confidence interval)
Estimate95% CI (HC1)
-25%-20%-15%-10%-5%0%+5%+10%+15%+11.1%Education (per year)+0.6%Experience (per year)+1.6%Tenure (per year)-14.6%Female (vs male)
Figure 1. Percentage effects implied by the log wage equation, 100 × (exp(b) − 1), with HC1 robust 95% confidence intervals. Companion wages data (simulated), n = 1,000.

Worked examples: reading the numbers

Worked example

Interpret the education coefficient of 0.1053 as a percentage effect on the hourly wage.

Step 1The outcome is log(wage), so the coefficient is a change in log points: one more year of education raises log wage by 0.1053, holding experience, tenure and gender fixed.
Step 2Quick rule: \(100 \times 0.1053 = 10.53\%\).
Step 3Exact effect: \(100 \times (e^{0.1053} – 1) = 100 \times (1.1110 – 1) = 11.10\%\).
Step 4The robust 95% interval for the coefficient is 0.0908 to 0.1198. Converted the same way, that is 9.50% to 12.73%.

Conclusion: an extra year of education goes with about 11.1% higher hourly pay, other things equal (95% CI 9.5% to 12.7%). This is an association: workers with more schooling may also differ in ability, which this regression does not hold fixed.

Worked example

The female coefficient is −0.1578 with robust standard error 0.0285. Find the percentage gap and test whether it is zero at the 5% level.

Step 1Exact gap: \(100 \times (e^{-0.1578} – 1) = 100 \times (0.8540 – 1) = -14.60\%\). Women earn about 14.6% less per hour than men with the same education, experience and tenure.
Step 2t statistic: \(t = -0.1578 / 0.0285 = -5.54\). The output shows −5.536, computed from unrounded numbers.
Step 3With 995 degrees of freedom, the 5% two-sided critical value is 1.962. Since \(|-5.54| > 1.962\), reject \(H_0: \beta_4 = 0\). The p-value in the output rounds to 0.000.

Conclusion: the gap is about 14.6% and is statistically significant. The robust interval for the coefficient (−0.2138 to −0.1019) gives a gap of 9.7% to 19.3%.

Worked example

Predict the hourly wage of a woman with 16 years of education, 10 years of experience and 5 years of tenure. Compare her with a woman who has 12 years of education and the same experience and tenure.

Step 1Predicted log wage: \(1.5285 + 0.1053(16) + 0.0057(10) + 0.0158(5) – 0.1578 = 3.1905\) (using unrounded coefficients).
Step 2Convert back: \(e^{3.1905} = 24.30\) dollars an hour.
Step 3With 12 years of education the predicted log wage is 2.7694, and \(e^{2.7694} = 15.95\) dollars.
Step 4Ratio: \(24.30 / 15.95 = 1.524\), which equals \(e^{4 \times 0.1053}\). Four extra years raise the predicted wage by about 52%.

Conclusion: the predictions are $24.30 and $15.95 an hour. Because the model is in logs, exponentiating gives a typical (median-type) wage, not the mean; for most coursework this is fine as long as you say so.

Econometrics Practice Questions coverPractise reading real output with the Practice Questions book: 1,161 questions, all fully worked.Get 1,161 questions · $9

Testing several coefficients at once

Do experience and tenure matter together? That is a joint hypothesis, \(H_0: \beta_2 = \beta_3 = 0\), and it needs an F test, not two t tests.

* Stata (after regress ..., vce(robust))
test exper tenure

# R
library(car)
linearHypothesis(m, c("exper = 0", "tenure = 0"), vcov. = vcovHC(m, type = "HC1"))

# Python
print(robust.f_test("exper = 0, tenure = 0"))

In Python the robust F statistic is 38.70 with 2 and 995 degrees of freedom (p-value 6.5e-17). With the usual standard errors it is 44.72. Either way, experience and tenure are jointly significant.

Exam tipExams often print one package’s output and ask you to interpret it. The layout differs, but the five numbers you need are always there: coefficient, standard error, t statistic, p-value and confidence interval. Check that t equals coefficient divided by standard error. If it does, you have found the right columns, whichever software produced the table.

Command map: Stata, R and Python side by side

This table covers the commands you will use most in a first econometrics course. R examples assume a fitted model called m; Python examples assume a fitted result called res and the imports shown earlier.

TaskStataRPython (statsmodels)
Load a CSV fileimport delimited using “wages.csv”, clearwages <- read.csv(“wages.csv”)wages = pd.read_csv(“wages.csv”)
Summary statisticssummarizesummary(wages)wages.describe()
New variable (log)generate lwage = ln(wage)wages$lwage <- log(wages$wage)wages[“lwage”] = np.log(wages[“wage”])
Squared termgenerate expersq = exper^2I(exper^2) in the formulaI(exper**2) in the formula
OLS regressionregress lwage educ experm <- lm(lwage ~ educ + exper, data = wages)res = smf.ols(“lwage ~ educ + exper”, data=wages).fit()
Show results(shown automatically)summary(m)print(res.summary())
Robust SEs (HC1), vce(robust)coeftest(m, vcov = vcovHC(m, type = “HC1”)).fit(cov_type=”HC1″, use_t=True)
Clustered SEs, vce(cluster firm)coeftest(m, vcov = vcovCL(m, cluster = ~firm)).fit(cov_type=”cluster”, cov_kwds={“groups”: wages[“firm”]})
Dummies for a categoryi.regionfactor(region)C(region)
Interactionc.educ#i.femaleeduc:femaleeduc:female
Fitted valuespredict yhat, xbfitted(m)res.fittedvalues
Residualspredict uhat, residualsresid(m)res.resid
Joint F testtest exper tenurelinearHypothesis(m, c(“exper = 0”, “tenure = 0”))res.f_test(“exper = 0, tenure = 0”)
Subsampleregress lwage educ if female == 1lm(lwage ~ educ, data = subset(wages, female == 1))smf.ols(“lwage ~ educ”, data=wages[wages.female == 1]).fit()

Two notes. Clustered standard errors need a group variable (firm is only an example; the wages file has none). In R, vcovHC and vcovCL come from the sandwich package, coeftest from lmtest and linearHypothesis from car; install them once with install.packages().

Common mistakeForgetting that R and Python formulas treat a categorical text variable differently from a number. If region is stored as 1, 2, 3, 4, then lm() and smf.ols() treat it as one continuous variable with a single slope, which is meaningless. Wrap it in factor() in R or C() in Python, just as you would use i.region in Stata.

Which language should you learn first?

Follow your course. Stata has short commands and needs a licence; R and Python are free, and with packages such as sandwich (R) or statsmodels and linearmodels (Python) they cover robust errors, instrumental variables and panel data.[4] For a dissertation, choose the language your supervisor can read. Our econometrics dissertation guide covers the rest of the project.

Free resources and what the book adds

You can do a lot for free. This post gives you a full first regression in three languages. Our free econometrics guides cover OLS, hypothesis tests, heteroskedasticity, instrumental variables and more. Wooldridge and Stock and Watson are the standard textbooks if your library has them.[1][2]

What the Econometrics Made Simple textbook adds is one consistent path through the whole course: 20 chapters and 589 pages, from your first regression to unit roots and cointegration, with every result run in Python, R and Stata and the actual output printed. It has 73 worked examples and 327 end-of-chapter questions with worked answers, 200+ scripts and 11 companion datasets, including the wages file used here. You can flip through the free sample on the product page before you decide: Econometrics Made Simple textbook.

Econometrics Made Simple bundle coverMaster regression in Stata, R and Python with both Econometrics Made Simple books for $19.Both books · $19

Want to go further? The Econometrics Made Simple textbook covers every method with Python, R and Stata output, and the Econometrics Made Simple Practice Questions book gives you 1,161 questions with worked answers, including a part on reading real software output in every chapter.

Practice questions

EasyQ1. Write the command to regress lwage on educ and exper with robust (HC1) standard errors in Stata, R and Python. Show worked answer
Stata: regress lwage educ exper, vce(robust)
R: m <- lm(lwage ~ educ + exper, data = wages); coeftest(m, vcov = vcovHC(m, type = “HC1”))
Python: smf.ols(“lwage ~ educ + exper”, data=wages).fit(cov_type=”HC1″, use_t=True)
All three give identical coefficients and identical HC1 standard errors.
EasyQ2. In the output above, the tenure coefficient is 0.0158. What is the approximate percentage effect of one more year of tenure on the hourly wage? Show worked answer
Approximate: 100 × 0.0158 = 1.58%.
Exact: 100 × (e^0.0158 − 1) = 1.59%.
One more year with the same employer goes with about 1.6% higher hourly pay, holding education, experience and gender fixed.
MediumQ3. With usual standard errors, exper has t = 2.877; with robust standard errors, t = 2.784. The coefficient is 0.0057 in both. Explain why t changed and whether the conclusion at 5% changes. Show worked answer
t = coefficient / standard error. The coefficient is unchanged, so the change comes from the standard error.
Usual SE = 0.005654 / 2.877 = 0.001965; robust SE = 0.005654 / 2.784 = 0.002031. The robust SE is about 3% larger.
The 5% critical value is about 1.962. Both 2.877 and 2.784 exceed it, so experience is significant either way (robust p-value 0.005).
MediumQ4. Using the coefficients above, how much higher is the predicted hourly wage of a man than of an otherwise identical woman? Give the answer as a percentage of the woman’s wage. Show worked answer
The man’s predicted log wage is higher by 0.1578.
Ratio of wages: e^0.1578 = 1.171.
The man’s predicted wage is 17.1% higher than the woman’s. (Measured from the man’s wage, the woman’s is 14.6% lower; the two percentages differ because the base differs.)
ExamQ5. A student runs the wage regression in R with coeftest(m, vcov = vcovHC(m)) and gets robust standard errors that differ slightly from the Stata output of regress …, vce(robust). (a) Explain why. (b) State how to make them match. (c) Using the robust results above, construct and interpret a 95% confidence interval for the education coefficient. [6 marks] Show worked answer
(a) vcovHC() defaults to HC3, while Stata’s vce(robust) is HC1. They use different small-sample adjustments, so the standard errors differ slightly. [2 marks: 1 for naming the defaults, 1 for the reason]
(b) Use vcovHC(m, type = “HC1”) in R. [1 mark]
(c) CI = 0.1053 ± 1.962 × 0.0074 = 0.1053 ± 0.0145, i.e. 0.0908 to 0.1198 (the output prints 0.091 to 0.120). [2 marks: 1 for the method, 1 for the values]
Interpretation: we are 95% confident that one more year of education raises log hourly wage by between 0.091 and 0.120, roughly 9.5% to 12.7% higher pay, holding the other regressors fixed. [1 mark]

Frequently asked questions

Do Stata, R and Python give exactly the same regression results?

Yes for OLS coefficients, R-squared and the usual standard errors, because they solve the same least squares problem. Robust standard errors match when you ask for the same version, such as HC1 in all three. Small differences usually come from different defaults, dropped missing values or different variable definitions.

Should I always use robust standard errors?

In cross-section data, most applied economists report heteroskedasticity-robust standard errors by default. They are valid whether or not the errors are heteroskedastic, and in large samples they cost little. With grouped data, such as workers within firms, use clustered standard errors instead.

Why does Python show z instead of t for robust standard errors?

When you change the covariance type, statsmodels switches to the normal distribution by default. Add use_t=True to get t statistics and t-based p-values. With 995 degrees of freedom the two are almost identical.

Can I use Excel for econometrics coursework?

Excel can run a basic OLS regression, but it does not give robust or clustered standard errors, instrumental variables or panel models without add-ins. For anything beyond a first exercise, a statistics language is safer and your work is easier to reproduce.

References

  1. Wooldridge, J. M. (2020). Introductory Econometrics: A Modern Approach, 7th edition. Boston: Cengage Learning. https://www.cengage.com/c/isbn/9781337558860
  2. Stock, J. H. and Watson, M. W. (2019). Introduction to Econometrics, 4th edition. Pearson. Pearson product page
  3. White, H. (1980). A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity. Econometrica, 48(4), 817–838. Econometric Society
  4. Seabold, S. and Perktold, J. (2010). Statsmodels: econometric and statistical modeling with Python. Proceedings of the 9th Python in Science Conference, 92–96. https://proceedings.scipy.org/articles/Majora-92bf1922-011.pdf
Econometrics Made Simple Complete Bundle: textbook and practice book
This topic has a full chapter in Econometrics Made Simple, with Python, R and Stata code and 1,161 worked practice questions in the bundle.Econometrics Made Simple Complete Bundle — Textbook + 1,161 Practice Questions
Get it for $19
E

The EconTutorials team writes clear, exam-focused lessons in economics and statistics for A-Level, IB, AP and university students, with more than 13 years of classroom teaching behind every guide and book in the Made Simple series.