R-Markdown and Knitr Tutorial (Part 1)

R-Markdown is a great way to create dynamic documents with embedded chunks of R code. The document is self contained and fully reproducible which makes it very easy to share. This post will be the first in a multi part series on how to embed Plotly graphs in R-Markdown documents as well as presentations.

R-Markdown is a flavor of markdown which allows R-users to embed R code into a markdown document. The document is then ‘knit’ using knitr to create a HTML file.

Getting started

  • Note: you can download the function definition for GetYahooData() here
  • Now we should be good to go…

Creating a R-Markdown document

  • Click on File -> New File -> R Markdown as shown below.

  • You should now see a dialog as shown below. Select ‘Document’ in the left panel and fill in title and author field and hit ‘OK’.

  • You should now have a document which looks like this –

Code chunks

To embed R code into the document, code needs to be inserted as shown below.

Inserting a Plotly graph

Inserting an awesome interactive Plotly chart is as simple as printing out the plotly object in a code chunk. Use the code snippet below.

Knitting the R-Markdown document

Now that our R-Markdown document is complete with text, code and graphs, we can go ahead and click the little ‘Knit HTML’ button to generate a HTML file.

We now have a nicely formatted HTML file !

Further reading

Please refer to the following resources for more details
R-Markdown cheatsheet
Plotly R Library

More to come…