Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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

# Not run
# install.packages('rmarkdown')
# install.packages('plotly')
• 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.

source("Yahoo Stock Data Pull.R")

AAPL <-  GetYahooData("AAPL")
IBM <- GetYahooData("IBM")

# Plotly chart
library(plotly)
mat <-  data.frame(Date = AAPL$Date, AAPL = round(AAPL$Adj.Close,2),

p <- mat %>%
plot_ly(x = Date, y = AAPL, fill = "tozeroy", name = "Microsoft") %>%
add_trace(y = IBM, fill = "tonexty", name = "IBM") %>%
layout(title = "Stock Prices",
xaxis = list(title = "Time"),
yaxis = list(title = "Stock Prices"))
p  # Thats it !

### 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 !

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

More to come…