9 Spin Stata

Occasionally you may wish you could take a Stata do file and knit it so that the comments were treated as Markdown.

This is what spinstata is for.

This function takes a Stata do file containing special mark up in it’s comments, and converts it into knitr’s “spin” format. The resulting document is in turn sent to knitr::spin, converted to Markdown, knit, and finally compiled to HTML or one of several other rmarkdown formats.

In order to coexist with the Stata code in a do file, the markup distinguishing different elements of a document take the form of special Stata comments.

Spin Stata Markup:

  • /*' - Begin document text, ends with '*/

  • /*+ - Begin chunk header, ends with +*/

  • /*R - Begin a chunk of R code, ends with R*/

  • */* - Dropped from the document, ends with */*

Ordinarily, you will begin with a Stata do file, and add comments. Suppose your plain do file looked like this:

sysuse auto
/* Stata comment */
summarize

You embellish by adding some explanatory text, saving it again as an enhanced do file, for example as spinstata_example.do:

/*'
This is a Stata script (a do file) which can 
also be used to generate a report.
You can write normal text in delimited comments.

First we specify a path for Stata and set up some options.
'*/

/*+  spinsetup +*/
/*R
library(Statamarkdown)
knitr::opts_chunk$set(comment=NA)
R*/

/*' The report begins here. '*/

/*+  example1, engine='stata' +*/
  sysuse auto
/* Stata comment */
  summarize

/*' You can use the ***usual*** Markdown.'*/

Note that if you open this file in the Stata editor you can execute the Stata commands, just like any other do file.

To knit the file and process the Markdown, in R issue the command:

Statamarkdown::spinstata("spinstata_example.do")

This would produce a document that looks like this