class: title-slide, center, middle <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #ffffffcc;"></i> <strong class="fa-stack-1x" style="color:#e7553c;">01</strong> </span> # R Markdown Basics ## Young Statisticians Conference 2019 ### Alison Hill · RStudio #### [https://ysc-rmarkdown.netlify.com/](https://ysc-rmarkdown.netlify.com/) --- class: middle, center .pull-left[ # <i class="fas fa-wifi"></i> Wifi network name Functions ] .pull-left[ # <i class="fas fa-key"></i> Wifi password Stata_16 ] --- class: middle, center # <i class="fas fa-cloud"></i> # Go here and log in (free): [http://bit.ly/ysc-rmarkdown](http://bit.ly/ysc-rmarkdown) --- class: middle, center | Time | Activity | |:--------------|:--------------------------------------------------------------| | 09:00 - 10:30 | Session 1 (R Markdown Basics) | | 10:30 - 11:00 | *Break* ☕ | | 11:00 - 12:30 | Session 2 (Advanced R Markdown) | | 12:30 - 01:30 | *Lunch* 🍱 | | 01:30 - 03:00 | Session 3 (Templates) | | 03:00 - 03:30 | *Break* 🍵 | | 03:30 - 05:00 | Session 4 (Collections) | --- layout: true <div class="my-footer"><span>https://ysc-rmarkdown.netlify.com/</span></div> --- background-image: url(images/hello-red.jpg) background-position: top center background-size: 100% class: middle, center .pull-left[ ### Alison Hill [<i class="fab fa-github"></i> @apreshill](https://github.com/apreshill) [<i class="fab fa-twitter"></i> @apreshill](https://twitter.com/apreshill) ] .pull-right[ ### Emi Tanaka [<i class="fab fa-github"></i> @emitanaka](https://github.com/emitanaka) [<i class="fab fa-twitter"></i> @statsgen](https://twitter.com/statsgen) ] .footnote[All content is CC-BY. All art (unless otherwise noted) is by [Desirée De Leon](https://desiree.rbind.io/), CC-BY-NC-ND.] --- .left-column[ <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #f2e255;"></i> <strong class="fa-stack-1x" style="color: #fff;">?</strong> </span> ] .right-column[ # What is R Markdown? 1. An authoring framework for data science. 1. A document format (`.Rmd`). 1. An R package named `rmarkdown`. 1. A file format for making dynamic documents with R. 1. A tool for integrating prose, code, and results. 1. A computational document. 1. Wizardry. ] --- .left-column[ <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #f2e255"></i> <strong class="fa-stack-1x" style="color: #fff;">?</strong> </span> ] .right-column[ # What is R Markdown? 1. ["An authoring framework for data science."](https://rmarkdown.rstudio.com/lesson-1.html) (✔️) 1. [A document format (`.Rmd`).](https://bookdown.org/yihui/rmarkdown/) (✔️) 1. [An R package named `rmarkdown`.](https://rmarkdown.rstudio.com/docs/) (✔️) 1. ["A file format for making dynamic documents with R."](https://rmarkdown.rstudio.com/articles_intro.html) (✔️) 1. ["A tool for integrating text, code, and results."](https://r4ds.had.co.nz/communicate-intro.html) (✔️) 1. ["A computational document."](http://radar.oreilly.com/2011/07/wolframs-computational-documen.html) (✔️) 1. Wizardry. (🧙♂️) ] --- class: middle, center # Change your mental model .pull-left[ ### Source ↔ output <img src="images/word.png" width="50%" /> ] .pull-right[ ### Source → output <img src="images/rmd-file.png" width="50%" /> ] --- class: middle, center # Change your mental model .pull-left[ ### Source ↔ output <img src="images/haba-elise.jpg" width="50%" /> ] .pull-right[ ### Source → output <img src="images/doll.png" width="50%" /> ] --- background-image: url(images/welliewishers/Slide1.png) background-size: cover class: top, center .footnote[https://www.americangirl.com/shop/c/welliewishers] --- background-image: url(images/welliewishers/Slide2.png) background-size: cover class: top, center .footnote[https://www.americangirl.com/shop/c/welliewishers] --- class: middle, inverse, center # Same ~~doll~~ source # Different occasions --- class: middle, center # `html_document` <img src="images/doll.png" width="40%" /> --- .left-column[ # <i class="fab fa-github"></i> ] .right-column[ # Go here: [https://github.com/ysc2019-workshop/01-basics](https://github.com/ysc2019-workshop/01-basics) Click on "Use this template" (make sure you are logged in) <img src="images/cloud-from-template.png" width="3840" /> ] --- .left-column[ # <i class="fab fa-github"></i> ] .right-column[ # In your repo Click on green button, then the clipboard to copy HTTPS <img src="images/cloud-from-https.png" width="3840" /> ] --- .left-column[ # <i class="fas fa-cloud"></i> ] .right-column[ # Go to rstudio.cloud: [http://bit.ly/ysc-rmarkdown](http://bit.ly/ysc-rmarkdown) 1. Join space > Click on "Projects" (nothing there) 1. New Project from GitHub Repo 1. Use **your** HTTPS link: <img src="images/cloud-from-git.png" width="50%" /> 1. Name your project ] --- .left-column[ # <i class="fas fa-cloud"></i> ] .right-column[ # Last step! I promise! Still in rstudio.cloud: ```r library(usethis) use_git_config( scope = "project", user.name = "Jane", user.email = "jane@example.org" ) ``` ] --- class: your-turn # Your turn Find a partner and look at `01-bakeoff-report.Rmd` together. Look at the source, then 🧶 **Knit** to HTML. Try to identify these parts in the source and the output: 1. The **metadata** 1. The **text** 1. The **code** 1. The **output** **If this was easy**, try to find all code that produces a *plot*.
05
:
00
--- class: live-code # Basic anatomy I We look at the source anatomy for `01-bakeoff-report.Rmd` together: 1. The **metadata** 1. The **text** 1. The **code** --- class: center, middle <img src="images/Knit-to-html.jpg" width="50%" /> --- class: center, middle <img src="images/doc-live.jpg" width="50%" /> --- class: live-code # Basic anatomy II We look at the output anatomy for `01-bakeoff-report.Rmd` together: 1. The **metadata** 1. The **text** 1. The **code** 1. The **output** --- background-image: url(images/rmarkdown_wizards.png) background-size: contain .footnote[Art by [Allison Horst](https://twitter.com/allison_horst?lang=en)] --- class: middle, center # What is inside? ![](images/doc-make.jpg) --- class: middle, center, inverse <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #fff;"></i> <strong class="fa-stack-1x" style="color:#17a2b8;">1 </strong> </span> -- # Metadata --- # metadata: YAML .pull-left[ _"YAML Ain't Markup Language"_ ```yaml --- key: value --- ``` ] .pull-right[ <img src="images/orchestra.jpg" width="75%" style="display: block; margin: auto;" /> ] --- class: middle, center # Output options --- # Save output options in your YAML .pull-left[ ```yaml --- title: The Great British Bake Off output: html_document --- ``` ```yaml --- title: The Great British Bake Off output: html_document: toc: true --- ``` ] .pull-right[ <img src="images/orchestra.jpg" width="75%" style="display: block; margin: auto;" /> ] --- class: your-turn # Your turn ## Add output options to YAML Use `?html_document` from your R console to: 1. Add a floating table of contents 1. Add a theme 🧶 **Knit** to HTML to see the output. **If this was easy**, try to embed the `Rmd` source code to download. _psst...answers on the next slide..._
03
:
00
--- class: your-turn # Answers ```yaml --- title: The Great British Bake Off output: html_document: toc: true toc_float: true theme: flatly code_download: true --- ``` --- # Parameters ```yaml --- title: The Great British Bake Off output: html_document: toc: true toc_float: true theme: flatly code_download: true params: series: '1' --- ``` --- class: your-turn # Your turn .pull-left[ Change this: ```yaml --- title: The Great British Bake Off output: html_document: toc: true toc_float: true theme: flatly code_download: true params: series: '1' --- ``` ] .pull-right[ To this: ```yaml --- title: The Great British Bake Off output: html_document: toc: true toc_float: true theme: flatly code_download: true params: series: '2' --- ``` ] Now click on knit button and pick __"Knit with Parameters."__ How is this different from what you did above?
03
:
00
--- class: inverse, center, middle <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #fff;"></i> <strong class="fa-stack-1x" style="color:#17a2b8;">2 </strong> </span> -- # Text --- # <center>Headers</center> -- .pull-left[ ```markdown # HEADER 1 ## HEADER 2 ### HEADER 3 #### HEADER 4 ##### HEADER 5 ###### HEADER 6 ``` ] -- .pull-right[ # HEADER 1 ## HEADER 2 ### HEADER 3 #### HEADER 4 ##### HEADER 5 ###### HEADER 6 ] --- class: middle, center <img src="images/rmd-nav.png" width="80%" /> --- # <center>Text</center> -- .pull-left[ ```markdown **The Great British Bake Off** (often abbreviated to _Bake Off_ or _GBBO_) is a British television baking competition. ``` ] -- .pull-right[ **The Great British Bake Off** (often abbreviated to _Bake Off_ or _GBBO_) is a British television baking competition. ] --- class: top # <center>Lists</center> -- .pull-left[ ```markdown The original cast included: - Sue Perkins (_host_) - Mel Giedroyc (_host_) - Mary Berry (_judge_) and - Paul Hollywood (_judge_). In each episode, the amateur bakers are given **three challenges** based on that week's theme. 1. a signature bake, 1. a technical challenge, 1. a show-stopper. ``` ] -- .pull-right[ The original cast included: - Sue Perkins (_host_) - Mel Giedroyc (_host_) - Mary Berry (_judge_) and - Paul Hollywood (_judge_). In each episode, the amateur bakers are given **three challenges** based on that week's theme. 1. a signature bake, 1. a technical challenge, 1. a show-stopper. ] --- # <center>Images</center> -- .pull-left[ ```markdown Competitive baking, such as making Victoria sponge (_pictured_), is part of the classic English village fête, which inspired the series. ![](http://bit.ly/blue-ribbon-sponge) ``` ] -- .pull-right[ Competitive baking, such as making Victoria sponge (_pictured_), is part of the classic English village fête, which inspired the series. ![](http://bit.ly/blue-ribbon-sponge) ] --- # <center>Links</center> -- .pull-left[ ```markdown Competitive baking, such as making Victoria sponge (_pictured_), is part of the classic English village fête, which inspired the series. [Photo](https://en.wikipedia.org/) ![](http://bit.ly/blue-ribbon-sponge) ``` ] -- .pull-right[ Competitive baking, such as making Victoria sponge (_pictured_), is part of the classic English village fête, which inspired the series. [Photo](https://en.wikipedia.org/) ![](http://bit.ly/blue-ribbon-sponge) ] --- name: 03-formative class: middle # Pop quiz -- .pull-left[ How do you add headers in Markdown? `! Header` `- Header` `# Header` `1. Header` ] -- .pull-right[ What about lists? Bulleted? Numbered? `! Item 1` `- Item 1` `# Item 1` `1. Item 1` ] --- class: inverse, center, middle <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #fff;"></i> <strong class="fa-stack-1x" style="color:#17a2b8;">3 </strong> </span> -- # <i class="fab fa-r-project"></i> code --- # Code chunks .pull-left[ ```` ```{r} ratings %>% filter(series == 1) %>% top_n(1, viewers_7day) ``` ```` What is the fate of this chunk? ] -- .pull-right[ ```r ratings %>% filter(series == 1) %>% top_n(1, viewers_7day) #> # A tibble: 1 x 8 #> series episode uk_airdate viewers_7day viewers_28day network_rank #> <int> <int> <date> <dbl> <dbl> <int> #> 1 1 5 2010-09-14 3.03 1 NA #> # … with 2 more variables: channels_rank <int>, bbc_iplayer_requests <dbl> ``` ] --- # Code chunks .pull-left[ ```` ```{r} top_viewers <- ratings %>% filter(series == 1) %>% top_n(1, viewers_7day) ``` ```` What fate do you predict here? ] -- .pull-right[ ```r top_viewers <- ratings %>% filter(series == 1) %>% top_n(1, viewers_7day) ``` ] --- # Code chunks .pull-left[ ```` ```{r} top_viewers <- ratings %>% filter(series == 1) %>% top_n(1, viewers_7day) top_viewers ``` ```` ] -- .pull-right[ ```r top_viewers <- ratings %>% filter(series == 1) %>% top_n(1, viewers_7day) top_viewers #> # A tibble: 1 x 8 #> series episode uk_airdate viewers_7day viewers_28day network_rank #> <int> <int> <date> <dbl> <dbl> <int> #> 1 1 5 2010-09-14 3.03 1 NA #> # … with 2 more variables: channels_rank <int>, bbc_iplayer_requests <dbl> ``` ] --- # Code chunks .pull-left[ ```` ```{r} ggplot(viewers, aes(episode, viewers, colour = days, group = days)) + geom_point() + geom_line() + labs(x = "Episode", y = "Viewers (millions)") + expand_limits(y = 0) ``` ```` What about this one? ] -- .pull-right[ ```r ggplot(viewers, aes(episode, viewers, colour = days, group = days)) + geom_point() + geom_line() + labs(x = "Episode", y = "Viewers (millions)") + expand_limits(y = 0) ``` <img src="01-basics_files/figure-html/unnamed-chunk-27-1.png" width="60%" style="display: block; margin: auto;" /> ] --- class: live-code # Adding/running chunks Together we: 1. Add chunks with button or: Command (or Cmd) `⌘` + Option (or Alt) `⌥` + `i` (Mac) Ctrl + Alt + `i` (Windows/Linux) 1. Run chunks by: Run current chunk button (interactive) Knit button / run all chunks --- # Inline code .pull-left[ The top viewed episode in series 1 was episode ``` `r top_viewers %>% pull(episode)` ``` ] -- .pull-right[ The top viewed episode in series 1 was episode 5 ] --- class: inverse, center, middle <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x" style="color: #fff;"></i> <strong class="fa-stack-1x" style="color:#17a2b8;">4 </strong> </span> -- # Output --- # Chunk options .pull-left[ ```` ```{r} glimpse(ratings) ``` ```` ] .pull-right[ ```r glimpse(ratings) #> Observations: 84 #> Variables: 8 #> $ series <int> 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3… #> $ episode <int> 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 1… #> $ uk_airdate <date> 2010-08-17, 2010-08-24, 2010-08-31, 2010-0… #> $ viewers_7day <dbl> 2.24, 3.00, 3.00, 2.60, 3.03, 2.75, 3.10, 3… #> $ viewers_28day <dbl> 7, 3, 2, 4, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1… #> $ network_rank <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… #> $ channels_rank <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… #> $ bbc_iplayer_requests <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… ``` ] --- # echo .pull-left[ ```` ```{r echo=FALSE} glimpse(ratings) ``` ```` ] .pull-right[ ``` #> Observations: 84 #> Variables: 8 #> $ series <int> 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3… #> $ episode <int> 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 1… #> $ uk_airdate <date> 2010-08-17, 2010-08-24, 2010-08-31, 2010-0… #> $ viewers_7day <dbl> 2.24, 3.00, 3.00, 2.60, 3.03, 2.75, 3.10, 3… #> $ viewers_28day <dbl> 7, 3, 2, 4, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1… #> $ network_rank <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… #> $ channels_rank <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… #> $ bbc_iplayer_requests <dbl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… ``` ] --- # eval .pull-left[ ```` ```{r eval=FALSE} glimpse(ratings) ``` ```` ] .pull-right[ ```r glimpse(ratings) ``` ] --- # include .pull-left[ ```` ```{r include=FALSE} glimpse(ratings) ``` ```` ] .pull-right[ ] --- # results .pull-left[ ```` ```{r echo=TRUE, results='hide'} glimpse(ratings) ``` ```` ] .pull-right[ ```r glimpse(ratings) ``` ] --- # message / warning ![](https://www.tidyverse.org/images/tidyverse_1.2.0/tidyverse_1-2-0_pkg_load.gif) --- # message / warning .pull-left[ ```` ```{r message=FALSE, warning=FALSE} library(tidyverse) ``` ```` ] .pull-right[ ```r library(tidyverse) ``` ] --- .left-column[ # Default options ] .right-column[ ```r str(knitr::opts_chunk$get()) #> List of 53 #> $ eval : logi TRUE #> $ echo : logi TRUE #> $ results : chr "markup" #> $ tidy : logi FALSE #> $ tidy.opts : NULL #> $ collapse : logi TRUE #> $ prompt : logi FALSE #> $ comment : chr "#>" #> $ highlight : logi TRUE #> $ strip.white : logi TRUE #> $ size : chr "normalsize" #> $ background : chr "#F7F7F7" #> $ cache : logi FALSE #> $ cache.path : chr "01-basics_cache/html/" #> $ cache.vars : NULL #> $ cache.lazy : logi TRUE #> $ dependson : NULL #> $ autodep : logi FALSE #> $ cache.rebuild: logi FALSE #> $ fig.keep : chr "high" #> $ fig.show : chr "asis" #> $ fig.align : chr "default" #> $ fig.path : chr "01-basics_files/figure-html/" #> $ dev : chr "png" #> $ dev.args : NULL #> $ dpi : num 72 #> $ fig.ext : NULL #> $ fig.width : num 7 #> $ fig.height : num 7 #> $ fig.env : chr "figure" #> $ fig.cap : NULL #> $ fig.scap : NULL #> $ fig.lp : chr "fig:" #> $ fig.subcap : NULL #> $ fig.pos : chr "" #> $ out.width : NULL #> $ out.height : NULL #> $ out.extra : NULL #> $ fig.retina : num 1 #> $ external : logi TRUE #> $ sanitize : logi FALSE #> $ interval : num 1 #> $ aniopts : chr "controls,loop" #> $ warning : logi TRUE #> $ error : logi FALSE #> $ message : logi TRUE #> $ render : NULL #> $ ref.label : NULL #> $ child : NULL #> $ engine : chr "R" #> $ split : logi FALSE #> $ include : logi TRUE #> $ purl : logi TRUE ``` ] --- # Chunk option take-aways + Place between curly braces<br>`{r option=value}` + Multiple options separated by commas<br>`{r option1=value, option2=value}` + Careful! The `r` part is the **code engine** (other engines possible) --- # Chunk labels .pull-left[ ```` ```{r peek, echo=FALSE, results='hide'} glimpse(ratings) ``` ```` ] .pull-right[ + Place between curly braces<br>`{r label}` + Separated options with commas<br>`{r label, option1=value}` + Careful! No duplicate chunk labels ```` ```{r peek} head(ratings) ``` ```` ``` Error in parse_block(g[-1], g[1], params.src) : duplicate label 'peek' Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block Execution halted ``` ] ??? how can we make it easier on ourselves to explore the code in here? show how to add chunk labels and view in IDE interactively --- class: middle, center # Pet or livestock? .pull-left[ ![](https://cdn.images.express.co.uk/img/dynamic/128/590x/Barry-the-Lamb-770211.jpg) ] .pull-right[ ![](images/christopher-burns-215Fiqh6hRc-unsplash.jpg) ] .footnote[https://masalmon.eu/2017/08/08/chunkpets/; https://www.express.co.uk/news/nature/770211/pet-sheep-lamb-rasied-dog-farm-nature] --- class: middle, center # A good chunk label .pull-left[ ### Good `my-plot` `myplot` `myplot1` `myplot-1` `MY-PLOT` ] .pull-right[ ### Bad `my_plot` `my plot` everything else! ] --- # The setup chunk .pull-left[ ```` ```{r setup, include=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", out.width = "100%" ) ``` ```` ] .pull-right[ + A special chunk label: `setup` + Typically #1 + All following chunks will use these options (i.e., sets global chunk options) + **Tip**: set `include=FALSE` + You can (and should) use individual chunk options too ] --- class: live-code # Adding a setup chunk We do this together: 1. Add `fig.path = "figs/"` as a knitr code chunk option for a single plot (watch what happens if we don't include the backslash!) 1. Knit and behold 1. We add it to a global setup chunk. --- class: your-turn # Your turn Customize this report. 1. Label the code chunk with your plot in it. 1. Add your setup chunk. 1. Use the RStudio outline pane; rejoice! 1. Build a [graphical user interface](https://bookdown.org/yihui/rmarkdown/params-knit.html#the-interactive-user-interface) for parameters. __If this was easy,__ try adding a parameter for color palette and add in a package like [wesanderson](https://github.com/karthik/wesanderson) — use the parameter in our ggplot2 code. _psst...`01-bakeoff-report-alison.Rmd` is there..._ _psst-psst...answers on the next slide..._
05
:
00
--- class: your-turn # Answers ```yaml params: series: label: "Series:" value: 1 input: numeric min: 1 max: 9 step: 1 palette: label: "Wes Anderson palette:" value: GrandBudapest1 input: select choices: [GrandBudapest1, Darjeeling1, Darjeeling2, FantasticFox1, Royal2] ``` --- class: inverse, middle, center # 📮 .large[https://app.netlify.com/drop] --- class: live-code # Clean your url up We live demo changing the main "landing page" name to `index.Rmd`, knit, then deploy again: https://app.netlify.com/drop --- class: middle, center # Take-aways -- ✔️ **Document your document:** use YAML to set up meaningful metadata -- ✔️ **Style your document:** use YAML to add options to your chosen output format -- ✔️ **Organize your text:** use markdown headers with `#` -- ✔️ **Organize your code:** use `knitr` chunk labels -- ✔️ **Style your text:** use markdown **bold**, _italics_, <i class="fas fa-list-ul"></i> bullets, and <i class="fas fa-list-ol"></i> lists -- ✔️ **Style your output:** use `knitr` chunk options -- 🧶 early, 🧶 often --- class: middle, center # ⏱ # Time for a break!
30
:
00