Dynamic Documents for R using R Markdown

Manuel Oviedo de la Fuente
 Alt Text Alt Text1

Ferrol, 26 October 2017

1. Introduction to R Markdown

R Markdown

R Markdown is a format for writing reproducible, dynamic reports with R.

Use it to embed R code and results into slideshows, pdfs, html documents, Word files and more.

An R Markdown (.Rmd) file is a record of your research. It contains the code that a scientist needs to reproduce your work along with the narration that a reader needs to understand your work.

To make a report:

  1. Open - Open a file that uses the .Rmd extension.
  2. Write - Write content with the easy to use R Markdown syntax
  3. Embed - Embed R code that creates output to include in the report
  4. Render - Replace R code with its output and transform the report into a slideshow, pdf, html or ms Word file.

It happened everyday

  1. Data preparation
  2. Modeling
  3. Generating report
  4. Something wrong in your data
  5. Repeat 1 ~ 4

What is R Markdown?

What is R Markdown? from RStudio, Inc. on Vimeo.

R Markdown

A convenient tool to generate reproducible document.

R Markdown

You can automatically update an R Markdown document whenever your data or R code changes, which creates one of the most reproducible - and efficient - workflows possible. You can use R Markdown to create attractive, fully customizable, HTML, PDF, and MS Word documents as well as Beamer slides.

Visit rmarkdown.rstudio.com to get started using R markdown right away. The site provides a quick tour of the R markdown syntax, as well as in depth articles and examples.

Installing R Markdown

2. Open R markdown File

Open R markdown File

Start by saving a text file with the extension .Rmd, or open an RStudio Rmd template

  1. In the menu bar, click: File -> New File -> R Markdown\(\cdots\)

Open File

  1. A window will open. Select the class of output you would like to make with your .Rmd file.
  2. Select the specific type of output to make with the radio buttons (you can change this later) and click OK.

Input (.Rmd File) and output (HTML, pdf)

Left: You write the reports inserting R code.

Right: A final document that replaces the R code with its results.

3. Markdown syntax

Markdown

Next, write your report in plain text.

Use markdown syntax to describe how to format text in the final report.

See Markdown Quick Reference in RStudio and R markdown cheatsheet, Spanish 2015

R markdown cheatsheet, English 2016

Markdown Quick Reference

Rmarkdown font size and header

Create your style .css file

body{
  font-family: Helvetica;
  font-size: 14pt;
  
}
/* Headers */
h1,h2,h3,h4,h5,h6{
  font-size: 24pt;
}
h1.title {
  font-size: 38px;
  color: DarkRed;
}

highlight text and Strikethrough

Lists

Unordered List:

* Item 1
* Item 2
    + Item 2a
    - Item 2b


Ordered List:

1. Item 1
2. Item 2
3. Item 3
    + Item 3a
    + Item 3b





Unordered List:

Ordered List:

  1. Item 1
  2. Item 2
  3. Item 3
    • Item 3a
    • Item 3b

Lists: The Four-space Rule

Subsequent paragraphs must be preceded by a blank line and indented four spaces or a tab.

* fruits

    delicious!!!
    + apples
        - macintosh
        - red delicious
    + pears
    + peaches

* vegetables  
  healthy!!!
    + broccoli
    + chard


Syntax: Image

The below examples produce the same output:

Logo ![Sgapeio](http://www.sgapeio.es/templates/smartinblack/images/logo.png)

Logo Sgapeio

and also with <img src="http://www.sgapeio.es/templates/smartinblack/images/logo.png" width="300"/>

and also with

Gif example GIF animate

[GIF animate](http://slides.yihui.name/gif/car-transform.gif)

Markdown syntax


```
# Header 1
## Header 2
> block quote
```

# Header 1
## Header 2

block quote

ioslides syntax

# section

## slide 1

---

##  Example: create a new slide | with a subtitle

Example: create a new slide | with a subtitle

Plain Code Blocks

Plain code blocks are displayed in a fixed-width font but not evaulated.

This text is displayed verbatim / preformatted

Specify the language of the block is avaliable

x = rnorm(10)  #R code

Equation

+Display equation: $$ equation $$

Tables

First Header  | Second Header
------------- | -------------
Content Cell  | Content Cell
Content Cell  | Content Cell

Set results=‘asis’ to write raw results from R into the output document

Text Color

You can color content using base color classes red, blue, green, yellow, and gray (or variations of them e.g. red2, red3, blue2, blue3, etc.).

<div class="blue2">
This text is blue
</div>

This text is blue

This text is red3

This text is blue

This text is red

Two-column

Note that the content will flow across the columns.

<div class="columns-2"> </div>

Image

Bibliography

Baumer cited [@baumer2014r].
Baumer cited without author [-@baumer2014r].
@baumer2014r cited in line.

Baumer cited (Baumer et al. 2014).

Baumer cited without author (2014).

Baumer et al. (2014) cited in line.

4. Choose Output

YAML Metadata

Write a YAML header that explains what type of document to build from your R Markdown file.

A YAML header is a set of key: value pairs at the start of your file. Begin and end the header with a line of three dashes (- - -)

The RStudio template writes the YAML header for you.

YAML Metadata

The output value determines which type of file R will build from your .Rmd file.

Output value type of file
output: html_document html file (web page)
output: pdf_document pdf document
output: word_document Microsoft Word .docx
output: beamer_presentation beamer slideshow (pdf)
output: ioslides_presentation ioslides slideshow (html)

YAML document options

5. Embed Code

knitr syntax

Use knitr syntax to embed R code into your report. R will run the code and include the results when you render your report.

Two plus two equals 'r 2+2'.
Two plus two equals 4.

Display options I

Use knitr options to style the output of a chunk.

```{r plot,eval=FALSE}
dim(iris)
```
```{r plot,echo=TRUE}
dim(iris)
```
dim(iris)
## [1] 150   5

Display options II

Option Defalul Effect
eval TRUE Whether to evaluate the code and include its results
echo TRUE Whether to display code along with its results
warning TRUE Whether to display warnings
error FALSE Whether to display errors
message TRUE Whether to display messages
tidy FALSE Whether to reformat code in a tidy way when displaying it
results “markup” “markup”, “asis”, “hold”, or “hide”
cache FALSE Whether to cache results for future renders
comment “##” Comment character to preface results with
fig.width 7 Width in inches for plots created in chunk
fig.height 7 Height in inches for plots created in chunk

Table Output: ktable

```
{r, results='asis'}
    knitr::kable(iris[1:4,])
    ```

```{r results=‘asis’, echo=FALSE}

Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3.0 1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
ver con starga zer
Table with stargazer
Statistic N Mean St. Dev. Min Max
Sepal.Length 4 4.825 0.222 4.600 5.100
Sepal.Width 4 3.200 0.216 3.000 3.500
Petal.Length 4 1.400 0.082 1.300 1.500
Petal.Width 4 0.200 0.000 0.200 0.200

Table Output: xtable

```{r, results='asis'}
    print(xtable::xtable(iris[1:4,]), 
          type="html", 
          include.rownames=FALSE)
    ```
    
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.10 3.50 1.40 0.20 setosa
4.90 3.00 1.40 0.20 setosa
4.70 3.20 1.30 0.20 setosa
4.60 3.10 1.50 0.20 setosa

6. Output Format

Rendering Output

Use your .Rmd file as a blueprint to build a finished report. Render your report in one of two ways:

  1. RStudio: “Knit” command (Ctrl+Shif+K)
  2. Command line: rmarkdown::render function
rmarkdown::render("file Rmd path")
#rmarkdown::render("miEjemplo.Rmd")

Rendering Output

When you render, R will

7. Interactive Docs

leaflet package

Use the leaflet map below to explore the Facultade de Humanidades e Documentacion.

leaflet() %>%
  setView(lng=-8.2237333, lat=43.4822354, zoom = 16) %>% 
  addTiles() %>%
  addMarkers(lng=-8.2237333, lat=43.4822354, popup="Facultade de Humanidades e Documentación") 

An R interface to the DataTables library

library(DT)
datatable(iris, options = list(
  searching = FALSE,
  pageLength = 5,
  lengthMenu = c(5, 10, 15, 20)
))

Cont’d DT package

Cont’d DT package

# global search
datatable(iris, options = list(searchHighlight = TRUE, search = list(search = 'setosa')))

Shiny tool

Turn your report sidor01.Rmd into an interactive Shiny document sidor02.Rmd in 3 steps:

  1. Add runtime:shiny to the YAML header.

  2. In the code chunks, add Shiny input functions to embed widgets. Add Shiny render functions to embed reactive output.

  3. Render with rmarkdown::run or click Run Document in RStudio.

See shiny tutorial (in Spanish) for more information about shiny apps.

Shiny example

  1. Clasificación del consumo energético utilizando datos climatológicos: https://manueloviedo.shinyapps.io/classifDD
  2.  Detección de curvas de precio y energía eléctrica atípicas: https://manueloviedo.shinyapps.io/omel
  3.  Predicción del Gas Liquado utilizando Series de Tiempo: https://manueloviedo.shinyapps.io/markdown/aa.Rmd
  4.  Predicción de la Gripe en Cataluña utilizando Datos Funcionales: https://manueloviedo.shinyapps.io/gripRS
  5.  Probabilidades de transición para un modelo de enfermedad-muerte: https://sidor.shinyapps.io/TPidm/

8. Publish

Share outputs

There are several ways to publish the output document on the web.

Compile from R console

library(rmarkdown)
render('slidy01sgapeio.Rmd')

Bibliography

Baumer, Ben, Mine Cetinkaya-Rundel, Andrew Bray, Linda Loi, and Nicholas J Horton. 2014. “R Markdown: Integrating a Reproducible Analysis Tool into Introductory Statistics.” ArXiv Preprint ArXiv:1402.1894.