10 RMarkdown & Knitr

10.1 Knitr

Knitr is a feature in RStudio that will turn your R programme into a HTML (or PDF/Word) document.

You need to use RMarkdown, and write your R code in ‘chunks’. You can include regular markdown text, and also html, javascript or python.

Knitr will evaulate all the code and embed any tables/charts/maps into the output.

10.2 YAML

At the top of all RMarkdown documents there is some YAML code:

YAML includes information that tells Knitr what type of document to create. In the example above it wil be a HTML document.

However it cann also be used to add a table of contents, or to allow users to input cutom paraemters.

Adding a table of contents

Nb. That the contents is automatically generated based on any RMarkdown header tags ‘#’ that you have used.

Adding parameters Parameters can be added after the params: option. They must have a label and a value. By defaut the parameter will be a textbox.

Different types of parameter input are allowed, such as check boxes and dropdown lists.

You can refer to the parameter values in the rest of the your code using the form params%parametername1

To use these parameters the Rmarkdown document must be Knitted using ‘Knit with parameters…’

10.3 Modular coding

If your R code is written in modules, then you can call them using the source() function, eg: