R-Markdown and Knitr Tutorial (Part 1)
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
-
We’ll use R-Studio to create our R-Markdown document. You can download it here -> http://www.rstudio.com/products/rstudio/download/
-
Next we’ll install a few packages just to ensure we have everything we need to get 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), IBM = round(IBM$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 !
Further reading
Please refer to the following resources for more details
– R-Markdown cheatsheet
– Plotly R Library
– Knitr
More to come…
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.