This page contains the notes for the first part of R Workshop Module 6: “To Infinity and Beyond”, which is part of the R Workshop series prepared by ICJIA Research Analyst Bobae Kang to enable and encourage ICJIA researchers to take advantage of R, a statistical programming language that is one of the most powerful modern research tools.
Click here to go to the workshop home page.
Click here to go to the workshop Modules page.
Click here to view the accompanying slides for Module 6, Part 1.
Navigate to the other workshop materials:
After learning how to use R to analyze data and get results, now is the time for us to explore various options to share our work effectively and elegantly.
Source: R Markdown
“R Markdown is a file format for making dynamic documents with R. An R Markdown document is written in markdown (an easy-to-write plain text format) and contains chunks of embedded R code.”
- Garret Grolemund from R Studio
R Markdown supports a variety of document formats and makes it easy to create amazing reports, presentation slides, or even websites to share your findings in R with others.
There are many benefits of using R Markdown.
First, it is a great way to incorporate your R code into a document. It not only shows your code to make it transparent, but also runs it as the document is rendered so that the resulting output is always true to the code. This is particularly useful when the code is used to compute certain key values or create tables/plots using data.
Second, R Markdown makes it easy to generate various formats of documents for the same contents–an HTML document, a PDF report, presentation slides, etc.–with little to no changes to the R Markdown script.
R Markdown’s ability to incorporate R code makes the rendered document and its content largely reproducible. If the data changes and we have to compute certain values again, we simply re-render the document using the modified data.
Finally, the report generating process can be largely automated with rmarkdown
tools.
To get started with R Markdown, we first have to install rmakrdown
package. If you are using RStudio IDE (which you should), this is already taken care of.
Creating a new R Markdown file is easily done using RStudio IDE. Go to its menu bar, and click File > New File > R Markdown.
Onces we have our R Markdown file ready to be rendered, we “Knit” the R Markdown file into a document in the desired format.
The following screenshots show how this is done:
On the RStuido IDE menu, click “File > New File > R Markdown”.
Alternatively, you can click a button right below File menu, which is for creating a new file. When you clikc the button, you will see various options for a new file. Click “R Markdown”.
When you click “R Markdown”, you will see a small window for specifying a few options, including “Title”, “Author”, and “Default Output format”.
Onces you click “OK”, a new R Markdown script shows up on the script pane of RStudio IDE. Now we are ready to work on our R Markdown file!
An R Markdown file starts with a YAML header, which specifies options for rendering the output document. In the following picture, the part in the red box is a YAML header, enclosed by three dashes (---
) on the top and bottom.
Basic YAML header options include the title, author, and date of the document as well as the output specifications (output format and related options). We will take a closer look at the output options below.
RStudio IDE offers a button for “knitting” the R Markdown file into documents of specified formats. Next to the “Knit” button is a button with options for previews.
Clickling the “Knit” button will simply knit the document. On the other hand, clicking a small down-arrow button will show some options for knitting the document.
Clikcing the cogwheel icon next to “Knit” button presents optiosn for preview.
The main body of the R Markdown file is a markdown script.
We will take a quick tour of markdown basics. More specifically, we will see the markdown syntax for the following elements:
# Header 1
## Header 2
### Header 3
_italic_ __bold__
*italic* **bold**
~~strikethrough~~
superscript^2^
Unordered list | Ordered list
|
* Item 1 | 1. Item 1
* Item 1a | 1. Item 1a
* Item 2 | 2. Item 2
+ Item 2a | 1. Item 2a
- Item 2b | 2. Item 2b
Mixed list
1. Item 1
* Item 1a
* Item 2
1. Item 2a
+ Item 2b
[text with hyperlink](http://link.path)


> A line of text following the "> " is a blockquote.
A line of text following the “>” is a blockquote.
More then three asteriks or dashs
***
******
------
Inline math equations look like: $y = (x + 1)^2$
Inline math equations look like: \(y = (x + 1)^2\)
A block of math equations look like:
$$y = x^2 + 2x + 1$$
A block of math equations look like: \[y = x^2 + 2x + 1\]
The highlighted part in the markdown body is an R code chunk. Each code chunk can have R code that will be executed when knitting the whole document.
Inserting a new code chunk can be done with clicking the “Insert” button on the right top of the script pane. Alternatively, we can used a keyboard shortcut: Ctrl + Alt + i
.
Click the “Run” button to see options for executing R code chunks. Also, we can execute each code chunk separately with the green play button on the right top of the code chunk. Alternatively, we can use a keyboard shortcut: Ctrl + Enter
.
knitr
package offers various options to control the knitted output of code chunks. There are global options and local options.
# use the following to control global options
knitr::opts_chunk$set(eval = TRUE, echo = TRUE, ...)
Global options act as the default settings for the whole document. This can be specified using opts_chunk$set()
function
_```{r eval = FALSE, echo = FALSE, ...}
Local options per code chunk are only applied to the specific code chunck. They can specified in the curly braces {}
at the beginning of the code chunk. Local options overide the global options if relevant.
See here for full documentation of knitr
chunk options.
The following table lists commonly used code chunk options and their descriptions.
Option (default) | Description |
---|---|
eval (TRUE ) |
Evaluate code in chunk? If FALSE, only code is shown |
echo (TRUE ) |
Show code in chunk? If FALSe, only output is shown |
error (FALSE ) |
Preserve the error? If TRUE, knitting continues in case of errors |
message (TRUE ) |
Display code messages? |
warning (TRUE ) |
Display code warnings? |
include (TRUE ) |
Include the code chunk? If FALSE, neither code nor output is shown but code is still evaluated |
fig.show (asis ) |
How to show/arrange plots? ("asis" , "hold" , "animate" , "hide" ) |
fig.width , fig.height (7 ) |
Plot width and height in inches. |
There are often cases where we want to generate a table using R code and include it in the R Markdown output. There are different options for printing a table:
knitr::kable()
DT::datatable()
my_table <- data.frame(
my_fruits = c("apple", "banana", "clementine"),
my_animals = c("dogs", "cats", "llamas"),
my_flavors = c("chocolate", "vanila", "cookie dough"),
my_colors = c("red", "green", "orange"),
my_cities = c("Chicago", "New Work", "Los Angeles")
)
my_table
## my_fruits my_animals my_flavors my_colors my_cities
## 1 apple dogs chocolate red Chicago
## 2 banana cats vanila green New Work
## 3 clementine llamas cookie dough orange Los Angeles
kable
exampleknitr::kable(my_table)
my_fruits | my_animals | my_flavors | my_colors | my_cities |
---|---|---|---|---|
apple | dogs | chocolate | red | Chicago |
banana | cats | vanila | green | New Work |
clementine | llamas | cookie dough | orange | Los Angeles |
datatable
exampleDT::datatable(my_table)
Source: Wikimedia Commons
R Markdown supports various output formats, including HTML, PDF, Microsoft Word, and more.
Output format can be specified using output
in the YAML header. R Markdown is not limited to generate a single format for the given file. In order words, depending on the YAML output
setting, the same file can be rendered in multiple formats.
Different output format has different YAML render options. Refer the page 2 of R Markdown cheat sheet on RStudio’s Cheat Sheets page for a full list.
The following table lists common output formats on YAML header and what they create.
output value |
Creates |
---|---|
html_document |
HTML file |
html_notebook |
R Notebook HTML file |
pdf_document |
PDF (requires Tex) file |
word_document |
Microsoft Word file |
md_document |
Markdown file |
github_document |
GitHub compatible markdown file |
The following table lists commonly used YAML render options and their descriptions as well as availability.
Option | Description | Available for |
---|---|---|
css |
CSS file to use to style document | html |
highlight |
Syntax highlighting | html, pdf, word |
number_sections |
Add section numbering to headers | html, pdf |
theme |
Bootswatch theme to use for page | html |
toc |
Add a table of contents | html, pdf, word, md, github |
toc_depth |
The lowest level of headings in toc | html, pdf, word, md, github |
toc_float |
Float the toc on the left | html |
Available highlights for R Markdown documents are as follows: "default"
, "tango"
, "pygments"
, "kate"
, "monochrome"
, "espresso"
, "zenburn"
, "haddock"
, and "textmate"
Available themes for R Markdown documents are as follows: "default"
, "cerulean"
, "journal"
, "flatly"
, "readable"
, "spacelab"
, "united"
, "cosmo"
, "lumen"
, "paper"
, "sandstone"
, "simplex"
, and "yeti"
. R Markdown themes are in fact drawn from “Bootswatch” themes, so you can visit the website to get a feel for each theme for your own R Markdown document.
“An R Notebook is an R Markdown document with chunks that can be executed independently and interactively, with output visible immediately beneath the input.”
- “R Notebooks”, RStudio
While all other R Markdown formats requires “knitting” to see the final output, an R notebook document is automatically re-rendered each time the source file (.Rmd
) is saved. This offers a more interactive workflow.
htmlwidgets
for Rhtmlwidgets
include:
plotly
and highcharter
for interactive visualizationsleaflet
for interactive mapsDT
for interactive data tableshtmlwidgets
for R website to find out more“RPubs is a quick and easy way to disseminate data analysis and R code and do ad-hoc collaboration with peers.”
- RStudio Team
Publishing an R Markdown output on RPubs is as easy as clicking the “publish” button on RStudio. You may consider RPubs as something comparable to Tableau Public’s Gallery website, although there are some differences.
Click the image below to view what others have shared:
Source: Wikimedia Commons
RStudio supports many options for creating presentation slides that are both modern-looking and highly customizable.
Popular ways to create slides using R include:
ioslides_presentation
(HTML)revealjs::revealjs_presentation
(HTML)slidy_presentation
(HTML)beamer_presentation
(PDF)ioslides
---
title: "My first ioslide presentation"
output: ioslides_presentation
---
ioslides
output format is built into RStudio. ioslides
fully integrates R Markdown syntax. For example, creating new slides is as easy as using #
and ##
headings.
To learn more about ioslides
, read the “Presentations with ioslides” article on RStudio.
ioslides
sample source codeHere is a sample course code for creating simple ioslides
HTML slides. The result will have a title slide with the information in YAML header.
---
title: "My first ioslide presentation"
author: Bobae Kang
date: April 18, 2018
output: ioslides_presentation
---
# First section
## Normal slide
- Item one
- Item two
## Another slide | With a subtitle
This slide has a two-column layout
----

The following is my own sample ioslides
presentation slides:
revealjs
---
title: "My first revealjs presentation"
output: revealjs::revealjs_presentation
---
With revealjs
R package, it is possible to use R Markdown (and its syntax) to generate slides using reveal.js, a JavaScript library for interactive slides in HTML. Try this demo slides generated using reveal.js to see how its slides look like.
Creating slides with revealjs
is mostly the same as using ioslides
, except for certain options that are available only with revealjs
. To learn more about revealjs
, read the “Presentations with reveal.js” article on RStudio.
The following is my own sample reveal.js
presentation slides:
There are more options for creating presentation slides via R Markdown, including the following:
slidy
output: slidy_presentation
in the YAML headerbeamer
output: beamer_presentation
xaringan
output: xaringan::moon_reader
R Presentation is another file format for an interactive HTML slides that are built on amazing reveal.js. All Workshop slides are generated using R Presentation with some customizing work.
Unlike what we have seen abvoe, R Presentation is not a R Markdown document and has its own file extension (.RPres
). Similar to R Notebook, R Presentation offers an interactive “Preview” which gets automatically re-rendered each time the source file (.RPres
) is saved. This can support a more interactive workflow for creating slides.
Unfortunately, R Presentation is no longer in active development.
To learn more about R Presentation, visit relevant pages on RStudio Support website.
Source: R Studio
“Shiny is an open source R package that provides an elegant and powerful web framework for building web applications using R. Shiny helps you turn your analyses into interactive web applications without requiring HTML, CSS, or JavaScript knowledge.”
- RStudio.com
To get a feel for what Shiny is capable of, try my ICJIA Uniform Crime Report Data dashboard app here.
Also, check out more examples on RStudio’s “Shiny User Showcase” page.
Shiny opens up a whole new world of opportunities. Two common “applications” of Shiny include building dashboards and generating interactive documents.
A data dashboard is a visual interface to data to allow its viewers for gain key insights. It is often an interactive application that provides viewers with options to explore data from multiple angles interactively. A Shiny application is perfectly capable of making a great dashboard.
Shiny can be used to generate interactive documents with Shiny app widgets embedded. An interactive document can be created by knitting an R Markdown file with the YAML head including runtime: shiny
and output: html_document
or output: ioslids_presentation
. Embedded Shiny R code chunks will render a mini application, which can offer your readers yet another way to gain insights from your work.
The following figure offers a visual illustration of the structure of an interactive document powered by Shiny.
Source: “Introduction to interactive documents”. Shiny from R Studio
install.pacakges("shiny")
library(shiny)
runExample("01_hello")
Shiny is a package, so you first have to install and import it. Once the package is imported to your R environment, try a simple built-in example for Shiny application!
A Shiny app consists of two parts, server
and ui
.
They can be separated into two files, server.R
and ui.R
. In this case, both files must be located in the same directory, typically named “app”.
Alternatively, both parts can live in a single file, app.R
.
For interactive documents, the R Markdown document serves as the user interface, so there is no need for a serarate ui
file.
function(input, output, session) {
## R code for server logic
}
server.R
file contains the server-side logic of the application. It contains a function with two required arguments (input
and output
) and one optional argument (session
) to define the server logic.
input
object is an environment for storing user inputs modified by user’s interaction with the application ui
.
output
object is an environment for storing elements (plots, tables, texts, etc) to be rendered and shown in the ui
.
Finally, session
object is an environment that can be used to access information relating to the session. Using session
is optional.
fluidPage(
## R code for user interface
)
ui.R
file defines the user interface elements, such as layouts, panels, inputs and outputs. The file contains fluidPage()
function.
Available layouts include: the sidebar layout and grid layout.
Available panels include: the title panel, sidebar panel, main panel, tabset panel, navigation list panel, and more.
shiny
offers functions to take user inputs and functions to render outputs (as defined in server.R
).
library(shiny)
server <- function(input, output) {
# server-side logic
}
ui <- fluidPage(
# user interface
)
shinyApp(ui, server)
app.R
file must include shinyApp(ui, server)
at the end, where server
is an object containing code for server-side logic and ui
is an object containing user interface elements.
Developing a Shiny app takes much practice, planning and pain experiment. However, the reward is YUGE!
You can get started with Shiny using these tutorials by RStudio. Also, follow along these articles by RStudio to hone your Shiny skills.
If you need examples and inspirations for your own projects, visit Shiny Gallery and check out featured applications and widgets.
Shiny applications, including the interactive documents, can be deployed for use in the following ways:
The easiest way to deploy/publish a Shiny application is via shinyapps.io, RStudio’s cloud hosting service for Shiny application. Using shinyapps.io requires signing up to their service, which can also be done with Google or GitHub account. Onces registered, it takes only a few clicks on the RStudio IDE to deploy an application via shinyapps.io.
While free hosting of Shiny application is available, it is limited to 5 applications and 25 active hours per month. This might be sufficient for quickly sharing demo projects, but not enough for serious applications. See the pricing for hosting Shiny apps on shinyapps.io website for more.
Source: Wikimedia Commons
A collection R Markdown documents in HTML format can be made into a website.
To do so, we need a _site.yml
file in the same folder as individual documents to be put together. _site.yml
specifies the name and the routing structure of the resulting website.
With _site.yml
and all HTML documents ready, run rstudio::render_site()
to generate the website.
For details, see the “R Markdown Websites” article on RStudio website.
The following is a _site.yml format example. This is in fact the actual YAML file for the R Workshop website, which can be found here.
name: ICJIA R Workshop
output_dir: '.'
navbar:
title: ICJIA R WORKSHOP
right:
- text: Home
href: index.html
- text: Modules
href: modules.html
- text: About
href: about.html
output:
html_document:
includes:
after_body: include_footer.html
css: css/style.css
lib_dir: site_libs
self_contained: no
“GitHub Pages is a static site hosting service designed to host your personal, organization, or project pages directly from a GitHub repository.”
-“What is GitHub Pages?”, GitHub Help
GitHub is a free and commercial online repository service for storing and sharing projects using Git.
The ICJIA R Workshop website is hosted on GitHub Pages. (Please not that the ICJIA network currently blocks all websites hosted on GitHub Pages.)
Read more about GitHub Pages and hosting static sites on GitHub Pages on GitHub Help here.
blogdown
bookdown
package, built on R Markdown, facilitates writing books and long articles/reports. A bookdown
publication is made downloadable in PDF, EPUB and MOBI formats, making it more like a real electronic “book” than just an online documentation website.
Check out bookdown
package website to find out more.
Also, read Xie, Y. (2018). bookdown
: Authoring Books and Technical Documents with R Markdown for a comprehensive guide for bookdown
. The book itself is generated using bookdown
.
blogdown
blogdown
is a package to generate static websites using R Markdown and the Hugo, a popular open-source static website generator.
You can visit Awesome Blogdown website for a curated list of blogdown
examples.
Also, read Xie, Y. et al. (2018). blogdown
: Creating Websites with R Markdown for a comprehensive guide for blogdown
.
The following are examples of blogs/websites built using blogdown
: