Knitting

Keep your source code readable, and your output reproducible.

Alternatively, open an interactive version of this article in your browser:

R Markdown is designed to keep your source code separate from your output. Why? Because you will want to save your source code as a readable record of what you did. The source code can then be used to “play back” that record and (re-)produce the output. To be reproducible though, you have to first produce something—let’s render this .Rmd to produce an output file.

Knitting the source file

The file extension .Rmd makes your file executable, which means that this file can be used to both save and execute code. Here is a code chunk:

```{r}
1 + 1
```

Any output your code produces like tables, plots, or other results can be included when you render your document. This process is called knitting, because you are executing code and knitting the output back into the document. There is a special button for it in RStudio that looks like this:

NOTE: You may also use keyboard shortcuts to knit:

  • Ctrl + Shift + K on Windows
  • Cmd + Shift + K on Mac

The output file

When we knit, R Markdown generates a new file that now contains four elements:

  • Metadata at the top (we see the title)
  • Narrative text
  • A code chunk (but we only see one…)
  • Results (a plot!)

The output format

This output file is an HTML document. This is a type of output, which was stored in the document’s metadata block:

---
title: "Early words"
output: html_document
---

Output formats are one of the most versatile features of R Markdown—you can use them to build web pages like this one, Word documents, PDFs, multi-page websites, slides, and even write books.

What’s next?

While this is a polished and shareable document as is, it is not likely that your work stops there—but it is a great place to start. Next, we’ll show how to use R Markdown to develop your ideas alongside your code using narrative text.