Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Motivation
Last term I taught Data Analysis at UNAB and I had to find a way to combine slides and R code.
Problem
You can write but you can’t run R code from TeXShop or other editor. LaTeX Beamer is a good option but it has that big flaw. In addition, some of my students used to study from their tablets and smartphones and they complained about missing characters when reading pdf presentations.
Solution
R Markdown allows you to create Rmd documents where you can write text and add both LaTeX and R code with html or pdf output. You can also embed Google Fonts to your presentation and missing characters won’t be an issue anymore.
Building a document/presentation
In RStudio is quite easy and with 2-3 clicks you are ready to go but here I’m presenting some additional steps that will do the magic.
Basic Steps
Create a new document, edit the content and you are ready to go. The first time you do this RStudio will ask you to download some libraries.
After you create your document the first lines are like these:
--- title: "DOCUMENT" author: "Pachamaltese" date: "December 2, 2015" output: html_document ---
To insert LaTeX equations just use \( (e.g. $a+b$
=\)a+b$) and to insert R code click “chunks”
R Markdown chunks contain options
eval = TRUE/FALSE
to run (do not run) codeecho = TRUE/FALSE
to display/hide the involved code
Here is an example. I show you the result and the code using eval=FALSE
.
Using echo=TRUE
{r, echo=TRUE} plot(cars)
Results in
plot(cars)
Using echo=FALSE
{r, echo=FALSE} plot(cars)
Results in
To obtain the output click on Knit HTML (or Knit PDF)
What you’ll obtain will be something like this
Adjusting images
Figure width and height can be configured as you wish. For example
{r, echo=FALSE, fig.height=3, fig.width=4} plot(cars)
Creating lightweight documents
If you want your html file to be as light as possible one option is to use vignette_html
. To to that you need to modify the first lines of your Rmd file like this:
--- title: "DOCUMENT" author: "Pachamaltese" output: rmarkdown::html_vignette: ---
Creating customized presentations
I saw a good design from the excellent Regression Models unit on Coursera by Brian Caffo and team. I adapted that design allowing several authors and more customization to produce my course material (the Rmd and style files are available here). To obtain the same result you need to change the first lines of your Rmd file like this:
--- title: "PRESENTATION" author: "AUTHOR 1" hitheme: tomorrow framework: io2012 knit : slidify::knit2slides ---
Further reading
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.