Automatic Reporting with rmarkdown

Carlos Bort & Lluís Ramon

Thursday, February 26, 2015

Motivación


Automatizar

Reproducible

Diferentes formatos

Ejemplo


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



Slide copiada de Mansun Kuo

Conceptos


Requisitos


Versiones de R y RStudio actualitzadas:

Los siguientes packages de R:

Una distribución de TeX

Ejercicio 1: Generar el primer documento


Markdown basics


# Nivel 1 
## Nivel 2
### Nivel 3

*cursiva*   **negrita**
_cursiva_   __negrita__

[link](https://rugbcn.wordpress.com/)

* lista de elementos
* elemento 2
 + elemento 2.1
 + elemento 2.2
* elemento 3

Formulas en formato LaTeX van entre dolares $\beta^2$

<!-- Comentario en Markdown basics -->


Document Templates


Ejercicio 2: Customizar el documento


Opciones de las templates


Corrector ortográfico


Knitr

Que és?

Que és un chunk?

paste("Mi primer chunk, empecemos por un simple paste!")
## [1] "Mi primer chunk, empecemos por un simple paste!"

Que és un chunk?

```{r, fig.height=4}
library(ggplot2)
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(color = Species))
p + ggtitle("In R we trust!")
```

Que és un chunk?

```{r, fig.height=4}
library(ggplot2)
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(color = Species))
p + ggtitle("In R we trust!")
```

Chunk/Text results

```{r}
paste("echo TRUE, vemos el código.")
```
paste("echo TRUE, vemos el código.")
## [1] "echo TRUE, vemos el código."
```{r,echo=FALSE}
library(knitr)
paste("echo FALSE, lo usaremos casi por defecto..")
rnorm(10)
```
## Warning: package 'knitr' was built under R version 3.1.2
## [1] "echo FALSE, lo usaremos casi por defecto.."
##  [1] -2.1854254  0.5594786 -0.6497459 -0.6926171  2.2025353  0.7534530
##  [7] -0.7200593 -1.8460778 -0.7172342 -1.5024214
```{r,echo=FALSE,results='asis'}
paste("Results as is, tal cual.")
```

[1] “Results as is, tal cual.”

cat("<h2>Html Code all night long</h2>")

Html Code all night long

```{r,echo=FALSE,results='hide'}
paste("No muestres ningún resultado.")
```

Chunk/Evaluation

Eval<-TRUE
```{r,eval=Eval}
paste(Eval)
```
paste(Eval)
## [1] "TRUE"

Chunk/Plot

```{r, echo=FALSE,fig.height=2,fig.width = 3,fig.align='left',dpi=100}
library(ggplot2);library(knitr)
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(color = Species))
p + ggtitle("In R we trust!")
```

Chunk/Code decoration

```{r, echo=FALSE}
summary(cars)
```
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00
```{r, echo=FALSE,comment=""}
summary(cars)
```
     speed           dist       
 Min.   : 4.0   Min.   :  2.00  
 1st Qu.:12.0   1st Qu.: 26.00  
 Median :15.0   Median : 36.00  
 Mean   :15.4   Mean   : 42.98  
 3rd Qu.:19.0   3rd Qu.: 56.00  
 Max.   :25.0   Max.   :120.00  
```{all-code, ref.label=all_labels(), echo=TRUE, eval=FALSE,tidy=TRUE}
```

Chunk/Cache

Chunk/Global options

library(knitr)

opts_chunk$set(echo = FALSE)
opts_chunk$get()
## $eval
## [1] TRUE
## 
## $echo
## [1] TRUE
## 
## $results
## [1] "markup"
## 
## $tidy
## [1] FALSE
## 
## $tidy.opts
## NULL
## 
## $collapse
## [1] FALSE
## 
## $prompt
## [1] FALSE
## 
## $comment
## [1] "##"
## 
## $highlight
## [1] TRUE
## 
## $strip.white
## [1] TRUE
## 
## $size
## [1] "normalsize"
## 
## $background
## [1] "#F7F7F7"
## 
## $cache
## [1] FALSE
## 
## $cache.path
## [1] "Presentacio_cache/slidy/"
## 
## $cache.vars
## NULL
## 
## $cache.lazy
## [1] TRUE
## 
## $dependson
## NULL
## 
## $autodep
## [1] FALSE
## 
## $fig.keep
## [1] "high"
## 
## $fig.show
## [1] "asis"
## 
## $fig.align
## [1] "default"
## 
## $fig.path
## [1] "Presentacio_files/figure-slidy/"
## 
## $dev
## [1] "png"
## 
## $dev.args
## NULL
## 
## $dpi
## [1] 96
## 
## $fig.ext
## NULL
## 
## $fig.width
## [1] 8
## 
## $fig.height
## [1] 6
## 
## $fig.env
## [1] "figure"
## 
## $fig.cap
## NULL
## 
## $fig.scap
## NULL
## 
## $fig.lp
## [1] "fig:"
## 
## $fig.subcap
## NULL
## 
## $fig.pos
## [1] ""
## 
## $out.width
## NULL
## 
## $out.height
## NULL
## 
## $out.extra
## NULL
## 
## $fig.retina
## [1] 2
## 
## $external
## [1] TRUE
## 
## $sanitize
## [1] FALSE
## 
## $interval
## [1] 1
## 
## $aniopts
## [1] "controls,loop"
## 
## $warning
## [1] TRUE
## 
## $error
## [1] FALSE
## 
## $message
## [1] TRUE
## 
## $render
## NULL
## 
## $ref.label
## NULL
## 
## $child
## NULL
## 
## $engine
## [1] "R"
## 
## $split
## [1] FALSE
## 
## $include
## [1] TRUE
## 
## $purl
## [1] TRUE

Ejemplo: rCharts

```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
  data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
  data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)

Worth a look


Recopilación de más de 114 ejemplos.

Recomendación para el trabajo:

Ejercicio 3: Usar diferentes chunks


Presentation Templates


Funciona igual que los documentos

Añadir codigo html directamente


<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2992.980538837
813!2d2.1940529999999994!3d41.396229!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x12a4a2c
2e2d59ceb%3A0xc4a659466688fe8d!2sitnig!5e0!3m2!1sca!2ses!4v1425493445609" 
width="600" height="450" frameborder="0" style="border:0"></iframe>

Añadir codigo html desde R


```{r, warning = FALSE}
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeath)
```

Mejorando el aspecto de las tablas


Usar chunk option result = 'asis'.

Ejemplo con xtable


library(xtable)
xIris <- xtable(head(iris), caption = "5 primeros valores de iris")
print.xtable(xIris, type = "html")
## <!-- html table generated in R 3.1.1 by xtable 1.7-4 package -->
## <!-- Mon Mar  9 00:04:16 2015 -->
## <table border=1>
## <caption align="bottom"> 5 primeros valores de iris </caption>
## <tr> <th>  </th> <th> Sepal.Length </th> <th> Sepal.Width </th> <th> Petal.Length </th> <th> Petal.Width </th> <th> Species </th>  </tr>
##   <tr> <td align="right"> 1 </td> <td align="right"> 5.10 </td> <td align="right"> 3.50 </td> <td align="right"> 1.40 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 2 </td> <td align="right"> 4.90 </td> <td align="right"> 3.00 </td> <td align="right"> 1.40 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 3 </td> <td align="right"> 4.70 </td> <td align="right"> 3.20 </td> <td align="right"> 1.30 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 4 </td> <td align="right"> 4.60 </td> <td align="right"> 3.10 </td> <td align="right"> 1.50 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 5 </td> <td align="right"> 5.00 </td> <td align="right"> 3.60 </td> <td align="right"> 1.40 </td> <td align="right"> 0.20 </td> <td> setosa </td> </tr>
##   <tr> <td align="right"> 6 </td> <td align="right"> 5.40 </td> <td align="right"> 3.90 </td> <td align="right"> 1.70 </td> <td align="right"> 0.40 </td> <td> setosa </td> </tr>
##    </table>

Añadiendo el chunk option result = 'asis'

library(xtable)
xIris <- xtable(head(iris), caption = "5 primeros valores de iris")
print.xtable(xIris, type = "html")
5 primeros valores de iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.10 3.50 1.40 0.20 setosa
2 4.90 3.00 1.40 0.20 setosa
3 4.70 3.20 1.30 0.20 setosa
4 4.60 3.10 1.50 0.20 setosa
5 5.00 3.60 1.40 0.20 setosa
6 5.40 3.90 1.70 0.40 setosa

Adaptar la salida del chunk


Ejemplo knit_print


head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
library(knitr)
library(printr) # De github https://github.com/yihui/printr
head(iris)
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
5.0 3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa

Añadiendo opciones de LaTeX


---
title: "Primer documento rmarkdown"
author: "Lluís Ramon"
date: "Wednesday, March 04, 2015"
output: pdf_document
header-includes:
- \usepackage{fancyhdr}
- \fancyfoot[CO,CE]{\em pàg. \thepage}
- \fancyhead[LE,LO]{\em \thetitle}
- \rfoot{\includegraphics[width = 3cm]{upc}}
---

Usar otras templates


templates

Crear tu propia template


Ejemplo upcTemplate


.Rnw/LaTeX

.Rnw/Creación Documento

Recordar, Tools / Global Options:

.Rnw/Estructuración Documento

.Rnw/Cómo funciona

.Rnw/Chunk


<>=
rnorm(10)
@

Ejercicio 4: Crear un Rnw


OR

.Rnw/Tipo output

  1.  \documentclass[12pt]{article}
  2.  \documentclass{beamer}

Más información en: http://en.wikibooks.org/wiki/LaTeX/Presentations

.Rnw/Tips

 \usepackage[utf8x]{inputenc}
 \usepackage[cp1252]{inputenc}

.Rnw vs .Rmd

Markdown or LaTeX?

.Rnw/Ejemplos Ejemplos Ejemplos


https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

https://github.com/yihui/knitr-examples

.Rnw/En caso de duda…

Thank you


Lluís Ramon

@LluisR_Tgn

@LluisRamon

lluisramon


Carlos Bort

@Carlosebort

@carlosbort

carlosbort