I would like to export summary statistics produced with the xtsum
command:
webuse nlswork, clear
xtsum hours birth_yr
Variable | Mean Std. Dev. Min Max | Observations
-----------------+--------------------------------------------+----------------
hours overall | 36.55956 9.869623 1 168 | N = 28467
between | 7.846585 1 83.5 | n = 4710
within | 7.520712 -2.154726 130.0596 | T-bar = 6.04395
| |
birth_yr overall | 48.08509 3.012837 41 54 | N = 28534
between | 3.051795 41 54 | n = 4711
within | 0 48.08509 48.08509 | T-bar = 6.05689
Is there a way to do this in Stata?
Below you can find an implementation, which uses the community-contributed command esttab
(type ssc install estout
to download) for exporting the produced (LaTeX
) table.
First define program xtsum2
:
program define xtsum2, eclass
syntax varlist
foreach var of local varlist {
xtsum `var'
tempname mat_`var'
matrix mat_`var' = J(3, 5, .)
matrix mat_`var'[1,1] = (`r(mean)', `r(sd)', `r(min)', `r(max)', `r(N)')
matrix mat_`var'[2,1] = (., `r(sd_b)', `r(min_b)', `r(max_b)', `r(n)')
matrix mat_`var'[3,1] = (., `r(sd_w)', `r(min_w)', `r(max_w)', `r(Tbar)')
matrix colnames mat_`var'= Mean "Std. Dev." Min Max "N/n/T-bar"
matrix rownames mat_`var'= `var' " " " "
local matall `matall' mat_`var'
local obw `obw' overall between within
}
if `= wordcount("`varlist'")' > 1 {
local matall = subinstr("`matall'", " ", " \ ",.)
matrix allmat = (`matall')
ereturn matrix mat_all = allmat
}
else ereturn matrix mat_all = mat_`varlist'
ereturn local obw = "`obw'"
end
You can then run xtsum2
and get the results with esttab
:
xtsum2 hours birth_yr
esttab e(mat_all), mlabels(none) labcol2(`e(obw)') varlabels(r2 " " r3 " ")
------------------------------------------------------------------------------------------
Mean Std. Dev. Min Max N/n/T-bar
------------------------------------------------------------------------------------------
hours overall 36.55956 9.869623 1 168 28467
between . 7.846585 1 83.5 4710
within . 7.520712 -2.154726 130.0596 6.043949
birth_yr overall 48.08509 3.012837 41 54 28534
between . 3.051795 41 54 4711
within . 0 48.08509 48.08509 6.056888
------------------------------------------------------------------------------------------
For LaTeX
output, simply add the tex
option:
esttab e(mat_all), mlabels(none) labcol2(`e(obw)') varlabels(r2 " " r3 " ") tex
\begin{tabular}{lc*{5}{c}}
\hline\hline
& & Mean& Std. Dev.& Min& Max& N/n/T-bar\\
\hline
hours & overall & 36.55956& 9.869623& 1& 168& 28467\\
& between & .& 7.846585& 1& 83.5& 4710\\
& within & .& 7.520712& -2.154726& 130.0596& 6.043949\\
birth\_yr & overall & 48.08509& 3.012837& 41& 54& 28534\\
& between & .& 3.051795& 41& 54& 4711\\
& within & .& 0& 48.08509& 48.08509& 6.056888\\
\hline\hline
\end{tabular}