Thus far, we’ve shown how you can use R Markdown with RStudio to interactively develop code inside an .Rmd
document. Next, we showed how you can also take the same .Rmd
document and knit it to make a single output file, like a simple HTML page. So, you have learned how to fill up an .Rmd
file with your good ideas, code, and data. How does it all actually work?
The knitr package
When you click the “Knit” button, the rmarkdown packages feeds the .Rmd
file to another R package called knitr (https://yihui.org/knitr/).
The knitr package executes all of the code chunks and creates a new markdown (.md
) document, which then includes your good ideas plus your code and its output (figures, results, tables, etc.).
So, knitr turns your .Rmd
into an .md
. This file is no longer executable, but it is still a plain text document without any formatting. Because of this, the actual .md
file is temporary and not kept by default.
.Rmd
.md
If you want to keep a copy of the Markdown file after rendering, you can do so using the keep_md
option:
---
output:
html_document:
keep_md: true
---
Pandoc
The markdown file generated by knitr is then processed by a tool called Pandoc (https://pandoc.org/).
Pandoc is a free and open-source document converter. The rmarkdown package calls Pandoc for you to create the finished output file. Pandoc also transforms your Markdown-flavored text into formatted text in your final file format.
If you choose an output
in your YAML, this is passed to Pandoc to convert the .md
into the right format. This is the formatted document that you’ll want to read and share with others.
three columns: html / word / pdf
Render from the command line
This may all sound complicated, but rmarkdown and RStudio makes this simpler for you by wrapping it all up with the “Knit” button.
If you don’t use RStudio, or if you simply prefer using the command line, you can also knit an .Rmd
file from the R console.
library(rmarkdown)
render("early-words.Rmd")
The render()
function will pass your .Rmd
file through the same process described above with knitr and Pandoc.
What’s next?
One of the most powerful features of the knitr package is how it helps you control how your code and output look in your final finished product. Want to hide some gnarly-looking code that nevertheless makes a beautiful plot? Want to save all the plots you made in a directory when you knit? Read on to learn about knitr code chunk options for figures.