11 Keeping Intermediate Files

The process of “knitting” or “rendering” a document from the source document you write to it’s final form takes several steps, and produces intermediate files along the way. Ordinarily, these intermediate files are temporary, and disappear when processing your document is complete. But there are a number of scenarios in which you might want to save intermediate files.

When working with Statamarkdown, the intermediate files you might save are

  • Stata do and log files
  • a Markdown file
  • a LaTeX file (when producing a PDF)

As knitr works its way through your source document, each code chunk it encounters is dynamically processed in the appropriate language (R, Stata, something else). In the case of Stata code chunks, these are saved as (temporary) do files and then processed by Stata in batch mode.

(If R fails to find Stata to process these files, this produces an error but no log file. The temporary do file disappears. You need to go back and figure out how to specify the Stata “engine”/executable path.)

As Stata processes each do file, the log is read back into R and “knit” into an intermediate Markdown file. The temporary do file and log file disappear as each code chunk is knit into the Markdown document.

Once the Markdown file is complete, it is then converted into the document in it’s final format, and the temporary Markdown document disappears.

11.1 Saving the Stata do and log files

Each Stata code chunk produces a Stata do file, which in turn is used to produce a Stata log file. These can be saved by setting the chunk option, savedo=TRUE. In a document that might look like this

```{stata, savedo=TRUE}
sysuse auto
summarize
```

The name of the do file is taken from the code chunk label. Unlabeled chunks produce do files with names like “unnamed-chunk-1.do”. The log files then take the same names, substituting a log file extension.

If you want to save all the Stata code chunks used in your document, you can include an initial code chunk that sets this option globally, like

```{r}
knitr::opts_chunk$set(savedo=TRUE)
```

11.2 Saving the Markdown file

Saving the Markdown file is a knitr option, which can be set in the initial document YAML (header).

---
title: "Stata Solves Everying"
author: "Doug Hemken"
date: "`r Sys.Date()`"
output: 
  html_document:
    keep_md: yes
---

11.3 Saving the LaTeX file

Saving a TeX document for producing PDFs is similar to saving the intermediate Markdown file.

---
title: "Stata Solves Everying"
author: "Doug Hemken"
date: "`r Sys.Date()`"
output: 
  pdf_document:
    keep_tex: yes
---

In this case, you could keep both the Markdown and the LaTeX.

This page was written using:

  • Statamarkdown version 0.9.2
  • knitr version 1.45