class: left, middle, inverse <!-- Title slide --> ### Friends don't let friends copy-paste ![:pull right, 35%]( <img src="https://github.com/crsh/papaja/raw/main/tools/images/papaja_hex.png" style="padding-top: 0.5em;"> ) # Introduction to R Markdown #### Frederik Aust & Marius Barth <small> 21.04.2023 </small> --- exclude: true --- layout: true name: footer <div class="my-footer"> <div style="float: left;"><span>Frederik Aust & Marius Barth</span></div> <div style="text-align: right;"><span>Friends don't let friends copy-paste</span></div> <div style="float: center;"><span>21.04.2023</span></div> </div> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ "HTML-CSS": { scale: 150, } }); </script> --- <script src="https://cdn.jsdelivr.net/npm/medium-zoom@1.0.6/dist/medium-zoom.js"></script> <script type="module"> import mediumZoom from 'https://cdn.jsdelivr.net/npm/medium-zoom@1.0.6/dist/medium-zoom.esm.js' const zoomDefault = mediumZoom('#zoom-default') const zoomMargin = mediumZoom('#zoom-margin', { margin: 45 }) </script> --- # Agenda - Document structure - YAML metadata - Scientific writing - Incorporating R code --- layout: false class: inverse, middle, center # R Markdown --- layout: true template: footer name: rmd # R Markdown --- .pull-right-45[<img src="data:image/png;base64,#img/rmarkdown_formats.png" width="564" style="display: block; margin: auto;" />] - Widely used and actively developed - Supports many output formats<br />(e.g., HTML, PDF, DOCX, ODT) - Customizable and extendable [`bookdown`](https://github.com/rstudio/bookdown), [`rticles`](https://github.com/rstudio/rticles), [`xaringan`](https://github.com/yihui/xaringan), [`blogdown`](https://github.com/rstudio/blogdown), [`pkgdown`](https://github.com/hadley/pkgdown), [`flexdashboard`]( https://github.com/rstudio/flexdashboard), ..., [`papaja`](https://github.com/crsh/papaja) ??? Image taken from http://rmarkdown.rstudio.com/authoring_quick_tour.html This work is licensed under the [Creative Commons Attribution-NonCommercial-NoDerivs 3.0](http://creativecommons.org/licenses/by-nc-nd/3.0/us/) United States License. --- layout: true template: footer <img src="data:image/png;base64,#img/new_rmarkdown.png" width="1421" height="475px" id="zoom-margin" style="display: block; margin: auto;" /> .center[ <span style = "font-size: 75%">Creating a new R Markdown document<br />(`File > New File > R Markdown`)</span> ] --- <img src="data:image/png;base64,#img/rmd_document.png" width="1421" height="475px" style="display: block; margin: auto;" /> --- layout: true template: rmd --- Documents can be rendered or "knitted" with<br /><kbd>![](data:image/png;base64,#img/knit.png) Knit</kbd> or <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>K</kbd> <img src="data:image/png;base64,#img/knit_dropdown.png" width="400px" style="display: block; margin: auto;" /> --- <img src="data:image/png;base64,#img/knitted_document.png" width="700px" style="display: block; margin: auto;" /> --- template: rmd Two-part plain text documents 1. YAML front matter - Document metadata - Rendering options -- 2. Document body - Markdown text - R code --- template: rmd <img src="data:image/png;base64,#img/yml-md.png" width="1920" style="display: block; margin: auto;" /> -- <div id="overlay-highlight"style="width:423px;height:70px;left:7.5%;top:30.5%;border-style:none;opacity:0.7;"></div> --- layout: true template: rmd ### YAML front matter --- A human-readable syntax to define data structures .pull-left-45[ .center[YAML] ```yaml *--- title: "YAML Example" author: "Frederik Aust" date: "29 11 2017" output: html_document *--- ``` ] .pull-right-45[ .center[Equivalent `list` in R] ```r list( title = "YAML Example" , author = "Frederik Aust" , date = "29 11 2017" , output = "html_document" ) ``` ] --- Indentation indicates nesting .pull-left-40[ ```yaml output: html_document: toc: yes ``` ] .pull-right-55[ ```r list( output = list( html_document = list(toc = TRUE) ) ) ``` ] <br /><br /><br /><br /> -- <small> Here, `toc = TRUE` is passed to `rmarkdown::html_document()` </small> --- You can also have unnamed list elements .pull-left-35[ ```yaml author: - name: "Me" corresponding: yes - name: "Myself" ``` ] .pull-right-60[ ```r list( author = list( list(name = "Me", corresponding = TRUE) , list(name = "Myself") ) ) ``` ] --- Of course, list elements can contain vectors .pull-left-45[ ```yaml bibliography: ["a.bib", "b.bib"] ``` ] .pull-right-50[ ```r list( bibliography = c("a.bib", "b.bib") ) ``` ] --- Text can span multiple lines ```yaml *abstract: | This text spanns multiple rows. New lines are preserved, but note the indentation! ``` --- template: rmd <img src="data:image/png;base64,#img/yml-md.png" width="1920" style="display: block; margin: auto;" /> -- <div id="overlay-highlight"style="width:423px;height:250px;left:7.5%;top:40.5%;border-style:none;opacity:0.7;"></div> --- layout: true template: rmd ### Markdown --- - Separation of content and style<br />(e.g., \*\*text\*\* instead of <span style="font-weight: 1000; text-shadow: 0px 1px, 1px 0px, 1px 1px;">text</span>) 1. Swiftly switch styles and document formats 2. Focus on writing -- 3. Well-supported by Git -- - Easy-to-read and -write -- - For details see [`pandoc` markdown](https://pandoc.org/MANUAL.html#pandocs-markdown) documentation --- ```md # Methods ## Participants Younger adults (14 women, 10 men, $M_{age} = 19.5$ years, age range: 18–22 years) were recruited with flyers posted on the Boston College campus. <!–– TODO: Add consent to appendix ––> Older adults (15 women, nine men, $M_{age} = 76.1$ years, age range: 68–84 years) were recruited through the Harvard Cooperative on Aging (see Table 1, for demographics and test scores).[^p] [^p]: Analyses of covariance were conducted with these covariates, with no resulting influences of these variables on the pattern or magnitude of the results. ``` --- .pull-left-45[ ``` # A level 1 heading ## A level 2 heading ### A level 3 heading This is a paragraph. This is a new paragraph. Still the same paragraph! ``` ] .pull-right-50[ <h1 style = "font-size: 1.5em; line-height: 1em;">A level 1 heading</h1> <h2 style = "font-size: 1.25em; line-height: 1em;">A level 2 heading</h2> <h3 style = "font-size: 1em; line-height: 1em;">A level 3 heading</h3> <small style = "line-height: 1em;">This is a paragraph. This is a new paragraph. Still the same paragraph!</small> ] --- .pull-left-45[ ``` *This text is italic.* **This text is bold.** ***This text is both.*** > A block quote.[^footnote] [^footnote]: This is a footnote <!-- A top secrete comment --> ``` ] .pull-right-50[ <small> *This text is italic.* <span style="font-weight: 1000; text-shadow: 0px 1px, 1px 0px, 1px 1px;">This text is bold.</span> <span style="font-weight: 1000; text-shadow: 0px 1px, 1px 0px, 1px 1px;">*This text is both.*</span> > *A block quote.*<sup>1</sup> .footnote[<sup>1</sup> This is a footnote] </small> ] --- .pull-left-45[ ``` - Unordered list item - Unordered list item - Unordered sublist item 1. Ordered list item 2. Ordered list item - Ordered sublist item ``` ] .pull-right-50[ <small> - Unordered list item - Unordered list item - Unordered sublist item 1. Ordered list item 2. Ordered list item - Ordered sublist item </small> ] --- .pull-left-45[ ``` Inline equations (e.g., $Z_{x} = \Phi^{-1}\{x\}$) and displayed equations, e.g., $$ \begin{align} d' & = Z_{\text{H}} - Z_{\text{FA}} \\ c & = -\frac{Z_{\text{H}} + Z_{\text{FA}}}{2} \end{align} $$ ``` ] .pull-right-50[ <small> Inline equations (e.g., `\(Z_{x} = \Phi^{-1}\{x\}\)`) and displayed equations, e.g., $$ `\begin{align} d' & = Z_{\text{H}} - Z_{\text{FA}} \\ c & = -\frac{Z_{\text{H}} + Z_{\text{FA}}}{2} \end{align}` $$ </small> ] --- layout: true template: rmd ### Citations --- `citeproc` is a `pandoc` extension that formats references - works well across documents formats -- - Provide a reference file (e.g., Bib(La)TeX, EndNote, JSON-CSL) ```yaml --- bibliography: "my.bib" --- ``` --- Reference handles are used to specify citations <small> | Citation style | Syntax | Displayed citation | |:---------------|:-------|:------------------| | Citation within parentheses | `[@james_1890]` | (James, 1890) | | Multiple citations | `[@james_1890; @bem_2011]` | (Bem, 2011; James, 1890) | | In-text citations | `@james_1890` | James (1890) | | Year only | `[-@bem_2011]` | (2011) | </small> --- Add pre- and post-fixes to individual citations - `[e.g., @bem_2011]` yields "(e.g., Bem, 2011)" - `[see @bem_2011 for a surprising result]` yields<br />"(see Bem, 2011, for a surprising result)" --- Placement of the reference section - By default, at the end of document -- - Specify placement (e.g., to include an appendix) ```md # References :::{#refs} ::: ``` --- `pandoc` relies on [Citation Style Language](http://citationstyles.org/) (CSL) - The default style is Chicago Author-Date style -- - Provide a CSL file to change the citation style ```yaml --- csl: plos-computational-biology.csl --- ``` --- The RStudio addin [`citr`](https://github.com/crsh/citr) facilitates searching and inserting citations - By default, searches the provided bibliography file(s) - Connects to Zotero if the [Better Bib(La)TeX extension](https://github.com/retorquere/zotero-better-bibtex/wiki) is installed and Zotero is up and running --- <img src="data:image/png;base64,#https://github.com/crsh/citr/raw/master/tools/images/addin_demo.gif" height="475px" style="display: block; margin: auto;" /> --- template: footer .pull-right-50[ ![](data:image/png;base64,#img/visual-editor.png) ] .pull-left-45[ # R Markdown ### Visual Editor - Word-like editor - Advanced citation features - Easy cross-referencing - See [documentation](https://quarto.org/docs/visual-editor/) for details ] --- layout: true template: rmd name: visual-editor ### Visual Editor --- <small> | Command | Shortcut | Markdown | |--------------|:------------------|:-----------------:| | Bold | <kbd>Ctrl</kbd> + <kbd>B</kbd> | `**bold**` | | Italic | <kbd>Ctrl</kbd> + <kbd> I</kbd> | `*italic*` | | Code | <kbd>Ctrl</kbd> + <kbd> D</kbd> | <code class = "remark-inline-code">`code`</code> | | Heading 1 | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd> 1</kbd> | `#` | | Heading 2 | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd> 2</kbd> | `##` | | Heading 3 | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd> 3</kbd> | `###` | </small> ??? Shortcuts can be customized --- .center[![:scale 65%](data:image/png;base64,#img/visual-editing-crossref.png)] --- .center[![:scale 70%](data:image/png;base64,#img/visual-editing-crossref2.png)] --- .center[![:scale 70%](data:image/png;base64,#img/visual-editing-citations.png)] --- .center[![:scale 70%](data:image/png;base64,#img/visual-editing-citations2.png)] --- layout: true template: rmd name: r-code ### R code --- *Code chunks*, the primary method to include R code .pull-left-45[ Insert a new code chunk - <kbd>![](data:image/png;base64,#img/insert_chunk.png)</kbd> - <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>I</kbd> ] -- .pull-right-50[ <pre><code class = "markdown hljs remark-code" style = "background: #F2F2F2;">.highlight[```{r}]<img src="data:image/png;base64,#img/chunk_buttons.png" style = "float:right;" /><br /> # Your code goes here<br /> .highlight[```] </code></pre> ] ??? Make sure code chunks are surrounded by new lines! --- layout: true template: rmd --- Executing R code interactively <small> | Code portion| Command | |-----------|--------------------------------------| | One line | <kbd>Ctrl</kbd> + <kbd>↵</kbd> | | One code chunk | <kbd>![](data:image/png;base64,#img/execute_chunk.png)</kbd> or<br /><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>C</kbd> | | Next code chunk | <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>C</kbd> | | All previous code chunks | <kbd>![](data:image/png;base64,#img/execute_previous_chunks.png)</kbd> or<br /><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>N</kbd> | | All code chunks | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>R</kbd> | </small> --- Results printed to the console and plots will be displayed in the document .pull-left-30[ ```r 1 + 1 ``` ``` ## [1] 2 ``` ```r a <- 1 + 1 a ``` ``` ## [1] 2 ``` ] -- .pull-right-60[ ```r image(volcano, axes = FALSE, asp = 1) ``` <img src="data:image/png;base64,#/Users/frederikaust/Documents/lectures/papaja-workshop/slides/2_rmarkdown_files/figure-html/unnamed-chunk-14-1.png" width="60%" style="display: block; margin: auto;" /> ] --- Knitting an R Markdown file 1. Vanilla R session - No variables defined! - No R packages loaded! -- 2. Working directory set to path of R Markdown file 3. R code is run from top to bottom - Variables are available in subsequent chunks --- layout: true template: r-code --- Add chunk name with special comments on the first line .pull-left-45[ - plot file name - enables cross-referencing plots and tables ] .pull-right-50[ <pre><code class = "markdown hljs remark-code">```{r}<img src="data:image/png;base64,#img/chunk_buttons.png" style = "float:right;" /><br /> .highlight[\#| label: addition]<br /><br /> 1 + 1<br /> ``` </code></pre> ] -- <br /><br /><br /><br /><br style="line-height: 2em;"/> *Names must be unique and cannot contain* `_` *or* ` `*!* --- Control behavior of chunks with special YAML comments .pull-left-45[ - `echo: false` hides code in rendered document - See [`knitr` documentation](https://yihui.name/knitr/options/) for list of options</small> ] .pull-right-50[ <pre><code class = "markdown hljs remark-code">```{r}<img src="data:image/png;base64,#img/chunk_buttons.png" style = "float:right;" /><br /> #| label: addition<br /> .highlight[\#| echo: false]<br /><br /> 1 + 1<br /> ``` </code></pre> ] -- <div id="overlay-highlight"style="width:30px;height:30px;left:82.25%;top:49.75%;background-color:transparent;opacity:0.7;"></div> --- Alternative syntax for chunk name and options <pre><code class = "markdown hljs remark-code">```{r, .highlight[addition, echo = FALSE]}<img src="data:image/png;base64,#img/chunk_buttons.png" style = "float:right;" /><br /> 1 + 1<br /> ``` </code></pre> *Note that options use R syntax, not YAML!* --- Special `setup` chunk to customize chunk default options <pre><code class = "markdown hljs remark-code">```{r}<img src="data:image/png;base64,#img/chunk_buttons.png" style = "float:right;" /><br /> .highlight[\#| label: setup]<br /> .highlight[\#| include: false]<br /><br /> knitr::opts_chunk$set(echo = FALSE)<br /> ``` </code></pre> -- `include: false` hides code, results, warnings, etc. --- `par()` sets graphical parameters for one chunk only <pre><code class = "markdown hljs remark-code">```{r}<img src="data:image/png;base64,#img/chunk_buttons.png" style = "float:right;" /><br /> #| label: setup<br /> #| include: false<br /><br /> knitr::opts_chunk$set(echo = FALSE)<br /> .highlight[knitr::opts_knit$set(global.par = TRUE)]<br /> ``` </code></pre> --- R code can also be included in-line ```md Participants' mean age was `r age_mean` years (*SD* = `r age_sd`). ``` > Participants' mean age was 32.35 years (*SD* = 6.23). --- template: rmd ### Troubleshooting Can be challenging -- - Code is run in a new *non-interactive* R session -- - Recreate problem in your *interactive* session 1. Restart R (*Session* > *Restart R*) 2. Run all chunks (<kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>R</kbd>) 3. Compare the working directories<br />(e.g., use `getwd()` in a code chunk) --- template: rmd ### Best practices - Load all R packages in the first code chunk - Never include `install.packages()` -- - Use relative paths - Never use `setwd()`! -- - Keep chunks short, use meaningful names -- - Knit early, knit often --- template: rmd ### Best practices - Keep R code close to the corresponding prose - Document R and R-package versions<br />(e.g., `sessioninfo::session_info()`) - Set seeds for random number generators (`set.seed()`) --- layout: false class: inverse, middle, center # Example manuscript --- layout: true template: footer # Serial response time task --- <img src="data:image/png;base64,#img/srt-thin.gif" style="display: block; margin: auto;" /> -- <img src="data:image/png;base64,#img/hands.png" width="1084" style="display: block; margin: auto;" /> --- .pull-left-50[ <img src="data:image/png;base64,#img/standard-finding.png" width="600" style="display: block; margin: auto;" /> ] --- exclude: true .pull-left-50[ <img src="data:image/png;base64,#img/standard-finding.png" width="600" style="display: block; margin: auto;" /> ] .pull-right[ - Dissociation with explicit sequence knowledge, as measured by - free recall - recognition tasks - generation task - ... - **Process dissociation** ] --- layout: true template: footer # Process Dissociation (PD) --- Distinguish implicit and explicit knowledge via *controllability* - Explicit: controllable - Implicit: not controllable .pull-left-40[ **Inclusion**<br> "Generate a *similar* sequence" ] .pull-right-40[ **Exclusion**<br> "Generate a *different* sequence" ] --- layout: true template: footer # The present study <!-- Is it valid to compare generation performance with a theoretically-derived baseline? --> Could the effects of possible identified moderators (*generation task* and type of random *material*) be attributed to changes in baseline performance? - Two types of generation task (**free** vs. **cued** generation tasks) - Different types of "random" material (**permuted** vs. **random** material) <!-- - **permuted**: 4-3-5-2-6-1---5-2-3-6-1-4 (i.e., "use up" all locations...) --> <!-- - **random**: 6-4-2-5-1-5-3-6-4-1-2-1 (i.e., "truly" random...) --> - How many "regular" transitions do participants generate who never actually worked on an SRTT (**no-learning** group)? --- template: footer class: middle, center # [Let's get some exercise](http://frederikaust.com/papaja-workshop/exercises/2_rmarkdown_question.html)!