8 Stata Output as Tables


8.1 Overview

To include tables of Stata output in a document’s text (as opposed to including Stata output in a specially formatted output block), requires three steps

  • save the Stata output in a form that can be used for a table
  • read the output into R as a matrix or data frame
  • display the output with knitr::kable

8.2 Saving Stata output

Example data set:

sysuse auto
(1978 automobile data)

Use Stata’s putexcel command to save a table of results.

quietly regress mpg weight displacement

quietly putexcel set regress.xlsx, replace

matrix coef = r(table)'
putexcel A1 = matrix(coef), names

quietly putexcel save
file regress.xlsx saved

8.3 Read into R

Use R’s readxl::readxlsx to import the saved table.

x <- readxl::read_xlsx("regress.xlsx")
names(x)[1] <- "variable"   # the first column needs a name
unlink("regress.xlsx")      # cleanup the output file

8.4 Display the Table

Then use knitr::kable to print those results as document text.

variable b se t pvalue
weight -0.0065671 0.0011662 -5.6310042 0.0000003
displacement 0.0052808 0.0098696 0.5350558 0.5942831
_cons 40.0845223 2.0201103 19.8427396 0.0000000