Search code examples
formatexportstataspace

How to export from data using esttab or estout


Say that I have these data:

sysuse auto2, clear
gen name = substr(make, 1,3)
drop if missing(rep78)
gen n = 1
collapse (mean) mpg (sum) (n), by(name)
replace name = "a b: c" if _n==1

I would like to export them to an .rtf (.tex, etc.) file directly from the data using esttab or estout. Is this possible? The key reason I want to do this is that I want to be able to preserve the spaces in the row names. And it would be nice to able to have the option to have commas after for 1,000's.

One partial approach is to save the data to a matrix, then export the matrix using esttab, but can I need this extra step?

mkmat mpg n, matrix(mat) rownames(name)
esttab matrix(mat)

A problem with this is that it replaces the spaces in the row names with _'s. Another problem is that if any of the rownames (from the variable name) are :, then this creates the category in the output. Is there another solution? Either to directly export from the data or possibly to somehow save the data in an estimation?


Solution

  • Instead of using collapse, you can calculate means and counts directly with estpost tabstat, statistics(mean count) by(). You can then use esttab to export the results.

    If you really want to create a dataset first, you can still use estpost tabstat. This appears to work for your dataset:

    estpost tabstat mpg n, by(name) nototal
    esttab, cells("mpg n") varlabels(`e(labels)') noobs nonumber nomtitle
    

    If you want to have "a b: c" on top again you can use the order option of esttab.