Improving Stata Newey-West Command Output
Published:
Stata’s built-in newey command does not output \( R^2 \) and adjusted \( R^2 \) by default. Notably, the \( R^2 \) from newey is the same as that from OLS. To facilitate exporting these statistics — particularly for use with reg2docx — I’ve created a custom command called newey_r2.
What This Solves
- Stata's
neweyomits \( R^2 \) and adjusted \( R^2 \) from its output. - This makes it difficult to export complete regression tables via
esttaborreg2docx. - The
newey_r2command wrapsneweyand adds these statistics back, with automatic lag selection.
The newey_r2 Command
The program runs OLS first to capture \( R^2 \), then executes newey with HAC standard errors, and stores both statistics in e() for downstream use.
cap program drop newey_r2
program define newey_r2, eclass
syntax varlist [if] [in], [lag(string) otheropt(string)]
marksample touse
qui count if `touse'
local N = r(N)
if "`lag'" == ""{
local lag = floor(4 * (`N' / 100)^(2 / 9))
}
qui reg `varlist' if `touse'
local r2 = e(r2)
local r2_a = e(r2_a)
dis as text "Newey-West regression using newey_r2" _c
dis as text _column(49) "R-squared" _c
dis as text _column(67) "=" _c
dis as result %11.4f `r2'
dis as text _column(49) "Adj R-squared" _c
dis as text _column(67) "=" _c
dis as result %11.4f `r2_a' _c
newey `varlist' if `touse' , force lag(`lag') `otheropt'
ereturn scalar r2 = `r2'
ereturn scalar r2_a = `r2_a'
end
Automatic lag selection When no lag is specified, the command uses the Newey-West optimal lag formula: \( \lfloor 4 \times (N / 100)^{2/9} \rfloor \). See MathWorks HAC documentation for details.
Installation
Step 1 — Locate the ado directory
- Ubuntu:
/home/USERNAME/STATA_DIR/ado/base/n - Mac:
/Applications/Stata/ado/base/n
Step 2 — Create the ado file
Open or create newey_r2.ado in that directory and paste the program code above.
sudo vim newey_r2.ado
Testing
Verify the command works correctly with sample data:
eststo clear
webuse idle2, clear
tset time
* Standard newey (no R² in output)
eststo: newey usr idle, lag(3) force
est store m1
* newey_r2 with explicit lag
eststo: newey_r2 usr idle, lag(3)
est store m2
* newey_r2 with automatic lag selection
eststo: newey_r2 usr idle
est store m3
* Test with irregularly spaced data
webuse idle2, clear
tset time
drop if time == 2
eststo: newey usr idle, lag(3) force
est store m1
eststo: newey_r2 usr idle, lag(3)
est store m2
eststo: newey_r2 usr idle
est store m3
* Export results
esttab using ./test.csv, b(3) t(2) ar2(3) ///
star(* 0.10 ** 0.05 *** 0.01) nogaps nonotes replace
eststo clear
Tip The
force option is built into newey_r2, so you don't need to specify it manually — useful for irregularly spaced time-series data.