Friday, December 11, 2009

Automatically Generating Reports with Stata

At PPRI, we get a lot of data in waves, so we end of recreating various versions of the same report with updated data.  This can become tiresome when having to recreate, re-copy/paste, and reformat lots of tables and figures.  Thankfully, Roger Newson, from Imperial College London, has created some ado-files, called -rtfutil-,  that help automate the insertion of these elements into a .rtf document.
Here's an snippet of how I've adopted his example code to help automatically generate some reports with new data:

*-----------------------BEGIN CODE
local sf  "`pwd'"
sysuse auto, clear
twoway scatter mpg price, mlabel(make) || lfitci mpg price
graph export "`sf'myplot1.eps", replace
twoway scatter price mpg, mlabel(make) by(for)
graph export "`sf'myplot2.eps", replace
     tempname handle1
rtfopen `handle1' using "`sf'mydoc1.rtf", replace
file write `handle1' _n _tab "{\pard\b SAMPLE DOCUMENT \par}" _tab _n
file write `handle1' _n "{\line}"
// Figure1
file write `handle1' "{\pard\b FIGURE 1: Plot of Price\par}" _n
rtflink `handle1' using "`sf'myplot1.eps"
// Figure2
file write `handle1' _n "{\page}" _n /*
*/ "{\pard Here is the plot and a paragraph about it. Here is the plot and a paragraph about it. Here is the plot and a paragraph about it. Here is the plot and a paragraph about it.....blah blah blah blah blah \line}" _n
file write `handle1' _n "{\line}"
file write `handle1' "{\pard\b FIGURE2: Plots of Price vs. MPG\par}" _n
rtflink `handle1' using "`sf'myplot2.eps"

// Table Title
file write `handle1' _n "{\page}" _n
file write `handle1' _n "{\par\pard}" _n /*
*/ "{\par\pard HERE IS A TABLE WITH THE CARS: \par\pard}" _n
file write `handle1' _n "{\par\pard}" _n

// Summary Table
rtfrstyle make mpg weight, cwidths(2000 1440 1440) local(b d e)
listtex make foreign mpg if mpg<15, /*
*/ handle(`handle1') begin("`b'") delim("`d'") end("`e'") /*
*/ head("`b'\ql{\i Make}`d'\qr{\i Foreign}`d'\qr{\i MPG }`e'")
file write `handle1' _n "{\line}"
file write `handle1' _n _tab(2) /*
*/ "{\pard\b Sources: Census Data, etc... \par}" _n _n
rtfclose `handle1'
*-----------------------END CODE

I posted this as part of a solution to a question at StackOverflow.  You can get -rtfutil- here or by typing "ssc install rtfutil" in Stata.

No comments:

Post a Comment