R knitr
knitr
This page contains examples for the use of knitr
to create documents from RMarkdown or LaTex sources.
knitr
is an R package for literate programming. It is integrated with R Studio and the exercises on this page assume you have R Studio installed.
RMarkdown
Markdown is an extremely simple and informal way of structuring documents that is useful if for some reason you feel html is too complicated. That's really all it does: format documents in a simple way so they can be displayed as Web pages. For Markdown documentation, see here.. The concept is quite similar to Wiki markup syntax, the syntax is (regrettably) different, and for a number of features there there are (regrettably) several different ways to achieve the same results.
RMarkdown is an R package that is integrated with R Studio and allows integrating R code with Markdown documents. knitr can work with Markdown files, and this gives additional output options, such as PDF and MSWord documents.
Let's give it a try: we'll develop an R function that will give us a random phobia to ponder on.
Task:
- Open an R Studio session.
- Select Session → Set Working Directory → Choose Directory... and choose some project directory.
- Select File → New File → RMarkdown.... R Studio will ask you whether you want to install/update a number of required packages. Click Yes.
- Enter "Random Phobia" as the Title and your name as the Author, select to create a Document, and check Word as the default output option.
R Studio will load some default text and markup into the script pane which we can edit.
Let's introduce our plan: copy/paste the following text into the document.
Phobias! We all have some that we might not even be aware of. How to know them all? With this code we access the Oxford English Dictionary's Website - the most authoritative source on the English language, and scrape a list of phobias. A function is supplied to retrieve a random phobia, which we can subsequently ponder on - either to delight in the fact that we don't have that fear, or to add to our daily quota of anxieties (like our well-founded [fear of bad programming practice](http://xkcd.com/292/)).
Note the following Markdown elements in the code:
- - a tag
<small>Text...</small>
to set text to a smaller font size (we could have used<span style="font-size:85%;">Text...</span>
instead because Markdown respects HTML elelements).
- - a tag
- - a Web link
[Text...](URL)
added to text
- - a Web link
- Save the file in your project directory, note that the extension
.Rmd
is automatically added.
Contents
Notes
Further reading and resources