Wednesday, April 13, 2011

STATA: file write or a way to exporting of almost anything

This is a bit of a repost, but it is so useful that I thought it would useful to people.

Ever want to get a formatted table of summary statitics exported directly from Stata? Outreg2 does a great job with exporting regression results, but what about variable means, variances, or other summary statitics. A great way to do this is with file write. This is a great command and provides you with a lot of control. Its simple:

sysuse auto
file open myfile using"C:/mytable.txt", write replace
file write myfile "Table of descriptive stats" _n _n
file write myfile _tab "Mean" _tab "5th pct" _tab "95th pct"_n
quietly sum price, detail
file write "Price" _tab %7.2f (r(mean)) _tab %7.2f (r(p5)) ///
_tab %7.2f (r(p95)) _n
file close myfile

Here is what just happened. We first open a file with the handle "myfile" that is associated with a text file "mytable.txt". Then I write a header on the first line. The _n sends a hard return, so I sent two hard returns after the header. Then I write my column headers, seperated by tabs (_tab). Then I write my formated summary statistics (%7.2f), again seperated by tabs. Note: you can send anything that is shown in return list or ereturn list so it is pretty flexible. Finally, I close the file. I have created a tab deliminated text file that we can open in excel or elsewhere.

When you combine this with loops and lists of variables that you can store in a local macro, it makes exporting standard tables very easy and automated. See my February 2010 post for a more complicated example.

Happy coding...


  1. Hi Sean! I can understand and execute analogous examples as this one that you gave.

    In your example the variables are written in the lines and the information in the columns. Actualy what I'm tring to do is to display the variables in the columns and the information in the line, the inverse. So I would need to do a loop for each column (variable) and that's where my problem begins because I don't know how to get back to the line 1 of the second variable in txt.

    I there a way to specify the line in txt?

    I appreciate if you can help me.


  2. This is a very good information you have posted. The content are very easy to understand and is remarkable.
    Accounts Software For Small Business

  3. Thanks for sharing This is a great post, I stumbled across your article while looking for some random stuff. Thanks for sharing, I’ll be sure to return regularly.
    Accounts Software For Small Business