├── .github ├── .gitignore ├── FUNDING.yml ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── suggestions.md │ └── questions.md └── workflows │ └── bookdown.yaml ├── latex ├── after_body.tex ├── before_body.tex └── preamble.tex ├── images ├── cover.png ├── paged.png ├── rpubs.png ├── shiny.png ├── shower.png ├── tabset.png ├── beamer-1.png ├── beamer-2.png ├── hello-rmd.png ├── leaflet.png ├── pkgdown.png ├── prettydoc.png ├── site-page.png ├── slidy-1.png ├── slidy-2.png ├── ioslides-1.png ├── ioslides-2.png ├── powerpoint.png ├── revealjs-1.png ├── revealjs-2.png ├── shiny-plot.png ├── shiny-table.png ├── site-build.png ├── tufte-full.png ├── tufte-main.png ├── tufte-table.png ├── xaringan-1.png ├── xaringan-2.png ├── beamer-theme-1.png ├── beamer-theme-2.png ├── bookdown-build.png ├── dashboard-text.png ├── hello-rmd-out.png ├── hex-rmarkdown.png ├── learnr-hello.png ├── mirror-display.png ├── notebook-demo.png ├── notebook-error.png ├── params-input.png ├── rticles-plos.png ├── shiny-deploy.png ├── site-preview.png ├── tufte-margin.png ├── tufte-overview.png ├── dashboard-gauges.png ├── dashboard-pages.png ├── dashboard-shiny.png ├── dashboard-start.png ├── dashboard-story.png ├── format-dropdown.png ├── learnr-progress.png ├── learnr-question.png ├── learnr-solution.png ├── learnr-template.png ├── notebook-console.png ├── notebook-preview.png ├── params-controls.png ├── rticles-springer.png ├── templates-select.png ├── tufte-responsive.png ├── bookdown-template.png ├── rmdformats-material.png ├── rticles-templates.png ├── shiny-new-document.png ├── shiny-widget-kmeans.png ├── dashboard-valueboxes.png ├── notebook-longrunning.png ├── notebook-split-after.png ├── notebook-split-before.png ├── notebook-external-code.png └── notebook-inline-output.png ├── .gitattributes ├── examples ├── r-notebook-stub.Rmd ├── hello-tutorial.Rmd ├── htmlwidgets.Rmd ├── dashboard │ ├── 01-start.Rmd │ ├── 02-pages.Rmd │ ├── 03-storyboard.Rmd │ ├── 05-gauges.Rmd │ ├── 04-valueboxes.Rmd │ ├── 06-text.Rmd │ └── 07-shiny.Rmd ├── shiny.Rmd ├── python.Rmd └── shiny-output-args.Rmd ├── README.md ├── .gitignore ├── _bookdown.yml ├── rmarkdown-book.Rproj ├── Makefile ├── _render.R ├── DESCRIPTION ├── 20-references.Rmd ├── css └── style.css ├── _output.yml ├── 01-installation.Rmd ├── 00-author.Rmd ├── book.bib ├── 11-pkgdown.Rmd ├── 18-new-formats.Rmd ├── 09-community.Rmd ├── 13-rticles.Rmd ├── 17-templates.Rmd ├── 15-parameterized.Rmd ├── 08-revealjs.Rmd ├── 06-tufte.Rmd ├── 14-learnr.Rmd ├── 05-dashboards.Rmd ├── 12-bookdown.Rmd ├── 19-shiny.Rmd ├── LICENSE └── index.Rmd /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /latex/after_body.tex: -------------------------------------------------------------------------------- 1 | \printindex 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [yihui] 2 | patreon: 3 | custom: 4 | -------------------------------------------------------------------------------- /images/cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/cover.png -------------------------------------------------------------------------------- /images/paged.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/paged.png -------------------------------------------------------------------------------- /images/rpubs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/rpubs.png -------------------------------------------------------------------------------- /images/shiny.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shiny.png -------------------------------------------------------------------------------- /images/shower.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shower.png -------------------------------------------------------------------------------- /images/tabset.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tabset.png -------------------------------------------------------------------------------- /images/beamer-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/beamer-1.png -------------------------------------------------------------------------------- /images/beamer-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/beamer-2.png -------------------------------------------------------------------------------- /images/hello-rmd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/hello-rmd.png -------------------------------------------------------------------------------- /images/leaflet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/leaflet.png -------------------------------------------------------------------------------- /images/pkgdown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/pkgdown.png -------------------------------------------------------------------------------- /images/prettydoc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/prettydoc.png -------------------------------------------------------------------------------- /images/site-page.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/site-page.png -------------------------------------------------------------------------------- /images/slidy-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/slidy-1.png -------------------------------------------------------------------------------- /images/slidy-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/slidy-2.png -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.tex linguist-vendored 2 | *.cls linguist-vendored 3 | *.Rmd linguist-detectable 4 | -------------------------------------------------------------------------------- /images/ioslides-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/ioslides-1.png -------------------------------------------------------------------------------- /images/ioslides-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/ioslides-2.png -------------------------------------------------------------------------------- /images/powerpoint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/powerpoint.png -------------------------------------------------------------------------------- /images/revealjs-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/revealjs-1.png -------------------------------------------------------------------------------- /images/revealjs-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/revealjs-2.png -------------------------------------------------------------------------------- /images/shiny-plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shiny-plot.png -------------------------------------------------------------------------------- /images/shiny-table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shiny-table.png -------------------------------------------------------------------------------- /images/site-build.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/site-build.png -------------------------------------------------------------------------------- /images/tufte-full.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tufte-full.png -------------------------------------------------------------------------------- /images/tufte-main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tufte-main.png -------------------------------------------------------------------------------- /images/tufte-table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tufte-table.png -------------------------------------------------------------------------------- /images/xaringan-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/xaringan-1.png -------------------------------------------------------------------------------- /images/xaringan-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/xaringan-2.png -------------------------------------------------------------------------------- /images/beamer-theme-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/beamer-theme-1.png -------------------------------------------------------------------------------- /images/beamer-theme-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/beamer-theme-2.png -------------------------------------------------------------------------------- /images/bookdown-build.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/bookdown-build.png -------------------------------------------------------------------------------- /images/dashboard-text.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-text.png -------------------------------------------------------------------------------- /images/hello-rmd-out.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/hello-rmd-out.png -------------------------------------------------------------------------------- /images/hex-rmarkdown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/hex-rmarkdown.png -------------------------------------------------------------------------------- /images/learnr-hello.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/learnr-hello.png -------------------------------------------------------------------------------- /images/mirror-display.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/mirror-display.png -------------------------------------------------------------------------------- /images/notebook-demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-demo.png -------------------------------------------------------------------------------- /images/notebook-error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-error.png -------------------------------------------------------------------------------- /images/params-input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/params-input.png -------------------------------------------------------------------------------- /images/rticles-plos.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/rticles-plos.png -------------------------------------------------------------------------------- /images/shiny-deploy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shiny-deploy.png -------------------------------------------------------------------------------- /images/site-preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/site-preview.png -------------------------------------------------------------------------------- /images/tufte-margin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tufte-margin.png -------------------------------------------------------------------------------- /images/tufte-overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tufte-overview.png -------------------------------------------------------------------------------- /images/dashboard-gauges.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-gauges.png -------------------------------------------------------------------------------- /images/dashboard-pages.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-pages.png -------------------------------------------------------------------------------- /images/dashboard-shiny.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-shiny.png -------------------------------------------------------------------------------- /images/dashboard-start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-start.png -------------------------------------------------------------------------------- /images/dashboard-story.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-story.png -------------------------------------------------------------------------------- /images/format-dropdown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/format-dropdown.png -------------------------------------------------------------------------------- /images/learnr-progress.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/learnr-progress.png -------------------------------------------------------------------------------- /images/learnr-question.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/learnr-question.png -------------------------------------------------------------------------------- /images/learnr-solution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/learnr-solution.png -------------------------------------------------------------------------------- /images/learnr-template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/learnr-template.png -------------------------------------------------------------------------------- /images/notebook-console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-console.png -------------------------------------------------------------------------------- /images/notebook-preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-preview.png -------------------------------------------------------------------------------- /images/params-controls.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/params-controls.png -------------------------------------------------------------------------------- /images/rticles-springer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/rticles-springer.png -------------------------------------------------------------------------------- /images/templates-select.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/templates-select.png -------------------------------------------------------------------------------- /images/tufte-responsive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/tufte-responsive.png -------------------------------------------------------------------------------- /images/bookdown-template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/bookdown-template.png -------------------------------------------------------------------------------- /images/rmdformats-material.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/rmdformats-material.png -------------------------------------------------------------------------------- /images/rticles-templates.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/rticles-templates.png -------------------------------------------------------------------------------- /images/shiny-new-document.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shiny-new-document.png -------------------------------------------------------------------------------- /images/shiny-widget-kmeans.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/shiny-widget-kmeans.png -------------------------------------------------------------------------------- /images/dashboard-valueboxes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/dashboard-valueboxes.png -------------------------------------------------------------------------------- /images/notebook-longrunning.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-longrunning.png -------------------------------------------------------------------------------- /images/notebook-split-after.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-split-after.png -------------------------------------------------------------------------------- /images/notebook-split-before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-split-before.png -------------------------------------------------------------------------------- /images/notebook-external-code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-external-code.png -------------------------------------------------------------------------------- /images/notebook-inline-output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rstudio/rmarkdown-book/HEAD/images/notebook-inline-output.png -------------------------------------------------------------------------------- /examples/r-notebook-stub.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "R Notebook Stub" 3 | output: html_notebook 4 | --- 5 | 6 | ```{r chunk-one} 7 | print("Hello, World!") 8 | ``` 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The R Markdown Book 2 | 3 | The comprehensive documentation of R Markdown, published by [Chapman & Hall/CRC](https://www.crcpress.com/p/book/9781138359338). 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | _book 6 | rsconnect 7 | _bookdown_files 8 | examples/r-notebook-stub.nb.html 9 | packages.bib 10 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | I assign the copyright of this contribution to the authors of the book "R Markdown: The Definitive Guide". 4 | -------------------------------------------------------------------------------- /_bookdown.yml: -------------------------------------------------------------------------------- 1 | book_filename: rmarkdown 2 | repo: https://github.com/rstudio/rmarkdown-book/ 3 | output_dir: _book 4 | clean: [packages.bib] 5 | language: 6 | label: 7 | fig: "FIGURE " 8 | tab: "TABLE " 9 | ui: 10 | chapter_name: "Chapter " 11 | delete_merged_file: true 12 | -------------------------------------------------------------------------------- /examples/hello-tutorial.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Hello, Tutorial!" 3 | output: learnr::tutorial 4 | runtime: shiny_prerendered 5 | --- 6 | 7 | ```{r setup, include=FALSE} 8 | library(learnr) 9 | ``` 10 | 11 | This code computes the answer to one plus one, change it 12 | so it computes two plus two: 13 | 14 | ```{r addition, exercise=TRUE} 15 | 1 + 1 16 | ``` 17 | -------------------------------------------------------------------------------- /rmarkdown-book.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Website 19 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | rm -f _book/*.html &&\ 3 | BOOKDOWN_FULL_PDF=false Rscript --quiet _render.R 4 | 5 | pdf: 6 | Rscript --quiet _render.R "bookdown::pdf_book" &&\ 7 | mv _book/rmarkdown.pdf _book/rmarkdown-full.pdf 8 | 9 | gitbook: 10 | Rscript --quiet _render.R "bookdown::gitbook" 11 | 12 | pdf2: 13 | BOOKDOWN_FULL_PDF=false Rscript --quiet _render.R "bookdown::pdf_book" 14 | -------------------------------------------------------------------------------- /examples/htmlwidgets.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "An Interactive Map" 3 | --- 4 | 5 | Below is a map that shows the location of the 6 | Department of Statistics, Iowa State University. 7 | 8 | ```{r out.width='100%', echo=FALSE} 9 | library(leaflet) 10 | leaflet() %>% addTiles() %>% 11 | setView(-93.65, 42.0285, zoom = 17) %>% 12 | addPopups( 13 | -93.65, 42.0285, 14 | 'Here is the Department of Statistics, ISU' 15 | ) 16 | ``` 17 | 18 | -------------------------------------------------------------------------------- /examples/dashboard/01-start.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Get Started" 3 | output: flexdashboard::flex_dashboard 4 | --- 5 | 6 | ```{r setup, include=FALSE} 7 | library(flexdashboard) 8 | ``` 9 | 10 | Column 1 11 | -------------------------------------------------- 12 | 13 | ### Chart A 14 | 15 | ```{r} 16 | ``` 17 | 18 | Column 2 19 | -------------------------------------------------- 20 | 21 | ### Chart B 22 | 23 | ```{r} 24 | ``` 25 | 26 | ### Chart C 27 | 28 | ```{r} 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /latex/before_body.tex: -------------------------------------------------------------------------------- 1 | \cleardoublepage\newpage\thispagestyle{empty}\null 2 | \cleardoublepage\newpage\thispagestyle{empty}\null 3 | %\cleardoublepage\newpage 4 | \thispagestyle{empty} 5 | \begin{center} 6 | \Large{To Jung Jae-sung (1982 -- 2018),} 7 | 8 | \large{a remarkably hard-working badminton player with a remarkably simple playing style} 9 | %\includegraphics{images/dedication.pdf} 10 | \end{center} 11 | 12 | \setlength{\abovedisplayskip}{-5pt} 13 | \setlength{\abovedisplayshortskip}{-5pt} 14 | -------------------------------------------------------------------------------- /examples/dashboard/02-pages.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Multiple Pages" 3 | output: flexdashboard::flex_dashboard 4 | --- 5 | 6 | Visualizations {data-icon="fa-signal"} 7 | ===================================== 8 | 9 | ### Chart 1 10 | 11 | ```{r} 12 | ``` 13 | 14 | ### Chart 2 15 | 16 | ```{r} 17 | ``` 18 | 19 | Tables {data-icon="fa-table"} 20 | ===================================== 21 | 22 | ### Table 1 23 | 24 | ```{r} 25 | ``` 26 | 27 | ### Table 2 28 | 29 | ```{r} 30 | ``` 31 | -------------------------------------------------------------------------------- /examples/dashboard/03-storyboard.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Storyboard Commentary" 3 | output: 4 | flexdashboard::flex_dashboard: 5 | storyboard: true 6 | --- 7 | 8 | ### A nice scatterplot here 9 | 10 | ```{r} 11 | plot(cars, pch = 20) 12 | grid() 13 | ``` 14 | 15 | --- 16 | 17 | Some commentary about Frame 1. 18 | 19 | ### A beautiful histogram on this board 20 | 21 | ```{r} 22 | hist(faithful$eruptions, col = 'gray', border = 'white', main = '') 23 | ``` 24 | 25 | --- 26 | 27 | Some commentary about Frame 2. 28 | -------------------------------------------------------------------------------- /_render.R: -------------------------------------------------------------------------------- 1 | quiet = "--quiet" %in% commandArgs(FALSE) 2 | formats = commandArgs(TRUE) 3 | 4 | # provide default formats if necessary 5 | if (length(formats) == 0) formats = c('bookdown::pdf_book', 'bookdown::gitbook') 6 | # render the book to all formats unless they are specified via command-line args 7 | for (fmt in formats) { 8 | cmd = sprintf("bookdown::render_book('index.Rmd', '%s', quiet = %s)", fmt, quiet) 9 | res = xfun::Rscript(c('-e', shQuote(cmd))) 10 | if (res != 0) stop('Failed to compile the book to ', fmt) 11 | } 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/suggestions.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Suggestions 3 | about: Got suggestions about the book? We'd love to listen! 4 | 5 | --- 6 | 7 | Suggestions on improving the existing chapters/sections are always welcome. Or even better, you may edit the source files and submit a pull request, in which case please include a statement if the contribution is nontrivial (e.g. not simply fixing a typo): 8 | 9 | > I assign the copyright of this contribution to the authors of the book "R Markdown: The Definitive Guide". 10 | 11 | You may also suggest new topics to us. Thanks! 12 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Type: Book 2 | Package: rmarkdownbook 3 | Title: R Markdown Definitive Guide 4 | Version: 1.0.0 5 | Imports: 6 | animation, 7 | blogdown, 8 | bookdown, 9 | DT, 10 | dygraphs, 11 | flexdashboard, 12 | JuliaCall, 13 | leaflet, 14 | learnr, 15 | markdown, 16 | pagedown, 17 | pkgdown, 18 | prettydoc, 19 | reticulate, 20 | revealjs, 21 | rmdformats, 22 | rticles, 23 | servr, 24 | shiny, 25 | tufte, 26 | webshot2, 27 | xaringan, 28 | sigma 29 | Remotes: 30 | jjallaire/sigma 31 | Config/Needs/deploy: rsconnect 32 | Encoding: UTF-8 33 | -------------------------------------------------------------------------------- /examples/shiny.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "A Shiny Document" 3 | output: html_document 4 | runtime: shiny 5 | --- 6 | 7 | A standard R plot can be made interactive by wrapping 8 | it in the Shiny `renderPlot()` function. The `selectInput()` 9 | function creates the input widget to drive the plot. 10 | 11 | ```{r eruptions, echo=FALSE} 12 | selectInput( 13 | 'breaks', label = 'Number of bins:', 14 | choices = c(10, 20, 35, 50), selected = 20 15 | ) 16 | 17 | renderPlot({ 18 | par(mar = c(4, 4, .1, .5)) 19 | hist( 20 | faithful$eruptions, as.numeric(input$breaks), 21 | col = 'gray', border = 'white', 22 | xlab = 'Duration (minutes)', main = '' 23 | ) 24 | }) 25 | ``` 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/questions.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Questions 3 | about: Got questions about R Markdown? You may consider asking elsewhere. 4 | 5 | --- 6 | 7 | This Github repository is maintained primarily by a single person. If you wish he still has time to breathe, please do him a favor to ask questions in a public forum such as Stack Overflow (https://stackoverflow.com/tags/rmarkdown) or RStudio Community (https://community.rstudio.com). Hopefully your question will be seen by a lot more people (> 1 for sure), and answered more quickly. 8 | 9 | If you have a question that is very specific to this particular Github repository, please feel free to ask, though. Thanks for your understanding! 10 | -------------------------------------------------------------------------------- /examples/dashboard/05-gauges.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Dashboard Gauges" 3 | output: 4 | flexdashboard::flex_dashboard: 5 | orientation: rows 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | library(flexdashboard) 10 | ``` 11 | 12 | ### Contact Rate 13 | 14 | ```{r} 15 | gauge(91, min = 0, max = 100, symbol = '%', gaugeSectors( 16 | success = c(80, 100), warning = c(40, 79), danger = c(0, 39) 17 | )) 18 | ``` 19 | 20 | ### Average Rating 21 | 22 | ```{r} 23 | gauge(37.4, min = 0, max = 50, gaugeSectors( 24 | success = c(41, 50), warning = c(21, 40), danger = c(0, 20) 25 | )) 26 | ``` 27 | 28 | ### Cancellations 29 | 30 | ```{r} 31 | gauge(7, min = 0, max = 10, gaugeSectors( 32 | success = c(0, 2), warning = c(3, 6), danger = c(7, 10) 33 | )) 34 | ``` 35 | -------------------------------------------------------------------------------- /20-references.Rmd: -------------------------------------------------------------------------------- 1 | \backmatter 2 | 3 | `r if (knitr::is_html_output()) ' 4 | # References {-} 5 | '` 6 | 7 | ```{r include=FALSE} 8 | bib = knitr::write_bib(c( 9 | .packages(), 'blogdown', 'bookdown', 'knitr', 'rmarkdown', 'htmlwidgets', 'webshot', 'servr', 'xaringan', 'animation', 'pkgdown', 'tinytex', 'reticulate', 'JuliaCall', 'DT', 'leaflet', 'dygraphs', 'shiny', 'markdown', 'flexdashboard', 'tufte', 'revealjs', 'prettydoc', 'htmltools', 'rticles', 'learnr', 'rmdformats', 'pagedown' 10 | ), file = NULL) 11 | bib = unlist(bib) 12 | bib = gsub("'(Htmlwidgets|iframes|TeX Live|LaTeX)'", '\\1', bib) 13 | xfun::write_utf8(bib, 'packages.bib') 14 | 15 | # embed fonts 16 | if (knitr::is_latex_output()) { 17 | pdfs = list.files(knitr::opts_chunk$get('fig.path'), '[.]pdf$', full.names = TRUE) 18 | invisible(lapply(pdfs, embedFonts)) 19 | } 20 | ``` 21 | -------------------------------------------------------------------------------- /examples/dashboard/04-valueboxes.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Dashboard Value Boxes" 3 | output: 4 | flexdashboard::flex_dashboard: 5 | orientation: rows 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | library(flexdashboard) 10 | # these computing functions are only toy examples 11 | computeArticles = function(...) return(45) 12 | computeComments = function(...) return(126) 13 | computeSpam = function(...) return(15) 14 | ``` 15 | 16 | ### Articles per Day 17 | 18 | ```{r} 19 | articles = computeArticles() 20 | valueBox(articles, icon = "fa-pencil") 21 | ``` 22 | 23 | ### Comments per Day 24 | 25 | ```{r} 26 | comments = computeComments() 27 | valueBox(comments, icon = "fa-comments") 28 | ``` 29 | 30 | ### Spam per Day 31 | 32 | ```{r} 33 | spam = computeSpam() 34 | valueBox( 35 | spam, icon = "fa-trash", 36 | color = ifelse(spam > 10, "warning", "primary") 37 | ) 38 | ``` 39 | -------------------------------------------------------------------------------- /css/style.css: -------------------------------------------------------------------------------- 1 | p.caption { 2 | color: #777; 3 | margin-top: 10px; 4 | } 5 | p code { 6 | white-space: inherit; 7 | } 8 | pre { 9 | word-break: normal; 10 | word-wrap: normal; 11 | } 12 | pre code { 13 | white-space: inherit; 14 | } 15 | p.flushright { 16 | text-align: right; 17 | } 18 | blockquote > p:last-child { 19 | text-align: right; 20 | } 21 | blockquote > p:first-child { 22 | text-align: inherit; 23 | } 24 | .header-section-number { 25 | padding-right: .2em; 26 | font-weight: 500; 27 | } 28 | .level1 .header-section-number { 29 | display: inline-block; 30 | border-bottom: 3px solid; 31 | } 32 | .level1 h1 { 33 | border-bottom: 1px solid; 34 | } 35 | h1, h2, h3, h4, h5, h6 { 36 | font-weight: normal; 37 | } 38 | h1.title { 39 | font-weight: 700; 40 | } 41 | .book .book-body .page-wrapper .page-inner section.normal strong { 42 | font-weight: 600; 43 | } 44 | -------------------------------------------------------------------------------- /_output.yml: -------------------------------------------------------------------------------- 1 | bookdown::gitbook: 2 | css: css/style.css 3 | split_by: section 4 | config: 5 | toc: 6 | collapse: none 7 | before: | 8 |
  • R Markdown: The Definitive Guide
  • 9 | after: | 10 |
  • Published with bookdown
  • 11 | download: [pdf] 12 | edit: https://github.com/rstudio/rmarkdown-book/edit/main/%s 13 | sharing: 14 | github: yes 15 | facebook: no 16 | bookdown::pdf_book: 17 | includes: 18 | in_header: latex/preamble.tex 19 | before_body: latex/before_body.tex 20 | after_body: latex/after_body.tex 21 | keep_tex: yes 22 | latex_engine: xelatex 23 | citation_package: natbib 24 | template: null 25 | pandoc_args: [--top-level-division=chapter, --wrap=none] 26 | toc_depth: 3 27 | toc_unnumbered: no 28 | toc_appendix: yes 29 | highlight_bw: yes 30 | quote_footer: ["\\VA{", "}{}"] 31 | -------------------------------------------------------------------------------- /examples/dashboard/06-text.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Text Annotations" 3 | output: 4 | flexdashboard::flex_dashboard: 5 | orientation: rows 6 | --- 7 | 8 | Monthly deaths from bronchitis, emphysema and asthma in the 9 | UK, 1974–1979 (Source: P. J. Diggle, 1990, Time Series: A 10 | Biostatistical Introduction. Oxford, table A.3) 11 | 12 | ```{r setup, include=FALSE} 13 | library(dygraphs) 14 | ``` 15 | 16 | Row {data-height=600} 17 | ------------------------------------- 18 | 19 | ### All Lung Deaths 20 | 21 | ```{r} 22 | dygraph(ldeaths) 23 | ``` 24 | 25 | Row {data-height=400} 26 | ------------------------------------- 27 | 28 | ### Male Deaths 29 | 30 | ```{r} 31 | dygraph(mdeaths) 32 | ``` 33 | 34 | > Monthly deaths from lung disease in the UK, 1974–1979 35 | 36 | ### About dygraphs 37 | 38 | This example makes use of the dygraphs R package. The dygraphs 39 | package provides rich facilities for charting time-series data 40 | in R. You can use dygraphs at the R console, within R Markdown 41 | documents, and within Shiny applications. 42 | -------------------------------------------------------------------------------- /examples/python.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Python code chunks in R Markdown" 3 | date: 2018-02-22 4 | --- 5 | 6 | ## A normal R code chunk 7 | 8 | ```{r} 9 | library(reticulate) 10 | x = 42 11 | print(x) 12 | ``` 13 | 14 | ## Modify an R variable 15 | 16 | In the following chunk, the value of `x` on the right hand side 17 | is `r x`, which was defined in the previous chunk. 18 | 19 | ```{r} 20 | x = x + 12 21 | print(x) 22 | ``` 23 | 24 | ## A Python chunk 25 | 26 | This works fine and as expected. 27 | 28 | ```{python} 29 | x = 42 * 2 30 | print(x) 31 | ``` 32 | 33 | The value of `x` in the Python session is `r py$x`. 34 | It is not the same `x` as the one in R. 35 | 36 | ## Modify a Python variable 37 | 38 | ```{python} 39 | x = x + 18 40 | print(x) 41 | ``` 42 | 43 | Retrieve the value of `x` from the Python session again: 44 | 45 | ```{r} 46 | py$x 47 | ``` 48 | 49 | Assign to a variable in the Python session from R: 50 | 51 | ```{r} 52 | py$y = 1:5 53 | ``` 54 | 55 | See the value of `y` in the Python session: 56 | 57 | ```{python} 58 | print(y) 59 | ``` 60 | 61 | ## Python graphics 62 | 63 | You can draw plots using the **matplotlib** package in Python. 64 | 65 | ```{python} 66 | import matplotlib.pyplot as plt 67 | plt.plot([0, 2, 1, 4]) 68 | plt.show() 69 | ``` 70 | -------------------------------------------------------------------------------- /examples/dashboard/07-shiny.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Old Faithful Eruptions" 3 | output: flexdashboard::flex_dashboard 4 | runtime: shiny 5 | --- 6 | 7 | ```{r global, include=FALSE} 8 | # load data in 'global' chunk so it can be shared 9 | # by all users of the dashboard 10 | library(datasets) 11 | data(faithful) 12 | ``` 13 | 14 | Column {.sidebar} 15 | -------------------------------------------------- 16 | 17 | Waiting time between eruptions and the duration of the eruption 18 | for the Old Faithful geyser in Yellowstone National Park, 19 | Wyoming, USA. 20 | 21 | ```{r} 22 | selectInput( 23 | "n_breaks", label = "Number of bins:", 24 | choices = c(10, 20, 35, 50), selected = 20 25 | ) 26 | 27 | sliderInput( 28 | "bw_adjust", label = "Bandwidth adjustment:", 29 | min = 0.2, max = 2, value = 1, step = 0.2 30 | ) 31 | ``` 32 | 33 | Column 34 | -------------------------------------------------- 35 | 36 | ### Geyser Eruption Duration 37 | 38 | ```{r} 39 | renderPlot({ 40 | erpt = faithful$eruptions 41 | hist( 42 | erpt, probability = TRUE, breaks = as.integer(input$n_breaks), 43 | xlab = "Duration (minutes)", main = "Geyser Eruption Duration", 44 | col = 'gray', border = 'white' 45 | ) 46 | 47 | dens = density(erpt, adjust = input$bw_adjust) 48 | lines(dens, col = "blue", lwd = 2) 49 | }) 50 | ``` 51 | -------------------------------------------------------------------------------- /examples/shiny-output-args.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: Setting output args via render functions 3 | runtime: shiny 4 | output: html_document 5 | --- 6 | 7 | This interactive Rmd document makes use of the `outputArgs` 8 | argument now available to all Shiny `render` functions. To 9 | give an example, this allows you to set arguments to 10 | `imageOutput` through `renderImage`. This means that you 11 | don't have to create a `ui` object just to be able to brush 12 | over an image. Note that this only applies to snippets of 13 | Shiny code during an interactive Rmd (and not to embedded 14 | full apps -- the ones you need to call `shinyApp` to run). 15 | 16 | ## Brushing over an image (and storing the data) 17 | 18 | ```{r setup, echo=FALSE} 19 | library(datasets) 20 | 21 | generateImage = function() { 22 | outfile = tempfile(fileext = '.png') 23 | png(outfile) 24 | par(mar = c(0,0,0,0)) 25 | image(volcano, axes = FALSE) 26 | contour(volcano, add = TRUE) 27 | dev.off() 28 | list(src = outfile) 29 | } 30 | ``` 31 | 32 | ```{r image} 33 | renderImage({ 34 | generateImage() 35 | }, deleteFile = TRUE, 36 | outputArgs = list(brush = brushOpts(id = "plot_brush"), 37 | width = "250", 38 | height = "250px") 39 | ) 40 | ``` 41 | 42 | Here is some of the brushing info sent to the server: 43 | (brush over the image to change the data) 44 | 45 | ```{r brush info} 46 | renderText({ 47 | print(input$plot_brush) 48 | brush = input$plot_brush 49 | paste0("xmin: ", brush$xmin, "; ", 50 | "xmax: ", brush$xmax, "; ", 51 | "ymin: ", brush$ymin, "; ", 52 | "ymax: ", brush$ymax) 53 | }) 54 | ``` 55 | 56 | --- 57 | 58 | ### Resizing a plot 59 | 60 | ```{r plot} 61 | renderPlot({ 62 | plot(cars) 63 | }, outputArgs = list(width = "75%", 64 | height = "250px") 65 | ) 66 | ``` 67 | -------------------------------------------------------------------------------- /latex/preamble.tex: -------------------------------------------------------------------------------- 1 | \usepackage{booktabs} 2 | \usepackage{longtable} 3 | \usepackage[bf,singlelinecheck=off]{caption} 4 | 5 | \usepackage{framed,color} 6 | \definecolor{shadecolor}{RGB}{248,248,248} 7 | 8 | \usepackage{Alegreya} 9 | \usepackage[scale=.8]{sourcecodepro} 10 | 11 | \renewcommand{\textfraction}{0.05} 12 | \renewcommand{\topfraction}{0.8} 13 | \renewcommand{\bottomfraction}{0.8} 14 | \renewcommand{\floatpagefraction}{0.75} 15 | 16 | \renewenvironment{quote}{\begin{VF}}{\end{VF}} 17 | \let\oldhref\href 18 | \renewcommand{\href}[2]{#2\footnote{\url{#1}}} 19 | 20 | \ifxetex 21 | \usepackage{letltxmacro} 22 | \setlength{\XeTeXLinkMargin}{1pt} 23 | \LetLtxMacro\SavedIncludeGraphics\includegraphics 24 | \def\includegraphics#1#{% #1 catches optional stuff (star/opt. arg.) 25 | \IncludeGraphicsAux{#1}% 26 | }% 27 | \newcommand*{\IncludeGraphicsAux}[2]{% 28 | \XeTeXLinkBox{% 29 | \SavedIncludeGraphics#1{#2}% 30 | }% 31 | }% 32 | \fi 33 | 34 | \makeatletter 35 | \newenvironment{kframe}{% 36 | \medskip{} 37 | \setlength{\fboxsep}{.8em} 38 | \def\at@end@of@kframe{}% 39 | \ifinner\ifhmode% 40 | \def\at@end@of@kframe{\end{minipage}}% 41 | \begin{minipage}{\columnwidth}% 42 | \fi\fi% 43 | \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep 44 | \colorbox{shadecolor}{##1}\hskip-\fboxsep 45 | % There is no \\@totalrightmargin, so: 46 | \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}% 47 | \MakeFramed {\advance\hsize-\width 48 | \@totalleftmargin\z@ \linewidth\hsize 49 | \@setminipage}}% 50 | {\par\unskip\endMakeFramed% 51 | \at@end@of@kframe} 52 | \makeatother 53 | 54 | \renewenvironment{Shaded}{\begin{kframe}}{\end{kframe}} 55 | 56 | \usepackage{makeidx} 57 | \makeindex 58 | 59 | \urlstyle{tt} 60 | 61 | \usepackage{amsthm} 62 | \makeatletter 63 | \def\thm@space@setup{% 64 | \thm@preskip=8pt plus 2pt minus 4pt 65 | \thm@postskip=\thm@preskip 66 | } 67 | \makeatother 68 | 69 | \frontmatter 70 | -------------------------------------------------------------------------------- /01-installation.Rmd: -------------------------------------------------------------------------------- 1 | \mainmatter 2 | 3 | # (PART) Get Started {-} 4 | 5 | # Installation 6 | 7 | We assume you have already installed R (https://www.r-project.org) [@R-base] and the RStudio IDE (https://www.rstudio.com). RStudio is not required but recommended, because it makes it easier for an average user to work with R Markdown. If you do not have RStudio IDE installed, you will have to install Pandoc\index{Pandoc} (http://pandoc.org), otherwise there is no need to install Pandoc separately because RStudio has bundled it. Next you can install the **rmarkdown** package in R: 8 | 9 | ```{r eval=FALSE, tidy=FALSE} 10 | # Install from CRAN 11 | install.packages('rmarkdown') 12 | 13 | # Or if you want to test the development version, 14 | # install from GitHub 15 | if (!requireNamespace("devtools")) 16 | install.packages('devtools') 17 | devtools::install_github('rstudio/rmarkdown') 18 | ``` 19 | 20 | If you want to generate PDF output, you will need to install LaTeX. For R Markdown users who have not installed LaTeX before, we recommend that you install TinyTeX (https://yihui.name/tinytex/): 21 | 22 | ```{r eval=FALSE} 23 | install.packages('tinytex') 24 | tinytex::install_tinytex() # install TinyTeX 25 | ``` 26 | 27 | TinyTeX\index{TinyTeX} is a lightweight, portable, cross-platform, and easy-to-maintain LaTeX distribution. The R companion package **tinytex** [@R-tinytex]\index{tinytex} can help you automatically install missing LaTeX packages when compiling LaTeX or R Markdown documents to PDF, and also ensures a LaTeX document is compiled for the correct number of times to resolve all cross-references. If you do not understand what these two things mean, you should probably follow our recommendation to install TinyTeX, because these details are often not worth your time or attention. 28 | 29 | With the **rmarkdown** package, RStudio/Pandoc, and LaTeX, you should be able to compile most R Markdown documents. In some cases, you may need other software packages, and we will mention them when necessary. 30 | -------------------------------------------------------------------------------- /.github/workflows/bookdown.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | workflow_dispatch: 9 | inputs: 10 | publish: 11 | description: 'publish the book to github pages for connect cloud deployment' 12 | required: false 13 | default: false 14 | type: boolean 15 | 16 | name: bookdown 17 | 18 | jobs: 19 | bookdown: 20 | runs-on: ubuntu-latest 21 | env: 22 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 23 | R_KNITR_OPTIONS: "knitr.chunk.tidy=TRUE" 24 | steps: 25 | - name: Checkout Repo 26 | uses: actions/checkout@v4 27 | 28 | - uses: r-lib/actions/setup-pandoc@v2 29 | with: 30 | pandoc-version: '2.13' 31 | 32 | - uses: r-lib/actions/setup-r@v2 33 | with: 34 | use-public-rspm: true 35 | 36 | 37 | - name: Install TinyTeX 38 | uses: r-lib/actions/setup-tinytex@v2 39 | env: 40 | # install full prebuilt version 41 | TINYTEX_INSTALLER: TinyTeX 42 | 43 | - uses: r-lib/actions/setup-r-dependencies@v2 44 | with: 45 | needs: deploy 46 | extra-packages: github::yihui/knitr 47 | 48 | - name: Install missing system dependencies 49 | if: runner.os == 'Linux' 50 | run: sudo apt-get install -y ghostscript 51 | 52 | - name: Cache bookdown results 53 | uses: actions/cache@v4 54 | with: 55 | path: _bookdown_files 56 | key: bookdown-${{ hashFiles('**/*Rmd') }} 57 | restore-keys: bookdown- 58 | 59 | - name: Build all book 60 | run: make all 61 | 62 | - name: Deploy to gh-pages for Connect Cloud deploy 63 | if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' 64 | uses: JamesIves/github-pages-deploy-action@v4 65 | with: 66 | branch: gh-pages 67 | folder: _book 68 | clean: true 69 | single-commit: true 70 | dry-run: ${{ (github.event_name == 'workflow_dispatch' && (github.event.inputs.publish == 'false' || github.event.inputs.publish == false)) || false }} 71 | 72 | - name: Upload book folder for debug 73 | if: failure() 74 | uses: actions/upload-artifact@main 75 | with: 76 | name: book-dir 77 | path: . 78 | -------------------------------------------------------------------------------- /00-author.Rmd: -------------------------------------------------------------------------------- 1 | # About the Authors {#author .unnumbered} 2 | 3 | This book is primarily put together by me (Yihui Xie), making use of the existing R documentation of the **rmarkdown** package and the **rmarkdown** website, which were mainly contributed by J.J. Allaire and Garrett Grolemund. 4 | 5 | ## Yihui Xie {-} 6 | 7 | Yihui Xie () is a software engineer at RStudio (). He earned his PhD from the Department of Statistics, Iowa State University. He is interested in interactive statistical graphics and statistical computing. As an active R user, he has authored several R packages, such as **knitr**, **bookdown**, **blogdown**, **xaringan**, **tinytex**, **animation**, **DT**, **tufte**, **formatR**, **fun**, **xfun**, **mime**, **highr**, **servr**, and **Rd2roxygen**, among which the **animation** package won the 2009 John M. Chambers Statistical Software Award (ASA). He also co-authored a few other R packages, including **shiny**, **rmarkdown**, and **leaflet**. 8 | 9 | He has authored two books, _Dynamic Documents with knitr_ [@xie2015], and _bookdown: Authoring Books and Technical Documents with R Markdown_ [@xie2016], and co-authored two book, _blogdown: Creating Websites with R Markdown_ [@xie2017], and _R Markdown: The Definitive Guide_ [@xie2018]. 10 | 11 | In 2006, he founded the Capital of Statistics (), which has grown into a large online community on statistics in China. He initiated the Chinese R conference in 2008, and has been involved in organizing R conferences in China since then. During his PhD training at Iowa State University, he won the Vince Sposito Statistical Computing Award (2011) and the Snedecor Award (2012) in the Department of Statistics. 12 | 13 | He occasionally rants on Twitter (https://twitter.com/xieyihui), and most of the time you can find him on GitHub (https://github.com/yihui). 14 | 15 | He enjoys spicy food as much as classical Chinese literature. 16 | 17 | ## J.J. Allaire {-} 18 | 19 | J.J. Allaire is the founder of RStudio and the creator of the RStudio IDE. J.J. is an author of several packages in the R Markdown ecosystem including **rmarkdown**, **flexdashboard**, **learnr**, and **radix**. 20 | 21 | ## Garrett Grolemund {-} 22 | 23 | Garrett Grolemund is the co-author of _R for Data Science_ and author of _Hands-On Programming with R_. He wrote the **lubridate** R package and works for RStudio as an advocate who trains engineers to do data science with R and the Tidyverse. If you use R yourself, you may recognize Garrett from his video courses on Datacamp.com and O'Reilly media, or for his series of popular R cheatsheets distributed by RStudio. 24 | 25 | Garrett earned his PhD in Statistics from Rice University in 2012 under the guidance of Hadley Wickham. Before that, he earned a Bachelor's degree in Psychology from Harvard University and briefly attended law school. Garrett has been one of the foremost promoters of Shiny, R Markdown, and the Tidyverse, documenting and explaining each in detail. 26 | -------------------------------------------------------------------------------- /book.bib: -------------------------------------------------------------------------------- 1 | @Book{xie2015, 2 | title = {Dynamic Documents with {R} and knitr}, 3 | author = {Yihui Xie}, 4 | publisher = {Chapman and Hall/CRC}, 5 | address = {Boca Raton, Florida}, 6 | year = {2015}, 7 | edition = {2nd}, 8 | note = {ISBN 978-1498716963}, 9 | url = {https://yihui.name/knitr/}, 10 | } 11 | @Book{xie2016, 12 | title = {bookdown: Authoring Books and Technical Documents with {R} Markdown}, 13 | author = {Yihui Xie}, 14 | publisher = {Chapman and Hall/CRC}, 15 | address = {Boca Raton, Florida}, 16 | year = {2016}, 17 | note = {ISBN 978-1138700109}, 18 | url = {https://github.com/rstudio/bookdown}, 19 | } 20 | @Book{xie2017, 21 | title = {blogdown: Creating Websites with {R} Markdown}, 22 | author = {Yihui Xie and Alison Presmanes Hill and Amber Thomas}, 23 | publisher = {Chapman and Hall/CRC}, 24 | address = {Boca Raton, Florida}, 25 | year = {2017}, 26 | note = {ISBN 978-0815363729}, 27 | url = {https://github.com/rstudio/blogdown}, 28 | } 29 | @Book{xie2018, 30 | title = {R Markdown: The Definitive Guide}, 31 | author = {Yihui Xie and J.J. Allaire and Garrett Grolemund}, 32 | publisher = {Chapman and Hall/CRC}, 33 | address = {Boca Raton, Florida}, 34 | year = {2018}, 35 | note = {ISBN 9781138359338}, 36 | url = {https://bookdown.org/yihui/rmarkdown}, 37 | } 38 | @Book{wickham2015, 39 | author = {Wickham, Hadley}, 40 | title = {R Packages}, 41 | year = {2015}, 42 | isbn = {1491910593, 9781491910597}, 43 | edition = {1st}, 44 | publisher = {O'Reilly Media, Inc.}, 45 | } 46 | @article{bion2018, 47 | author = {Ricardo Bion and Robert Chang and Jason Goodman}, 48 | title = {How R Helps Airbnb Make the Most of its Data}, 49 | journal = {The American Statistician}, 50 | volume = {72}, 51 | number = {1}, 52 | pages = {46-52}, 53 | year = {2018}, 54 | publisher = {Taylor \& Francis}, 55 | doi = {10.1080/00031305.2017.1392362}, 56 | URL = {https://doi.org/10.1080/00031305.2017.1392362}, 57 | eprint = {https://doi.org/10.1080/00031305.2017.1392362} 58 | } 59 | @article{knuth1984, 60 | title={Literate programming}, 61 | author={Knuth, Donald E.}, 62 | journal={The Computer Journal}, 63 | volume={27}, 64 | number={2}, 65 | pages={97--111}, 66 | year={1984}, 67 | publisher={British Computer Society} 68 | } 69 | @article{hartgerink2017, 70 | title={Too good to be false: Nonsignificant results revisited}, 71 | author={Hartgerink, Chris HJ and Wicherts, Jelte M and van Assen, Marcel ALM}, 72 | journal={Collabra: Psychology}, 73 | volume={3}, 74 | number={1}, 75 | year={2017}, 76 | publisher={The Regents of the University of California} 77 | } 78 | @article{lowndes2017, 79 | title={Our path to better science in less time using open data science tools}, 80 | author={Lowndes, Julia S Stewart and Best, Benjamin D and Scarborough, Courtney and Afflerbach, Jamie C and Frazier, Melanie R and O’Hara, Casey C and Jiang, Ning and Halpern, Benjamin S}, 81 | journal={Nature ecology \& evolution}, 82 | volume={1}, 83 | number={6}, 84 | year={2017}, 85 | publisher={Nature Publishing Group} 86 | } 87 | -------------------------------------------------------------------------------- /11-pkgdown.Rmd: -------------------------------------------------------------------------------- 1 | # HTML Documentation for R Packages {#pkgdown} 2 | 3 | R has a built-in HTML help system that can be accessed via `help.start()`. From this system, you can see the HTML help pages of functions and objects in all packages, as well as other information about packages such as the `DESCRIPTION` file and package vignettes. However, this system is usually dynamically launched (via a local web server), and it is not straightforward to turn it into a static website that can be viewed without starting R. 4 | 5 | The **pkgdown** package\index{pkgdown} [@R-pkgdown] makes it easy to build a documentation website for an R package, which can help you organize different pieces of the package documentation (e.g., README, help pages, vignettes, and news) with a more visually pleasant style. The navigation can also be easier for users than R's built-in help system. This website can be published to any web server (e.g., GitHub Pages or Netlify). An example is **pkgdown**'s own website: http://pkgdown.r-lib.org (see Figure \@ref(fig:pkgdown)). 6 | 7 | ```{r pkgdown, echo=FALSE, out.width='100%', fig.cap='A screenshot of the pkgdown website.'} 8 | knitr::include_graphics('images/pkgdown.png', dpi = NA) 9 | ``` 10 | 11 | ## Get started {#pkgdown-start} 12 | 13 | You can install **pkgdown** from CRAN, or its development version from GitHub, and find more information from its GitHub repository (https://github.com/r-lib/pkgdown). 14 | 15 | ```r 16 | install.packages("pkgdown") 17 | 18 | # Or the development version 19 | devtools::install_github("r-lib/pkgdown") 20 | ``` 21 | 22 | After it is installed, you can call the function `pkgdown::build_site()` in the root directory of your source package. It will build a website to the `docs/` directory, which can be turned into an online website via [GitHub Pages](https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/) or Netlify. 23 | 24 | ## Components {#pkgdown-components} 25 | 26 | A **pkgdown** website consists of these components: the home page, function reference, articles, news, and the navigation bar. You may configure these components via a file `_pkgdown.yml`. 27 | 28 | ### Home page 29 | 30 | The home page is generated from the first existing file of the following files in your source package: 31 | 32 | - `index.Rmd` 33 | - `README.Rmd` 34 | - `index.md` 35 | - `README.md` 36 | 37 | Other meta information about the package, such as the package license and author names, will be displayed automatically as a sidebar on the home page. 38 | 39 | ### Function reference 40 | 41 | The reference pages look like R's own help pages. In fact, these pages are generated from the `*.Rd` files under `man/`. Compared to R's own help pages, **pkgdown** offers a few more benefits: the examples on a help page (if they exist) will be evaluated so that you can see the output, and function names are automatically linked so you can click on a name to navigate to the help page of another function. What is more, **pkgdown** allows you to organize the list of all functions into groups (e.g., by topic), which can make it easier for users to find the right function in a list. By default, all functions are listed alphabetically just like R's help system. To group functions on the list page, you need to provide a `reference` key in `_pkgdown.yml`, e.g., 42 | 43 | ```yaml 44 | reference: 45 | - title: "One Topic" 46 | desc: "These functions are awesome..." 47 | contents: 48 | - awesome_a 49 | - awesome_b 50 | - cool_c 51 | - title: "Another Topic" 52 | desc: "These functions are boring..." 53 | contents: 54 | - starts_with("boring_") 55 | - ugh_oh 56 | ``` 57 | 58 | As you can see from the above example, you may list the names of functions in the `contents` field, or provide a pattern to let **pkgdown** match the names. There are three ways to match function names: `starts_with()` to match names that start with a string, `ends_width()` for an ending pattern, and `matches()` for an arbitrary regular expression. 59 | 60 | ### Articles 61 | 62 | Package vignettes in the R Markdown format under the `vignettes/` directories will be built as "articles" for a **pkgdown**-based website. Note that Rmd files under subdirectories will also be built. The list of articles will be displayed as a drop-down menu in the navigation bar. 63 | 64 | If you have a vignette that has the same base name as the package name (e.g., a vignette `foo.Rmd` in a package **foo**), it will be displayed as the "Get started" menu item in the navigation bar. 65 | 66 | ### News 67 | 68 | If the source package has a news file `NEWS.md`, it will be parsed and rendered to HTML pages that can be accessed via the "Changelog" menu in the navigation bar. 69 | 70 | ### Navigation bar 71 | 72 | The navigation bar in **pkgdown** is based on the **rmarkdown** site generator. You can learn how to customize it from Section \@ref(site-navigation), if you are not satisfied by the default navigation bar. Please note that you need to specify the `navbar` field in `_pkgdown.yml` instead of `_site.yml`. 73 | -------------------------------------------------------------------------------- /18-new-formats.Rmd: -------------------------------------------------------------------------------- 1 | # Creating New Formats {#new-formats} 2 | 3 | The **rmarkdown** package has included many built-in document and presentation formats. At their core, these formats are just R functions. When you include an output format in the YAML metadata of a document, you are essentially specifying the format function to call and the parameters to pass to it. 4 | 5 | We can create new formats for R Markdown, which makes it easy to customize output formats to use specific options or refer to external files. Defining a new function can be particularly beneficial if you have generated a new template as described in Chapter \@ref(document-templates), as it allows you to use your custom templates without having to copy any files to your local directory. 6 | 7 | ## Deriving from built-in formats {#format-derive} 8 | 9 | The easiest way to create a new format is to write a function that calls one of the built-in formats. These built-in formats are designed to be extensible enough to serve as the foundation of custom formats. The following example, `quarterly_report`, is based on `html_document` but alters the default options: 10 | 11 | ```{r, eval=FALSE, tidy=FALSE} 12 | quarterly_report = function(toc = TRUE) { 13 | # locations of resource files in the package 14 | pkg_resource = function(...) { 15 | system.file(..., package = "mypackage") 16 | } 17 | 18 | css = pkg_resource("reports/styles.css") 19 | header = pkg_resource("reports/quarterly/header.html") 20 | 21 | # call the base html_document function 22 | rmarkdown::html_document( 23 | toc = toc, fig_width = 6.5, fig_height = 4, 24 | theme = NULL, css = css, 25 | includes = rmarkdown::includes(before_body = header) 26 | ) 27 | } 28 | ``` 29 | 30 | The new format defined has the following behavior: 31 | 32 | 1. Provides an option to determine whether a table of contents should be generated (implemented by passing `toc` through to the base format). 33 | 34 | 2. Sets a default height and width for figures (note that this is intentionally not user-customizable so as to encourage a standard for all reports of this type). 35 | 36 | 3. Disables the default Bootstrap theme and provides custom CSS in its place. 37 | 38 | 4. Adds a standard header to every document. 39 | 40 | Note that (3) and (4) are implemented using external files that are stored within the package that defines the custom format, so their locations need to be looked up using the `system.file()` function. 41 | 42 | ## Fully custom formats {#format-custom} 43 | 44 | Another lower-level approach is to define a format directly by explicitly specifying **knitr** options and Pandoc command-line arguments. At its core, an R Markdown format consists of: 45 | 46 | 1. A set of **knitr** options that govern how Rmd is converted to Markdown. 47 | 48 | 2. A set of Pandoc options that govern how Markdown is converted to the final output format (e.g., HTML). 49 | 50 | 3. Some optional flags and filters (typically used to control handling of supporting files). 51 | 52 | You can create a new format using the `output_format()` function in **rmarkdown**. Here is an example of a simple format definition: 53 | 54 | ```{r, eval=FALSE, tidy=FALSE} 55 | #' @importFrom rmarkdown output_format knitr_options pandoc_options 56 | simple_html_format = function() { 57 | # if you don't use roxygen2 (see above), you need to either 58 | # library(rmarkdown) or use rmarkdown:: 59 | output_format( 60 | knitr = knitr_options(opts_chunk = list(dev = 'png')), 61 | pandoc = pandoc_options(to = "html"), 62 | clean_supporting = FALSE 63 | ) 64 | } 65 | ``` 66 | 67 | The **knitr** and Pandoc options can get considerably complicated (see help pages `?rmarkdown::knitr_options` and `?rmarkdown::pandoc_options` for details). The `clean_supporting` option indicates that you are not creating self-contained output (like a PDF or HTML document with base64 encoded resources), and therefore want to preserve supporting files like R plots generated during knitting. 68 | 69 | You can also pass a `base_format` to the `output_format()` function if you want to inherit all of the behavior of an existing format but tweak a subset of its options. 70 | 71 | If there are supporting files required for your format that cannot be easily handled by the `includes` option (see Section \@ref(includes)), you will also need to use the other arguments to `output_format` to ensure they are handled correctly (e.g., use the `intermediates_generator` to copy them into the place alongside the generated document). 72 | 73 | The best way to learn more about creating fully custom formats is to study the source code of the existing built-in formats (e.g., `html_document` and `pdf_document`): https://github.com/rstudio/rmarkdown/tree/master/R. In some cases, a custom format will define its own Pandoc template, which was discussed in Section \@ref(template-pandoc). 74 | 75 | ## Using a new format {#format-use} 76 | 77 | New formats should be stored within a package and installed onto your local system. This allows the format to be provided to the document YAML. Assuming our example format `quarterly_report` is in a package named **mypackage**, we can use it as follows: 78 | 79 | ```markdown 80 | --- 81 | title: "Habits" 82 | output: 83 | mypackage::quarterly_report: 84 | toc: true 85 | --- 86 | ``` 87 | 88 | This means to use the `quarterly_report()` function defined in **mypackage** as the output format, and to pass `toc = TRUE` as a parameter to the function. 89 | -------------------------------------------------------------------------------- /09-community.Rmd: -------------------------------------------------------------------------------- 1 | # Community Formats {#community} 2 | 3 | Most output formats introduced in this book are created and maintained by the RStudio team. In fact, other members in the R community have also created a number of R Markdown output formats.\index{output formats} We mention those formats that we are aware of in this chapter. If you have developed or know other formats, please feel free to suggest that we add them to the page https://rmarkdown.rstudio.com/formats.html. 4 | 5 | ## Lightweight Pretty HTML Documents {#prettydoc} 6 | 7 | When designing the **rmarkdown** package, we wished it could produce output documents that look pleasant by default, especially for HTML documents. Pandoc does not really style the HTML documents when converting Markdown to HTML, but **rmarkdown** does. As we mentioned in Section \@ref(appearance-and-style), the themes of HTML documents are based on Bootswatch, which actually relies on the Bootstrap library (https://getbootstrap.com). Although these themes look pretty, the major disadvantage is that their file sizes are relatively large. The size of an HTML document created from an empty R Markdown document with the `html_document` format is about 600Kb, which is roughly the total size of all CSS, JavaScript, and font files in the default theme. 8 | 9 | If you are concerned about the file size but still want a fancy theme, you may consider the **prettydoc** package [@R-prettydoc], which has bundled a few pretty themes (yet small in size). This package provides an output format `prettydoc::html_pretty`. An empty R Markdown document with this format generates an HTML file of about 70Kb. 10 | 11 | ### Usage {#prettydoc-usage} 12 | 13 | The usage of `prettydoc::html_pretty` is very similar to `html_document`, with two major differences: 14 | 15 | - The `theme` option takes different values. The currently supported themes are `"cayman"`, `"tactile"`, `"architect"`, `"leonids"`, and `"hpstr"`. Figure \@ref(fig:prettydoc) shows the appearance of the `leonids` theme. See https://github.com/yixuan/prettydoc for screenshots of more themes. 16 | 17 | - The `highlight` option takes `null`, `"github"`, or `"vignette"`. 18 | 19 | Below is an example of the YAML metadata of an R Markdown document that uses the `prettydoc::html_pretty` output format: 20 | 21 | ```yaml 22 | --- 23 | title: "Your Document Title" 24 | author: "Document Author" 25 | date: "2018-04-16" 26 | output: 27 | prettydoc::html_pretty: 28 | theme: leonids 29 | highlight: github 30 | --- 31 | ``` 32 | 33 | ```{r prettydoc, echo=FALSE, fig.cap='The leonids theme of the prettydoc package.', out.width='100%'} 34 | knitr::include_graphics('images/prettydoc.png', dpi = NA) 35 | ``` 36 | 37 | ### Package vignettes {#prettydoc-vignettes} 38 | 39 | The `prettydoc::html_pretty` can be particularly useful for R package vignettes.\index{R package vignette} We have mentioned the `html_vignette` format in Section \@ref(r-package-vignette) that also aims at smaller file sizes, but that format is not as stylish. To apply the `prettydoc::html_pretty` format to a package vignette, you may use the YAML metadata below: 40 | 41 | ```yaml 42 | --- 43 | title: "Vignette Title" 44 | author: "Vignette Author" 45 | output: prettydoc::html_pretty 46 | vignette: > 47 | %\VignetteIndexEntry{Vignette Title} 48 | %\VignetteEngine{knitr::rmarkdown} 49 | %\VignetteEncoding{UTF-8} 50 | --- 51 | ``` 52 | 53 | Do not forget to change the vignette title, author, and the index entry. You should also add `prettydoc` to the `Suggests` field of your package `DESCRIPTION` file, and the two package names `knitr, rmarkdown` to the `VignetteBuilder` field. 54 | 55 | ## The rmdformats package {#rmdformats} 56 | 57 | The **rmdformats** package [@R-rmdformats] provides several HTML output formats of unique and attractive styles, including: 58 | 59 | - `material`: A format based on the [Material design theme for Bootstrap 3](https://github.com/FezVrasta/bootstrap-material-design). With this format, every first-level section will become a separate page. See Figure \@ref(fig:rmdformats-material) for what this format looks like ("Introduction" and "Including Plots" are two first-level sections). 60 | 61 | - `readthedown`: It features a sidebar layout. The table of contents is displayed in the sidebar on the left. As you scroll on the page, the current section header will be automatically highlighted (and expanded if necessary) in the sidebar. 62 | 63 | - `html_clean`: A simple and clean HTML template, with a dynamic table of contents at the top-right of the page. 64 | 65 | - `html_docco`: A simple template inspired by [the Docco project](https://github.com/jashkenas/docco). 66 | 67 | Do not forget the `rmdformats::` prefix when you use these formats, e.g., 68 | 69 | ```yaml 70 | --- 71 | output: rmdformats::material 72 | --- 73 | ``` 74 | 75 | ```{r rmdformats-material, echo=FALSE, fig.cap='The Material Design theme in the rmdformats package.', out.width='100%'} 76 | knitr::include_graphics('images/rmdformats-material.png', dpi = NA) 77 | ``` 78 | 79 | These output formats have some additional features such as responsiveness and code folding. Please refer to the GitHub repository of the **rmdformats** package for more information: https://github.com/juba/rmdformats. 80 | 81 | ## Shower presentations 82 | 83 | Shower (https://github.com/shower/shower) is a popular and customizable HTML5 presentation\index{HTML5 slides} framework. See Figure \@ref(fig:shower) for what it looks like. 84 | 85 | ```{r shower, echo=FALSE, fig.cap='A few sample slides created via the Shower presentation framework.', out.width='100%'} 86 | knitr::include_graphics('images/shower.png', dpi = NA) 87 | ``` 88 | 89 | The R package **rmdshower** (https://github.com/mangothecat/rmdshower) is built on top of Shower. You may install it from GitHub: 90 | 91 | ```{r eval=FALSE} 92 | devtools::install_github("mangothecat/rmdshower") 93 | ``` 94 | 95 | You can create a Shower presentation with the output format `rmdshower::shower_presentation`, e.g., 96 | 97 | ```yaml 98 | --- 99 | title: "Hello Shower" 100 | author: "John Doe" 101 | output: rmdshower::shower_presentation 102 | --- 103 | ``` 104 | 105 | See the help page `?rmdshower::shower_presentation` for all possible options of this format. 106 | -------------------------------------------------------------------------------- /13-rticles.Rmd: -------------------------------------------------------------------------------- 1 | # Journals 2 | 3 | Academic journals often have strict guidelines on the formatting for submitted articles. As of today, few journals directly support R Markdown submissions, but many support the LaTeX\index{LaTeX} format. While you can convert R Markdown to LaTeX (see Section \@ref(pdf-document)), different journals have different typesetting requirements and LaTeX styles, and it may be slow and frustrating for all authors who want to use R Markdown to figure out the technical details about how to properly convert a paper based on R Markdown to a LaTeX document that meets the journal requirements. 4 | 5 | The **rticles** package [@R-rticles]\index{rticles} is designed to simplify the creation of documents that conform to submission standards. A suite of custom R Markdown templates for popular journals is provided by the package such as those shown in Figure \@ref(rticles-templates). 6 | 7 | (ref:rticles-templates) Two journal templates in the **rticles** package (PLOS and Springer). 8 | 9 | ```{r rticles-templates, echo=FALSE, out.width="100%", fig.cap="(ref:rticles-templates)", fig.show='hold'} 10 | knitr::include_graphics(c("images/rticles-plos.png", "images/rticles-springer.png"), dpi = NA) 11 | ``` 12 | 13 | Understanding of LaTeX is recommended, but not essential, to use this package. R Markdown templates may sometimes inevitably contain LaTeX code, but usually we can use the simpler Markdown and **knitr** syntax to produce elements like figures, tables, and math equations as explained in Chapter \@ref(basics). 14 | 15 | ## Get started {#rticles-start} 16 | 17 | You can install and use **rticles** from CRAN as follows: 18 | 19 | ```{r, eval = FALSE} 20 | # Install from CRAN 21 | install.packages("rticles") 22 | 23 | # Or install development version from GitHub 24 | devtools::install_github("rstudio/rticles") 25 | ``` 26 | 27 | We would recommend the development version of the package from GitHub, as it contains the most up-to-date versions along with several new templates. 28 | 29 | If you are using RStudio, you can easily access the templates through `File -> New File -> R Markdown`. This will open the dialog box where you can select from one of the available templates as shown in Figure \@ref(fig:rticles-setup). 30 | 31 | (ref:rticles-setup) The R Markdown template window in RStudio showing available **rticles** templates. 32 | 33 | ```{r rticles-setup, echo=FALSE, fig.cap="(ref:rticles-setup)", out.width='100%'} 34 | knitr::include_graphics("images/rticles-templates.png", dpi = NA) 35 | ``` 36 | 37 | If you are using the command line, you can use the `rmarkdown::draft()` function, which requires you to specify a template using the journal short name, e.g., 38 | 39 | ```r 40 | rmarkdown::draft( 41 | "MyJSSArticle.Rmd", template = "jss", package = "rticles" 42 | ) 43 | ``` 44 | 45 | ## rticles templates 46 | 47 | The **rticles** package provides templates for various journals and publishers, including: 48 | 49 | - JSS articles (Journal of Statistical Software) 50 | - R Journal articles 51 | - CTeX documents 52 | - ACM articles (Association of Computing Machinery) 53 | - ACS articles (American Chemical Society) 54 | - AMS articles (American Meteorological Society) 55 | - PeerJ articles 56 | - Elsevier journal submissions 57 | - AEA journal submissions (American Economic Association) 58 | - IEEE Transaction journal submissions 59 | - Statistics in Medicine journal submissions 60 | - Royal Society Open Science journal submissions 61 | - Bulletin de l'AMQ journal submissions 62 | - MDPI journal submissions 63 | - Springer journal submissions 64 | 65 | The full list is available within the R Markdown templates window in RStudio, or through the function `rticles::journals()`: 66 | 67 | ```{r} 68 | rticles::journals() 69 | ``` 70 | 71 | ## Using a template {#rticles-usage} 72 | 73 | Templates have an extended YAML section compared to the basic R Markdown template, which allows you to specify additional details relevant to the custom template. Below is an example of the YAML section for the *Springer* template: 74 | 75 | ```yaml 76 | title: Title here 77 | subtitle: Do you have a subtitle? If so, write it here 78 | titlerunning: Short form of title (if too long for head) 79 | authorrunning: 80 | Short form of author list if too long for running head 81 | thanks: | 82 | Grants or other notes about the article that should go 83 | on the front page should be placed here. General 84 | acknowledgments should be placed at the end of the article. 85 | authors: 86 | - name: Author 1 87 | address: Department of YYY, University of XXX 88 | email: abc@def 89 | - name: Author 2 90 | address: Department of ZZZ, University of WWW 91 | email: djf@wef 92 | keywords: 93 | - key 94 | - dictionary 95 | - word 96 | MSC: 97 | - MSC code 1 98 | - MSC code 2 99 | abstract: | 100 | The text of your abstract. 150 -- 250 words. 101 | bibliography: bibliography.bib 102 | output: rticles::springer_article 103 | ``` 104 | 105 | As the Rmd documents are built using customized templates, you may not be able to use the YAML metadata to control the layout of the document as described in Section \@ref(pdf-document), unless the template supports such metadata. For example, adding `toc: true` may not add a table of contents. Commands that control the building process may still be used though, including `keep_tex: true`, or those that configure **knitr** chunk options (e.g., `fig_width`). 106 | 107 | ## LaTeX content {#rticles-latex} 108 | 109 | As the only output format of the **rticles** formats is PDF, the content of the documents may include raw LaTeX formatting. This means you may use LaTeX to produce figures and tables (if you have to), e.g., 110 | 111 | ```latex 112 | \begin{figure}[ht] 113 | \centering 114 | \includegraphics[width=\linewidth]{foo} 115 | \caption{An example image.} 116 | \label{fig:foo} 117 | \end{figure} 118 | ``` 119 | 120 | Unless you have specific requirements for using LaTeX, we recommend that you use the R Markdown syntax. This keeps you work generally more readable (in terms of the source document), and less prone to formatting errors. For example, the above code block would be better represented as: 121 | 122 | ````markdown 123 | `r ''````{r foo, out.width="100%", fig.cap="An example image."} 124 | knitr::include_graphics("foo.png") 125 | ``` 126 | ```` 127 | 128 | ## Linking with bookdown {#rticles-bookdown} 129 | 130 | As explained in Section \@ref(bookdown-markdown), **bookdown**\index{bookdown} offers several extensions to the Markdown syntax, which can be particularly useful for academic writing, including cross-referencing of figures and tables. All **rticles** output formats are based on `rmarkdown::pdf_document`, and we can use them as the "base formats" for `bookdown::pdf_book`, e.g., 131 | 132 | ```yaml 133 | output: 134 | bookdown::pdf_book: 135 | base_format: rticles::peerj_article 136 | ``` 137 | 138 | You can substitute `rticles::peerj_article` with the template you actually intend to use. 139 | 140 | ## Contributing templates {#rticles-contrib} 141 | 142 | If you take a look at the GitHub repository of **rticles** (https://github.com/rstudio/rticles), you will see that a lot of the templates have been contributed by the R community. If you are interested in improving them or adding more journal templates, you may want to read Chapter \@ref(document-templates), which outlines how a template can be made for R Markdown. Basically these templates are defined to translate the Pandoc variables from the YAML frontmatter and the body of the R Markdown document into LaTeX. 143 | -------------------------------------------------------------------------------- /17-templates.Rmd: -------------------------------------------------------------------------------- 1 | # Document Templates {#document-templates} 2 | 3 | When you create a new R Markdown document from the RStudio menu `File -> New File -> R Markdown`, you will see a default example document (a template) in the RStudio editor. In fact, you can create custom document templates by yourself, which can be useful if you need to create a particular type of document frequently or want to customize the appearance of the final report. The **rticles** package in Chapter \@ref(journals) is a good example of custom templates for a range of journals. Some additional examples of where a template could be used include: 4 | 5 | - Creating a company branded R Markdown template that includes a logo and branding colors. 6 | 7 | - Updating the default YAML settings to include standard fields for `title`, `author`, `date`, or default `output` options. 8 | 9 | - Customizing the layout of the output document by adding additional fields to the YAML metadata. For example, you can add a `department` field to be included within your title page. 10 | 11 | Once created, templates are easily accessed within RStudio, and will appear within the "New R Markdown" window as shown in Figure \@ref(fig:templates-select). 12 | 13 | ```{r templates-select, echo=FALSE, fig.cap="Selecting R Markdown templates within RStudio.", out.width='100%'} 14 | knitr::include_graphics("images/templates-select.png", dpi = NA) 15 | ``` 16 | 17 | This chapter explains how to create templates and share them within an R package. If you would like to see some real-world examples, you may check out the source package of **rticles** (https://github.com/rstudio/rticles). The `rmarkdown::html_vignette` format is also a relatively simple example (see both its R source code and [the template structure](https://github.com/rstudio/rmarkdown/tree/master/inst/rmarkdown/templates/html_vignette)). In addition, Michael Harper has kindly prepared more examples in the repository https://github.com/dr-harper/example-rmd-templates. 18 | 19 | ## Template structure {#template-structure} 20 | 21 | R Markdown templates should be contained within an R package, which can be easily created from the menu `File -> New Project` in RStudio (choose the project type to be "R Package"). If you are already familiar with creating R packages, you are certainly free to use your own favorite way to create a new package. 22 | 23 | Templates are located within the `inst/rmarkdown/templates` directory of a package. This structure can be generated automatically with the [`use_rmarkdown_template()`](https://usethis.r-lib.org/reference/use_rmarkdown_template.html) function from the **usethis** package. It is possible to contain multiple templates in a single package, with each template stored in a separate sub-directory. As a minimal example, `inst/rmarkdown/templates/my_template` requires the following files: 24 | 25 | ```markdown 26 | template.yaml 27 | skeleton/skeleton.Rmd 28 | ``` 29 | 30 | The `template.yaml` specifies how the template is displayed within the RStudio "From Template" dialog box. This YAML file must have a `name` and a `description` field. You can optionally specify `create_dir: true` if you want a new directory to be created when the template is selected. As an example of the `template.yaml` file: 31 | 32 | ```yaml 33 | name: My Template 34 | description: This is my template 35 | ``` 36 | 37 | You can provide a brief example R Markdown document in `skeleton.Rmd`, which will be opened in RStudio when the template is selected. We can add section titles, load commonly used packages, or specify default YAML parameters in this skeleton document. In the following example, we specify the default output format to `bookdown::html_document2`, and select a default template `flatly`: 38 | 39 | ```yaml 40 | --- 41 | title: "Untitled" 42 | author: "Your Name" 43 | output: 44 | bookdown::html_document2: 45 | toc: true 46 | fig_caption: true 47 | template: flatly 48 | --- 49 | 50 | ## Introduction 51 | 52 | ## Analysis 53 | 54 | ## Conclusions 55 | ``` 56 | 57 | ## Supporting files {#template-support} 58 | 59 | Sometimes a template may require supporting files (e.g., images, CSS files, or LaTeX style files). Such files should be placed in the `skeleton` directory. They will be automatically copied to the directory where the new document is created. For example, if your template requires a logo and CSS style sheet, they can be put under the directory `inst/rmarkdown/templates/my_template`: 60 | 61 | ```markdown 62 | template.yaml 63 | skeleton/skeleton.Rmd 64 | skeleton/logo.png 65 | skeleton/styles.css 66 | ``` 67 | 68 | We can refer to these files within the `skeleton.Rmd` file, e.g., 69 | 70 | ````markdown 71 | --- 72 | title: "Untitled" 73 | author: "Your Name" 74 | output: 75 | html_document: 76 | css: styles.css 77 | --- 78 | 79 | ![logo](logo.png) 80 | 81 | # Introduction 82 | 83 | # Analysis 84 | 85 | `r ''````{r} 86 | knitr::kable(mtcars[1:5, 1:5]) 87 | ``` 88 | 89 | # Conclusion 90 | ```` 91 | 92 | ## Custom Pandoc templates {#template-pandoc} 93 | 94 | An R Markdown is first compiled to Markdown through **knitr**, and then converted to an output document (e.g., PDF, HTML, or Word) by Pandoc through a Pandoc template. While the default Pandoc templates used by R Markdown are designed to be flexible by allowing parameters to be specified in the YAML, users may wish to provide their own template for more control over the output format. 95 | 96 | You can make use of additional YAML fields from the source document when designing a Pandoc template\index{Pandoc template}. For example, you may wish to have a `department` field to be added to your title page, or include an `editor` field to be displayed below the author. We can add additional variables to the Pandoc template by surrounding the variable in dollar signs (`$`) within the template. Most variables take values from the YAML metadata of the R Markdown document (or command-line arguments passed to Pandoc). We may also use conditional statements and for-loops. Readers are recommended to check the Pandoc manual for more details: https://pandoc.org/MANUAL.html#using-variables-in-templates. Below is an example of a very minimal Pandoc template for HTML documents that only contains two variables (`$title$` and `$body$`): 97 | 98 | ```html 99 | 100 | 101 | $title$ 102 | 103 | 104 | 105 | $body$ 106 | 107 | 108 | ``` 109 | 110 | For R Markdown to use the customized template, you can specify the `template` option in the output format (provided that the output format supports this option), e.g., 111 | 112 | ```yaml 113 | output: 114 | html_document: 115 | template: template.html 116 | ``` 117 | 118 | If you wish to design your own template, we recommend starting from the default Pandoc templates included within the **rmarkdown** package (https://github.com/rstudio/rmarkdown/tree/master/inst/rmd) or Pandoc's built-in templates (https://github.com/jgm/pandoc-templates). 119 | 120 | ## Sharing your templates {#template-share} 121 | 122 | As templates are stored within packages, it is easy to distribute them to other users. The most common and recommended way is to publish such packages to CRAN. If you decide not to take this way, you may also consider using GitHub to host your package instead, in which case users can also easily install your package and templates: 123 | 124 | ```{r, eval=FALSE} 125 | if (!requireNamespace("devtools")) install.packages("devtools") 126 | devtools::install_github("username/packagename") 127 | ``` 128 | 129 | To find out more about packages and the use of GitHub, you may refer to the book "*R Packages*" [@wickham2015] (http://r-pkgs.had.co.nz/git.html). 130 | 131 | If you need some inspiration, there are many examples on CRAN and GitHub providing document templates, such as **tufte** (Chapter \@ref(tufte-handouts)), **prettydoc** (Section \@ref(prettydoc)), **rticles** (Chapter \@ref(journals)), [**memor**,](https://github.com/hebrewseniorlife/memor) and [**rtemps**,](https://github.com/bblodfon/rtemps) etc. 132 | -------------------------------------------------------------------------------- /15-parameterized.Rmd: -------------------------------------------------------------------------------- 1 | # (PART) Other Topics {-} 2 | 3 | # Parameterized reports 4 | 5 | One of the many benefits of working with R Markdown is that you can reproduce analysis at the click of a button. This makes it very easy to update any work and alter any input parameters within the report. Parameterized reports\index{parameterized reports} extend this one step further, and allow users to specify one or more parameters to customize the analysis. This is useful if you want to create a report template that can be reused across multiple similar scenarios. Examples may include: 6 | 7 | - Showing results for a specific geographic location. 8 | 9 | - Running a report that covers a specific time period. 10 | 11 | - Running a single analysis multiple times for different assumptions. 12 | 13 | - Controlling the behavior of **knitr** (e.g., specify if you want the code to be displayed or not). 14 | 15 | In this chapter, we discuss the use of parameterized reports, and explain how we can interactively define the parameters to compile the results. 16 | 17 | ## Declaring parameters {#params-declare} 18 | 19 | Parameters are specified using the `params` field within the YAML section. We can specify one or more parameters with each item on a new line. As an example: 20 | 21 | ```yaml 22 | --- 23 | title: My Document 24 | output: html_document 25 | params: 26 | year: 2018 27 | region: Europe 28 | printcode: TRUE 29 | data: file.csv 30 | --- 31 | ``` 32 | 33 | All standard R types that can be parsed by `yaml::yaml.load()` can be included as parameters, including `character`, `numeric`, `integer`, and `logical` types. We can also use R objects by including `!r` before R expressions. For example, we could include the current date with the following R code: 34 | 35 | ```yaml 36 | --- 37 | title: My Document 38 | output: html_document 39 | params: 40 | date: !r Sys.Date() 41 | --- 42 | ``` 43 | 44 | Any R expressions included within the parameters are executed before any code in the document, therefore any package dependencies must be explicitly stated using the `package::function` notation (e.g., `!r lubridate::today()`), even if the package is loaded later in the Rmd document. 45 | 46 | ## Using parameters {#params-use} 47 | 48 | You can access the parameters within the knitting environment and the R console in RStudio.^[Parameters will not be available immediately after loading the file, but require any line of the report to be executed first.] The values are contained within a read-only list called `params`. In the previous example, the parameters can be accessed as follows: 49 | 50 | ```r 51 | params$year 52 | params$region 53 | ``` 54 | 55 | Parameters can also be used to control the behavior of **knitr**. For example, the **knitr** chunk option `echo` controls whether to display the program code, and we can set this option globally in a document via a parameter: 56 | 57 | ````markdown 58 | --- 59 | params: 60 | printcode: false # or set it to true 61 | --- 62 | 63 | `r ''````{r, setup, include=FALSE} 64 | # set this option in the first code chunk in the document 65 | knitr::opts_chunk$set(echo = params$printcode) 66 | ``` 67 | ```` 68 | 69 | ## Knitting with parameters {#params-knit} 70 | 71 | There are three ways in which a parameterized report can be knitted: 72 | 73 | - Using the `Knit` button within RStudio. 74 | 75 | - `rmarkdown::render()` with the `params` argument. 76 | 77 | - Using an interactive user interface to input parameter values. 78 | 79 | ### The `Knit` button 80 | 81 | By using the `Knit` button in RStudio or calling `rmarkdown::render()` function, the default values listed in the YAML metadata (if specified) will be used. 82 | 83 | ### Knit with custom parameters 84 | 85 | Even if your document has the `params` field in the YAML metadata, you can actually override it by providing a custom list of parameter values to the function `rmarkdown::render()`. For example: 86 | 87 | ```{r, eval=FALSE, tidy=FALSE} 88 | rmarkdown::render("MyDocument.Rmd", params = list( 89 | year = 2017, 90 | region = "Asia", 91 | printcode = FALSE, 92 | file = "file2.csv" 93 | )) 94 | ``` 95 | 96 | We do not have to explicitly state all parameters in the `params` argument. Any parameters not specified will default to the values specified in the YAML metadata. For example, this will only override the `region` parameter: 97 | 98 | ```{r, eval=FALSE, tidy=FALSE} 99 | rmarkdown::render("MyDocument.Rmd", params = list( 100 | region = "Asia" 101 | )) 102 | ``` 103 | 104 | You may want to integrate these changes into a function. Such a function could also be used to create an output file with a different filename for each of the different combination of parameters. In the following example, a new file `Report-region-year.pdf` is created for each set of parameters: 105 | 106 | ```{r, eval=FALSE, tidy=FALSE} 107 | render_report = function(region, year) { 108 | rmarkdown::render( 109 | "MyDocument.Rmd", params = list( 110 | region = region, 111 | year = year 112 | ), 113 | output_file = paste0("Report-", region, "-", year, ".pdf") 114 | ) 115 | } 116 | ``` 117 | 118 | ### The interactive user interface 119 | 120 | We can use a graphical user interface (GUI) based on Shiny to interactively input the parameters of a report. The user interface can be called by either `rmarkdown::render("MyDocument.Rmd", params = "ask")` or clicking the drop-down menu behind the `Knit` button and choosing `Knit with Parameters` in RStudio. Figure \@ref(fig:params-input) shows the GUI of **rmarkdown** asking for inputting parameters. 121 | 122 | ```{r params-input, echo=FALSE, fig.cap="Input parameter values interactively for parameterized reports.", out.width="100%"} 123 | knitr::include_graphics("images/params-input.png", dpi = NA) 124 | ``` 125 | 126 | The input controls for different types of parameters can be customized by specifying additional sub-items within the parameter specification in YAML. For example, sliders, check boxes, and text input boxes can all be used for input controls. 127 | 128 | In addition, we can also specify constraints of the values allowed in each parameter. For example, we may only want our model to be run for years between 2010 and 2018. This is particularly beneficial if you would like other users to interact with the report, as it prevents users from attempting to run reports outside of the designed limits. 129 | 130 | Adapting our above example to include some settings: 131 | 132 | ```yaml 133 | --- 134 | title: My Document 135 | output: html_document 136 | params: 137 | year: 138 | label: "Year" 139 | value: 2017 140 | input: slider 141 | min: 2010 142 | max: 2018 143 | step: 1 144 | sep: "" 145 | region: 146 | label: "Region:" 147 | value: Europe 148 | input: select 149 | choices: [North America, Europe, Asia, Africa] 150 | printcode: 151 | label: "Display Code:" 152 | value: TRUE 153 | data: 154 | label: "Input dataset:" 155 | value: results.csv 156 | input: file 157 | --- 158 | ``` 159 | 160 | This results in the user interface for the parameters as shown in Figure \@ref(fig:params-controls). 161 | 162 | ```{r params-controls, echo=FALSE, fig.cap="Custom controls for parameters.", out.width="100%"} 163 | knitr::include_graphics("images/params-controls.png", dpi = NA) 164 | ``` 165 | 166 | The type of Shiny control used is controlled by the `input` field. Table \@ref(tab:params-types) shows the input types currently supported (see the help page for the associated Shiny function for additional attributes that can be specified to customize the input, e.g., `?shiny::checkboxInput`). 167 | 168 | ```{r, params-types, echo=FALSE} 169 | knitr::kable( 170 | read.table( 171 | text = "checkbox checkboxInput 172 | numeric numericInput 173 | slider sliderInput 174 | date dateInput 175 | text textInput 176 | file fileInput 177 | radio radioButtons 178 | select selectInput 179 | password passwordInput", 180 | col.names = c("Input Type", "Shiny Function"), 181 | check.names = FALSE 182 | ), 183 | caption = "Possible input types and the associated Shiny functions for parameterized reports.", 184 | booktabs = TRUE 185 | ) 186 | ``` 187 | 188 | ## Publishing {#params-publish} 189 | 190 | Parameterized reports are supported by the publishing platform RStudio Connect (https://www.rstudio.com/products/connect/). If you publish a parameterized report to an RStudio Connect server, you will be able to compile reports by interactively choosing different parameter values on the server, and easily store/navigate through different reports built previously. You may watch a video demonstration at https://bit.ly/rsc-params. 191 | -------------------------------------------------------------------------------- /08-revealjs.Rmd: -------------------------------------------------------------------------------- 1 | # reveal.js Presentations {#revealjs} 2 | 3 | The **revealjs** package [@R-revealjs] provides an output format `revealjs::revealjs_presentation` that can be used to create yet another style of HTML5 slides\index{HTML5 slides} based on the JavaScript library [reveal.js](https://revealjs.com). You may install the R package from CRAN: 4 | 5 | ```r 6 | install.packages("revealjs") 7 | ``` 8 | 9 | To create a reveal.js presentation from R Markdown, you specify the `revealjs_presentation` output format in the YAML metadata of your document. You can create a slide show broken up into sections by using the `#` and `##` heading tags; you can also create a new slide without a header using a horizontal rule (`---`). For example, here is a simple slide show: 10 | 11 | ```markdown 12 | --- 13 | title: "Habits" 14 | author: John Doe 15 | date: March 22, 2005 16 | output: revealjs::revealjs_presentation 17 | --- 18 | 19 | # In the morning 20 | 21 | ## Getting up 22 | 23 | - Turn off alarm 24 | - Get out of bed 25 | 26 | ## Breakfast 27 | 28 | - Eat eggs 29 | - Drink coffee 30 | 31 | # In the evening 32 | 33 | ## Dinner 34 | 35 | - Eat spaghetti 36 | - Drink wine 37 | 38 | ## Going to sleep 39 | 40 | - Get in bed 41 | - Count sheep 42 | ``` 43 | 44 | See Figure \@ref(fig:revealjs-sample) for two sample slides. 45 | 46 | ```{r revealjs-sample, echo=FALSE, fig.cap='Two sample slides created from the revealjs package.', out.width='49%', fig.show='hold'} 47 | knitr::include_graphics(c('images/revealjs-1.png', 'images/revealjs-2.png'), dpi = NA) 48 | ``` 49 | 50 | ## Display modes 51 | 52 | The following single character keyboard shortcuts enable alternate display modes: 53 | 54 | - `'f'`: enable fullscreen mode. 55 | 56 | - `'o'`: enable overview mode. 57 | 58 | Pressing `Esc` exits all of these modes. 59 | 60 | ## Appearance and style 61 | 62 | There are several options that control the appearance of reveal.js presentations: 63 | 64 | - `theme` specifies the theme to use for the presentation (available themes are `"default"`, `"simple"`, `"sky"`, `"beige"`, `"serif"`, `"solarized"`, `"blood"`, `"moon"`, `"night"`, `"black"`, `"league"`, and `"white"`). 65 | 66 | - `highlight` specifies the syntax highlighting style. Supported styles include `"default"`, `"tango"`, `"pygments"`, `"kate"`, `"monochrome"`, `"espresso"`, `"zenburn"`, and `"haddock"`. Pass null to prevent syntax highlighting. 67 | 68 | - `center` specifies whether you want to vertically center content on slides (this defaults to `false`). 69 | 70 | - `smart` indicates whether to produce typographically correct output, converting straight quotes to curly quotes, `---` to em-dashes, `--` to en-dashes, and `...` to ellipses. Note that `smart` is enabled by default. 71 | 72 | For example: 73 | 74 | ```yaml 75 | --- 76 | output: 77 | revealjs::revealjs_presentation: 78 | theme: sky 79 | highlight: pygments 80 | center: true 81 | --- 82 | ``` 83 | 84 | ### Smaller text 85 | 86 | If you need smaller text for certain paragraphs, you can enclose text in the `` tag. For example: 87 | 88 | ```html 89 | This sentence will appear smaller. 90 | ``` 91 | 92 | ## Slide transitions 93 | 94 | You can use the `transition` and `background_transition` options to specify the global default slide transition style: 95 | 96 | - `transition` specifies the visual effect when moving between slides. Available transitions are `"default"`, `"fade"`, `"slide"`, `"convex"`, `"concave"`, `"zoom"` or `"none"`. 97 | 98 | - `background_transition` specifies the background transition effect when moving between full page slides. Available transitions are `"default"`, `"fade"`, `"slide"`, `"convex"`, `"concave"`, `"zoom"` or `"none"`. 99 | 100 | For example: 101 | 102 | ```yaml 103 | --- 104 | output: 105 | revealjs::revealjs_presentation: 106 | transition: fade 107 | --- 108 | ``` 109 | 110 | You can override the global transition for a specific slide by using the `data-transition` attribute. For example: 111 | 112 | ```markdown 113 | ## Use a zoom transition {data-transition="zoom"} 114 | 115 | ## Use a faster speed {data-transition-speed="fast"} 116 | ``` 117 | 118 | You can also use different in and out transitions for the same slide. For example: 119 | 120 | ```markdown 121 | ## Fade in, Slide out {data-transition="slide-in fade-out"} 122 | 123 | ## Slide in, Fade out {data-transition="fade-in slide-out"} 124 | ``` 125 | 126 | ## Slide backgrounds 127 | 128 | Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a `data-background` attribute to your slide header element. Four different types of backgrounds are supported: `color`, `image`, `video`, and `iframe`. Below are a few examples. 129 | 130 | ```markdown 131 | ## CSS color background {data-background=#ff0000} 132 | 133 | ## Full size image background {data-background="background.jpeg"} 134 | 135 | ## Video background {data-background-video="background.mp4"} 136 | 137 | ## A background page {data-background-iframe="https://example.com"} 138 | ``` 139 | 140 | Backgrounds transition using a `fade` animation by default. This can be changed to a linear sliding transition by specifying the `background-transition: slide`. Alternatively, you can set `data-background-transition` on any slide with a background to override that specific transition. 141 | 142 | ## 2-D presentations 143 | 144 | You can use the `slide_level` option to specify which level of heading will be used to denote individual slides. If `slide_level` is 2 (the default), a two-dimensional layout will be produced, with level-1 headers building horizontally and level-2 headers building vertically. For example: 145 | 146 | ```markdown 147 | # Horizontal Slide 1 148 | 149 | ## Vertical Slide 1 150 | 151 | ## Vertical Slide 2 152 | 153 | # Horizontal Slide 2 154 | ``` 155 | 156 | With this layout, horizontal navigation will proceed directly from "Horizontal Slide 1" to "Horizontal Slide 2", with vertical navigation to "Vertical Slide 1" (and then "Vertical Slide 2", etc.) presented as an option on "Horizontal Slide 1". See Figure \@ref(fig:revealjs-sample) for an example (note the arrows at the bottom right on the slides). 157 | 158 | ## Custom CSS 159 | 160 | You can add your own CSS\index{CSS} to a reveal.js presentation using the `css` option: 161 | 162 | ```yaml 163 | --- 164 | output: 165 | revealjs::revealjs_presentation: 166 | css: styles.css 167 | --- 168 | ``` 169 | 170 | If you want to override the appearance of particular HTML element document-wide, you need to qualify it with the `.reveal section` preface in your CSS. For example, to change the default text color in paragraphs to blue, you would use: 171 | 172 | ```css 173 | .reveal section p { 174 | color: blue; 175 | } 176 | ``` 177 | 178 | ### Slide IDs and classes 179 | 180 | You can also target specific slides or classes of slice with custom CSS by adding IDs or classes to the slides headers within your document. For example, the following slide header 181 | 182 | ```markdown 183 | ## Next Steps {#nextsteps .emphasized} 184 | ``` 185 | 186 | would enable you to apply CSS to all of its content using either of the following CSS selectors: 187 | 188 | ```css 189 | #nextsteps { 190 | color: blue; 191 | } 192 | 193 | .emphasized { 194 | font-size: 1.2em; 195 | } 196 | ``` 197 | 198 | ### Styling text spans 199 | 200 | You can apply classes defined in your CSS file to spans of text by using a `span` tag. For example: 201 | 202 | ```html 203 | Pay attention to this! 204 | ``` 205 | 206 | ## reveal.js options 207 | 208 | Reveal.js has many additional options to configure its behavior. You can specify any of these options using `reveal_options`. For example: 209 | 210 | ```yaml 211 | --- 212 | title: "Habits" 213 | output: 214 | revealjs::revealjs_presentation: 215 | self_contained: false 216 | reveal_options: 217 | slideNumber: true 218 | previewLinks: true 219 | --- 220 | ``` 221 | 222 | You can find documentation on the various available reveal.js options here: . 223 | 224 | ## reveal.js plugins 225 | 226 | You can enable various reveal.js plugins using the `reveal_plugins` option. Plugins currently supported plugins are listed in Table \@ref(tab:revealjs-plugins). 227 | 228 | Table: (\#tab:revealjs-plugins) The currently supported reveal.js plugins. 229 | 230 | | Plugin | Description | 231 | |----------------------------|---------------------------------------------| 232 | | notes | Present per-slide notes in a separate browser window. | 233 | | zoom | Zoom in and out of selected content with Alt+Click. | 234 | | search | Find a text string anywhere in the slides and show the next occurrence to the user. | 235 | | chalkboard | Include handwritten notes within a presentation. | 236 | 237 | Note that the use of plugins requires that the `self_contained` option be set to `false`. For example, this presentation includes both the "notes" and "search" plugins: 238 | 239 | ```yaml 240 | --- 241 | title: "Habits" 242 | output: 243 | revealjs::revealjs_presentation: 244 | self_contained: false 245 | reveal_plugins: ["notes", "search"] 246 | --- 247 | ``` 248 | 249 | You can specify additional options for the `chalkboard` plugin using `reveal_options`. For example: 250 | 251 | ```yaml 252 | --- 253 | title: "Habits" 254 | output: 255 | revealjs::revealjs_presentation: 256 | self_contained: false 257 | reveal_plugins: ["chalkboard"] 258 | reveal_options: 259 | chalkboard: 260 | theme: whiteboard 261 | toggleNotesButton: false 262 | --- 263 | ``` 264 | 265 | ## Other features 266 | 267 | Refer to Section \@ref(html-document) for the documentation of other features of reveal.js presentations, including figure options (Section \@ref(figure-options)), MathJax equations (Section \@ref(mathjax-equations)), keeping Markdown (Section \@ref(keeping-markdown)), document dependencies (Section \@ref(document-dependencies)), header and before/after body inclusions (Section \@ref(includes)), custom templates (Section \@ref(custom-templates)), Pandoc arguments (Section \@ref(pandoc-arguments)), and shared options (Section \@ref(shared-options)). Also see Section \@ref(incremental-bullets) for incremental bullets. 268 | -------------------------------------------------------------------------------- /06-tufte.Rmd: -------------------------------------------------------------------------------- 1 | # Tufte Handouts 2 | 3 | The Tufte handout\index{Tufte handout} style is a style that [Edward Tufte](https://en.wikipedia.org/wiki/Edward_Tufte) uses in his books and handouts. Tufte's style is known for its extensive use of sidenotes, tight integration of graphics with text, and well-set typography. This style has been implemented in LaTeX and HTML/CSS,^[See Github repositories https://github.com/tufte-latex/tufte-latex and https://github.com/edwardtufte/tufte-css.] respectively. Both implementations have been ported into the **tufte** package [@R-tufte]. If you want LaTeX/PDF output, you may use the `tufte_handout` format for handouts, and `tufte_book` for books. For HTML output, use `tufte_html`, e.g., 4 | 5 | ```yaml 6 | --- 7 | title: "An Example Using the Tufte Style" 8 | author: "John Smith" 9 | output: 10 | tufte::tufte_handout: default 11 | tufte::tufte_html: default 12 | --- 13 | ``` 14 | 15 | Figure \@ref(fig:tufte-overview) shows the basic layout of the Tufte style, in which you can see a main column on the left that contains the body of the document, and a side column on the right to display sidenotes. 16 | 17 | ```{r tufte-overview, echo=FALSE, fig.cap='The basic layout of the Tufte style.', out.width='100%'} 18 | knitr::include_graphics('images/tufte-overview.png', dpi = NA) 19 | ``` 20 | 21 | There are two goals for the **tufte** package: 22 | 23 | 1. To produce both PDF and HTML output with similar styles from the same R Markdown document. 24 | 25 | 1. To provide simple syntax to write elements of the Tufte style such as side notes and margin figures. For example, when you want a margin figure, all you need to do is the chunk option `fig.margin = TRUE`, and **tufte** will take care of the details for you, so you never need to think about LaTeX environments like `\begin{marginfigure} \end{marginfigure}` or HTML tags like ` `; the LaTeX and HTML code under the hood may be complicated, but you never need to learn or write such code. 26 | 27 | You can use the wizard in RStudio IDE from the menu `File -> New File -> R Markdown -> From Template` to create a new R Markdown document with a default example provided by the **tufte** package. Note that you need a LaTeX distribution if you want PDF output (see Chapter \@ref(installation)). 28 | 29 | ## Headings {#tufte-headings} 30 | 31 | The Tufte style provides the first and second-level headings (that is, `#` and `##`), demonstrated in the next section. You may get unexpected output (and even errors) if you try to use `###` and smaller headings. 32 | 33 | In his later books,^[Such as "Beautiful Evidence": http://www.edwardtufte.com/tufte/books_be.], Tufte starts each section with a bit of vertical space, a non-indented paragraph, and sets the first few words of the sentence in small caps. To accomplish this using this style, call the `newthought()` function in **tufte** in an _inline R expression_ `` `r ` ``. Note that you should not assume **tufte** has been attached to your R session. You should either use `library(tufte)` in your R Markdown document before you call `newthought()`, or use `tufte::newthought()`. 34 | 35 | ## Figures {#tufte-figures} 36 | 37 | ### Margin figures 38 | 39 | Images and graphics play an integral role in Tufte's work. To place figures in the margin, you can use the **knitr** chunk option `fig.margin = TRUE`. For example: 40 | 41 | ````markdown 42 | `r ''````{r fig-margin, fig.margin=TRUE} 43 | plot(cars) 44 | ``` 45 | ```` 46 | 47 | As in other Rmd documents, you can use the `fig.cap` chunk option to provide a figure caption, and adjust figure sizes using the `fig.width` and `fig.height` chunk options, which are specified in inches, and will be automatically scaled down to fit within the handout margin. 48 | 49 | Figure \@ref(fig:tufte-margin) shows what a margin figure looks like. 50 | 51 | ```{r tufte-margin, echo=FALSE, fig.cap='A margin figure in the Tufte style.', out.width='100%'} 52 | knitr::include_graphics('images/tufte-margin.png', dpi = NA) 53 | ``` 54 | 55 | ### Arbitrary margin content 56 | 57 | You can include anything in the margin using the **knitr** engine named `marginfigure`. Unlike R code chunks ```` ```{r} ````, you write a chunk starting with ```` ```{marginfigure} ```` instead, then put the content in the chunk, e.g., 58 | 59 | ````markdown 60 | `r ''````{marginfigure} 61 | We know from _the first fundamental theorem of calculus_ that 62 | for $x$ in $[a, b]$: 63 | $$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$ 64 | ``` 65 | ```` 66 | 67 | For the sake of portability between LaTeX and HTML, you should keep the margin content as simple as possible (syntax-wise) in the `marginfigure` blocks. You may use simple Markdown syntax like `**bold**` and `_italic_` text, but please refrain from using footnotes, citations, or block-level elements (e.g., blockquotes and lists) there. 68 | 69 | Note that if you set `echo = FALSE` in your global chunk options, you will have to add `echo = TRUE` to the chunk to display a margin figure, for example ```` ```{marginfigure, echo = TRUE} ````. 70 | 71 | ### Full-width figures 72 | 73 | You can arrange for figures to span across the entire page by using the chunk option `fig.fullwidth = TRUE`, e.g., 74 | 75 | ````markdown 76 | `r ''````{r, fig.width=10, fig.height=2, fig.fullwidth=TRUE} 77 | par(mar = c(4, 4, .1, .2)); plot(sunspots) 78 | ``` 79 | ```` 80 | 81 | Other chunk options related to figures can still be used, such as `fig.width`, `fig.cap`, and `out.width`, etc. For full-width figures, usually `fig.width` is large and `fig.height` is small. In the above example, the plot size is 10x2. 82 | 83 | Figure \@ref(fig:tufte-full) shows what a full-width figure looks like. 84 | 85 | ```{r tufte-full, echo=FALSE, fig.cap='A full-width figure in the Tufte style.', out.width='100%'} 86 | knitr::include_graphics('images/tufte-full.png', dpi = NA) 87 | ``` 88 | 89 | ### Main column figures 90 | 91 | Besides margin and full-width figures, you can certainly also include figures constrained to the main column. This is the default type of figures in the LaTeX/HTML output, and requires no special chunk options. 92 | 93 | Figure \@ref(fig:tufte-main) shows what a figure looks like in the main column. 94 | 95 | ```{r tufte-main, echo=FALSE, fig.cap='A figure in the main column in the Tufte style.', out.width='100%'} 96 | knitr::include_graphics('images/tufte-main.png', dpi = NA) 97 | ``` 98 | 99 | ## Sidenotes {#tufte-sidenotes} 100 | 101 | One of the most prominent and distinctive features of this style is the extensive use of sidenotes. There is a wide margin to provide ample room for sidenotes and small figures. Any use of a footnote, of which the Markdown syntax is `^[footnote content]`, will automatically be converted to a sidenote. 102 | 103 | If you would like to place ancillary information in the margin without the sidenote mark (the superscript number), you can use the `margin_note()` function from **tufte** in an inline R expression. This function does not process the text with Pandoc, so Markdown syntax will not work here. If you need to write anything in Markdown syntax, please use the `marginfigure` block described previously. 104 | 105 | ## References {#tufte-references} 106 | 107 | References can be displayed as margin notes for HTML output. To enable this feature, you must set `link-citations: yes` in the YAML metadata, and the version of `pandoc-citeproc` should be at least 0.7.2. To check the version of `pandoc-citeproc` in your system, you may run this in R: 108 | 109 | ```{r eval=FALSE} 110 | system2('pandoc-citeproc', '--version') 111 | ``` 112 | 113 | If your version of `pandoc-citeproc` is too low, or you did not set `link-citations: yes` in YAML, references in the HTML output will be placed at the end of the output document. 114 | 115 | You can also explicitly disable this feature via the `margin_references` option, e.g., 116 | 117 | ```yaml 118 | --- 119 | output: 120 | tufte::tufte_html: 121 | margin_references: false 122 | --- 123 | ``` 124 | 125 | ## Tables {#tufte-tables} 126 | 127 | You can use the `kable()` function from the **knitr** package to format tables that integrate well with the rest of the Tufte handout style. The table captions are placed in the margin like figures in the HTML output. A simple example (Figure \@ref(fig:tufte-table) shows the output): 128 | 129 | ````markdown 130 | `r ''````{r} 131 | knitr::kable( 132 | mtcars[1:6, 1:6], caption = 'A subset of mtcars.' 133 | ) 134 | ``` 135 | ```` 136 | 137 | ```{r tufte-table, echo=FALSE, fig.cap='A table in the Tufte style.', out.width='100%'} 138 | knitr::include_graphics('images/tufte-table.png', dpi = NA) 139 | ``` 140 | 141 | ## Block quotes {#tufte-quotes} 142 | 143 | We know from the Markdown syntax that paragraphs that start with `>` are converted to block quotes. If you want to add a right-aligned footer for the quote, you may use the function `quote_footer()` from **tufte** in an inline R expression. Here is an example: 144 | 145 | ````markdown 146 | > "If it weren't for my lawyer, I'd still be in prison. 147 | > It went a lot faster with two people digging." 148 | > 149 | > `r "\x60r tufte::quote_footer('--- Joe Martin')\x60"` 150 | ```` 151 | 152 | ## Responsiveness {#tufte-responsiveness} 153 | 154 | The HTML page is responsive in the sense that when the page width is smaller than 760px, sidenotes and margin notes will be hidden by default. For sidenotes, you can click their numbers (the superscripts) to toggle their visibility. For margin notes, you may click the circled plus signs to toggle visibility (see Figure \@ref(fig:tufte-responsive)). 155 | 156 | ```{r tufte-responsive, echo=FALSE, fig.cap='The Tufte HTML style on narrow screens.', out.width='100%'} 157 | knitr::include_graphics('images/tufte-responsive.png', dpi = NA) 158 | ``` 159 | 160 | ## Sans-serif fonts and epigraphs {#tufte-sans} 161 | 162 | There are a few other things in Tufte CSS that we have not mentioned so far. If you prefer sans-serif fonts, use the function `sans_serif()` in **tufte**. For epigraphs, you may use a pair of underscores to make the paragraph italic in a block quote, e.g., 163 | 164 | ````markdown 165 | > _I can win an argument on any topic, against any opponent. 166 | > People know this, and steer clear of me at parties. Often, 167 | > as a sign of their great respect, they don't even invite me._ 168 | > 169 | > `r "\x60r quote_footer('--- Dave Barry')\x60"` 170 | ```` 171 | 172 | ## Customize CSS styles {#tufte-css} 173 | 174 | You can turn on/off some features of the Tufte style in HTML output. The default features enabled are: 175 | 176 | ```yaml 177 | --- 178 | output: 179 | tufte::tufte_html: 180 | tufte_features: ["fonts", "background", "italics"] 181 | --- 182 | ``` 183 | 184 | If you do not want the page background to be lightyellow, you can remove `background` from `tufte_features`. You can also customize the style of the HTML page via a CSS file. For example, if you do not want the subtitle to be italic, you can define 185 | 186 | ```css 187 | h3.subtitle em { 188 | font-style: normal; 189 | } 190 | ``` 191 | 192 | in, say, a CSS file `my-style.css` (under the same directory of your Rmd document), and apply it to your HTML output via the `css` option, e.g., 193 | 194 | ```yaml 195 | --- 196 | output: 197 | tufte::tufte_html: 198 | tufte_features: ["fonts", "background"] 199 | css: "my-style.css" 200 | --- 201 | ``` 202 | 203 | There is also a variant of the Tufte style in HTML/CSS named "[Envisioned CSS](http://nogginfuel.com/envisioned-css/)". This style can be enabled by specifying the argument `tufte_variant = 'envisioned'` in `tufte_html()`,^[The actual Envisioned CSS was not used in the **tufte** package. Only the fonts, background color, and text color are changed based on the default Tufte style.], e.g., 204 | 205 | ```yaml 206 | --- 207 | output: 208 | tufte::tufte_html: 209 | tufte_variant: "envisioned" 210 | --- 211 | ``` 212 | 213 | You can see a live example at https://rstudio.github.io/tufte/. It is also available in Simplified Chinese: https://rstudio.github.io/tufte/cn/, and its `envisioned` style can be found at https://rstudio.github.io/tufte/envisioned/. 214 | -------------------------------------------------------------------------------- /14-learnr.Rmd: -------------------------------------------------------------------------------- 1 | # Interactive Tutorials {#learnr} 2 | 3 | The **learnr** package [@R-learnr]\index{learnr} makes it easy to turn any R Markdown document into an interactive tutorial. Tutorials consist of content along with interactive components for checking and reinforcing understanding. Tutorials can include any or all of the following: 4 | 5 | 1. Narrative, figures, illustrations, and equations. 6 | 7 | 1. Code exercises (R code chunks that users can edit and execute directly). 8 | 9 | 1. Quiz questions. 10 | 11 | 1. Videos (currently supported services include YouTube and Vimeo). 12 | 13 | 1. Interactive Shiny components. 14 | 15 | Tutorials automatically preserve work done within them, so if a user works on a few exercises or questions and returns to the tutorial later, they can pick up right where they left off. 16 | 17 | This chapter is only a brief summary of **learnr**'s full documentation at https://rstudio.github.io/learnr/. If you are interested in building more sophisticated tutorials, we recommend that you read the full documentation. 18 | 19 | ## Get started {#learnr-start} 20 | 21 | To create a **learnr** tutorial, first install the **learnr** package with: 22 | 23 | ```r 24 | install.packages("learnr") 25 | ``` 26 | 27 | Then you can select the "Interactive Tutorial" template from the "New R Markdown" dialog in the RStudio IDE (see Figure \@ref(fig:learnr-template)). 28 | 29 | ```{r learnr-template, echo=FALSE, out.width='100%', fig.cap='Create an interactive tutorial in RStudio.'} 30 | knitr::include_graphics('images/learnr-template.png', dpi = NA) 31 | ``` 32 | 33 | If you do not use RStudio, it is also easy to create a tutorial: add `runtime: shiny_prerendered` and the output format `learnr::tutorial` to the YAML metadata, use `library(learnr)` within your Rmd file to activate the tutorial mode, and then add the chunk option `exercise = TRUE` to turn code chunks into exercises. Your tutorial users can edit and execute the R code and see the results right within their web browser. 34 | 35 | Below is a minimal tutorial example: 36 | 37 | ````markdown 38 | `r xfun::file_string('examples/hello-tutorial.Rmd')` 39 | ```` 40 | 41 | To run this tutorial, you may hit the button "Run Document" in RStudio, or call the function `rmarkdown::run()` on this Rmd file. Figure \@ref(fig:learnr-hello) shows what the tutorial looks like in the browser. Users can do the exercise by editing the code and running it live in the browser. 42 | 43 | ```{r learnr-hello, echo=FALSE, out.width='100%', fig.cap='A simple example tutorial.'} 44 | knitr::include_graphics('images/learnr-hello.png', dpi = NA) 45 | ``` 46 | 47 | We strongly recommend that you assign unique chunk labels to exercises (e.g., the above example used the label `addition`), because chunk labels will be used as identifiers for **learnr** to save and restore user work. Without these identifiers, users could possibly lose their work in progress the next time when they pick up the tutorial. 48 | 49 | ## Tutorial types {#learnr-types} 50 | 51 | There are two main types of tutorial documents: 52 | 53 | 1. Tutorials that are mostly narrative and/or video content, and also include some runnable code chunks. These documents are very similar to package vignettes in that their principal goal is communicating concepts. The interactive tutorial features are then used to allow further experimentation by the reader. 54 | 55 | 1. Tutorials that provide a structured learning experience with multiple exercises, quiz questions, and tailored feedback. 56 | 57 | The first type of tutorial is much easier to author while still being very useful. These documents will typically add `exercise = TRUE` to selected code chunks, and also set `exercise.eval = TRUE` so the chunk output is visible by default. The reader can simply look at the R code and move on, or play with it to reinforce their understanding. 58 | 59 | The second type of tutorial provides much richer feedback and assessment, but also requires considerably more effort to author. If you are primarily interested in this sort of tutorial, there are many features in **learnr** to support it, including exercise hints and solutions, automated exercise checkers, and multiple choice quizzes with custom feedback. 60 | 61 | The most straightforward path is to start with the first type of tutorial (executable chunks with pre-evaluated output), and then move into more sophisticated assessment and feedback over time. 62 | 63 | ## Exercises {#learnr-exercises} 64 | 65 | Exercises are interactive R code chunks that allow readers to directly execute R code and see its results. We have shown a simple exercise in Figure \@ref(fig:learnr-hello). 66 | 67 | Exercises can include hints or solutions as well as custom checking code to provide feedback on user answers. 68 | 69 | ### Solutions 70 | 71 | To create a solution to an exercise in a code chunk with the chunk label `foo`, you add a new code chunk with the chunk label `foo-solution`, e.g., 72 | 73 | ````markdown 74 | `r ''````{r filter, exercise=TRUE} 75 | # Change the filter to select February rather than January 76 | nycflights <- filter(nycflights, month == 1) 77 | ``` 78 | 79 | `r ''````{r filter-solution} 80 | nycflights <- filter(nycflights, month == 2) 81 | ``` 82 | ```` 83 | 84 | When a solution code chunk is provided, there will be a `Solution` button on the exercise (see Figure \@ref(fig:learnr-solution)). Users can click this button to see the solution. 85 | 86 | ```{r learnr-solution, echo=FALSE, out.width='100%', fig.cap='A solution to an exercise.'} 87 | knitr::include_graphics('images/learnr-solution.png', dpi = NA) 88 | ``` 89 | 90 | ### Hints 91 | 92 | Sometimes you may not want to give the solutions directly to students, but provide hints instead to guide them. Hints can be either Markdown-based text content or code snippets. 93 | 94 | To create a hint based on custom Markdown content, add a `
    ` tag with an `id` attribute that marks it as hint for your exercise (e.g., `filter-hint`). For example: 95 | 96 | ````markdown 97 | `r ''````{r filter, exercise=TRUE} 98 | # filter the flights table to include only United and 99 | # American flights 100 | flights 101 | ``` 102 | 103 |
    104 | **Hint:** You may want to use the dplyr `filter` function. 105 |
    106 | ```` 107 | 108 | The content within the `
    ` will be displayed underneath the R code editor for the exercise whenever the user presses the `Hint` button. 109 | 110 | If your Pandoc version is higher than 2.0 (check `rmarkdown::pandoc_version()`), you can also use the alternative syntax to write the `
    `: 111 | 112 | ```markdown 113 | :::{#filter-hint} 114 | **Hint:** You may want to use the dplyr `filter` function. 115 | ::: 116 | ``` 117 | 118 | To create a hint with a code snippet, you add a new code chunk with the label suffix `-hint`, e.g., 119 | 120 | ````markdown 121 | `r ''````{r filter, exercise=TRUE} 122 | # filter the flights table to include only United and 123 | # American flights 124 | flights 125 | ``` 126 | 127 | `r ''````{r filter-hint} 128 | filter(flights, ...) 129 | ``` 130 | ```` 131 | 132 | You can also provide a sequence of hints that reveal progressively more of the solution as desired by the user. To do this, create a sequence of indexed hint chunks (e.g., `-hint-1`, `-hint-2`, `-hint-3`, etc.) for your exercise chunk. For example: 133 | 134 | ````markdown 135 | `r ''````{r filter, exercise=TRUE} 136 | # filter the flights table to include only United and 137 | # American flights 138 | flights 139 | ``` 140 | 141 | `r ''````{r filter-hint-1} 142 | filter(flights, ...) 143 | ``` 144 | 145 | `r ''````{r filter-hint-2} 146 | filter(flights, UniqueCarrier == "AA") 147 | ``` 148 | 149 | `r ''````{r filter-hint-3} 150 | filter(flights, UniqueCarrier == "AA" | UniqueCarrier == "UA") 151 | ``` 152 | ```` 153 | 154 | ## Quiz questions {#learnr-quiz} 155 | 156 | You can include one or more multiple-choice quiz questions within a tutorial to help verify that readers understand the concepts presented. Questions can either have a single or multiple correct answers. 157 | 158 | Include a question by calling the `question()` function within an R code chunk, e.g., 159 | 160 | ````markdown 161 | `r ''````{r letter-a, echo=FALSE} 162 | question("What number is the letter A in the English alphabet?", 163 | answer("8"), 164 | answer("14"), 165 | answer("1", correct = TRUE), 166 | answer("23") 167 | ) 168 | ``` 169 | ```` 170 | 171 | Figure \@ref(fig:learnr-question) shows what the above question would look like within a tutorial. 172 | 173 | ```{r learnr-question, echo=FALSE, out.width='100%', fig.cap='A question in a tutorial.'} 174 | knitr::include_graphics('images/learnr-question.png', dpi = NA) 175 | ``` 176 | 177 | The functions `question()` and `answer()` have several other arguments for more features that allow you to customize the questions and answers, such as custom error messages when the user's answer is wrong, allowing users to retry a question, multiple-choice questions, and multiple questions in a group. See their help pages in R for more information. 178 | 179 | ## Videos {#learnr-videos} 180 | 181 | You can include videos published on either YouTube or Vimeo within a tutorial using the standard Markdown image syntax. Note that any valid YouTube or Vimeo URL will work. For example, the following are all valid examples of video embedding: 182 | 183 | ```markdown 184 | ![](https://youtu.be/zNzZ1PfUDNk) 185 | ![](https://www.youtube.com/watch?v=zNzZ1PfUDNk) 186 | 187 | ![](https://vimeo.com/142172484) 188 | ![](https://player.vimeo.com/video/142172484) 189 | ``` 190 | 191 | Videos are responsively displayed at 100% of their container's width (with height automatically determined based on a 16x9 aspect ratio). You can change this behavior by adding attributes to the Markdown code where you reference the video. 192 | 193 | You can specify an alternate percentage for the video's width or an alternate fixed width and height. For example: 194 | 195 | ```markdown 196 | ![](https://youtu.be/zNzZ1PfUDNk){width="90%"} 197 | 198 | ![](https://youtu.be/zNzZ1PfUDNk){width="560" height="315"} 199 | ``` 200 | 201 | ## Shiny components {#learnr-shiny} 202 | 203 | Tutorials are essentially Shiny documents, which we will introduce in Chapter \@ref(shiny-documents). For that reason, you are free to use any interactive Shiny components in tutorials, not limited to exercises and quiz questions. 204 | 205 | The Shiny UI components can be written in normal R code chunks. For the Shiny server logic code (rendering output), you need to add a chunk option `context="server"` to code chunks. For example: 206 | 207 | ````markdown 208 | `r ''````{r, echo=FALSE} 209 | sliderInput("bins", "Number of bins:", 30, min = 1, max = 50) 210 | plotOutput("distPlot") 211 | ``` 212 | 213 | `r ''````{r, context="server"} 214 | output$distPlot = renderPlot({ 215 | x = faithful[, 2] # Old Faithful Geyser data 216 | bins = seq(min(x), max(x), length.out = input$bins + 1) 217 | hist(x, breaks = bins, col = 'darkgray', border = 'white') 218 | }) 219 | ``` 220 | ```` 221 | 222 | Again, since tutorials are Shiny applications, they can be deployed using the same methods mentioned in Section \@ref(shiny-deploy). 223 | 224 | ## Navigation and progress tracking {#learnr-nav} 225 | 226 | Each **learnr** tutorial includes a table of contents on the left that tracks student progress (see Figure \@ref(fig:learnr-progress)). Your browser will remember which sections of a tutorial a student has completed, and return a student to where he/she left off when the tutorial is reopened. 227 | 228 | ```{r learnr-progress, echo=FALSE, out.width='100%', fig.cap="Keeping track of the student's progress in a tutorial."} 229 | knitr::include_graphics('images/learnr-progress.png', dpi = NA) 230 | ``` 231 | 232 | You can optionally reveal content by one sub-section at a time. You can use this feature to let students set their own pace, or to hide information that would spoil an exercise or question that appears just before it. 233 | 234 | To use progressive reveal, set the `progressive` option to `true` in the `learnr::tutorial` output format in the YAML metadata, e.g., 235 | 236 | ```yaml 237 | --- 238 | title: "Programming basics" 239 | output: 240 | learnr::tutorial: 241 | progressive: true 242 | allow_skip: true 243 | runtime: shiny_prerendered 244 | --- 245 | ``` 246 | 247 | The `allow_skip` option above indicates that students can skip any sections, and move directly to the next section without completing exercises in the previous section. 248 | -------------------------------------------------------------------------------- /05-dashboards.Rmd: -------------------------------------------------------------------------------- 1 | # (PART) Extensions {-} 2 | 3 | # Dashboards 4 | 5 | R Markdown is customizable and extensible. In Chapters \@ref(documents) and \@ref(presentations), we have introduced basic document and presentation formats in the **rmarkdown** package, and explained how to customize them. From this chapter on, we will show several more existing extension packages that bring different styles, layouts, and applications to the R Markdown ecosystem. In this chapter, we introduce dashboards\index{dashboard} based on the **flexdashboard** package [@R-flexdashboard]. 6 | 7 | Dashboards are particularly common in business-style reports. They can be used to highlight brief and key summaries of a report. The layout of a dashboard is often grid-based, with components arranged in boxes of various sizes. 8 | 9 | With the **flexdashboard** package, you can 10 | 11 | - Use R Markdown to publish a group of related data visualizations as a dashboard. 12 | 13 | - Embed a wide variety of components including HTML widgets, R graphics, tabular data, gauges, value boxes, and text annotations. 14 | 15 | - Specify row or column-based layouts (components are intelligently re-sized to fill the browser and adapted for display on mobile devices). 16 | 17 | - Create story boards for presenting sequences of visualizations and related commentary. 18 | 19 | - Optionally use Shiny to drive visualizations dynamically. 20 | 21 | To author a dashboard, you create an R Markdown document with the `flexdashboard::flex_dashboard` output format. You can also create a document from within RStudio using the `File -> New File -> R Markdown` dialog, and choosing a "Flex Dashboard" template. 22 | 23 | If you are not using RStudio, you can create a new `flexdashboard` R Markdown file from the R console: 24 | 25 | ```r 26 | rmarkdown::draft( 27 | "dashboard.Rmd", template = "flex_dashboard", 28 | package = "flexdashboard" 29 | ) 30 | ``` 31 | 32 | The full documentation of **flexdashboard** is at https://rmarkdown.rstudio.com/flexdashboard/. We will only cover some basic features and usage in this chapter. Dashboards have many features in common with HTML documents (Section \@ref(html-document)), such as figure options (Section \@ref(figure-options)), appearance and style (Section \@ref(appearance-and-style)), MathJax equations (Section \@ref(mathjax-equations)), header and before/after body inclusions (Section \@ref(includes)), and Pandoc arguments (Section \@ref(pandoc-arguments)), and so on. We also recommend that you take a look at the R help page `?flexdashboard::flex_dashboard` to learn about more features and options. 33 | 34 | ## Layout 35 | 36 | The overall rule about the dashboard layout is that a first-level section generates a page, a second-level section generates a column (or a row), and a third-level section generates a box (that contains one or more dashboard components). Below is a quick example: 37 | 38 | ````markdown 39 | `r xfun::file_string('examples/dashboard/01-start.Rmd')` 40 | ```` 41 | 42 | Note that a series of dashes under a line of text is the alternative Markdown syntax for the second-level section header, i.e., 43 | 44 | ```markdown 45 | Column 1 46 | -------------------------------------------------- 47 | ``` 48 | 49 | is equivalent to 50 | 51 | ```markdown 52 | ## Column 1 53 | ``` 54 | 55 | We used a series of dashes just to make the second-level sections stand out in the source document. By default, the second-level sections generate columns on a dashboard, and the third level sections will be stacked vertically inside columns. You do not have to have columns on a dashboard: when all you have are the third-level sections in the source document, they will be stacked vertically as one column in the output. 56 | 57 | The text of the second-level headers will not be displayed in the output. The second-level headers are for the sole purpose of layout, so the actual content of the headers does not matter at all. By contrast, the first-level and third-level headers will be displayed as titles. 58 | 59 | Figure \@ref(fig:dashboard-start) shows the output of the above example, in which you can see two columns, with the first column containing "Chart A", and the second column containing "Chart B" and "Chart C". We did not really include any R code in the code chunks, so all boxes are empty. In these code chunks, you may write arbitrary R code that generates R plots, HTML widgets, and various other components to be introduced in Section \@ref(dashboard-components). 60 | 61 | ```{r dashboard-start, echo=FALSE, fig.cap='A quick example of the dashboard layout.', out.width='100%'} 62 | knitr::include_graphics('images/dashboard-start.png', dpi = NA) 63 | ``` 64 | 65 | ### Row-based layouts 66 | 67 | You may change the column-oriented layout to the row-oriented layout through the `orientation` option, e.g., 68 | 69 | ```yaml 70 | output: 71 | flexdashboard::flex_dashboard: 72 | orientation: rows 73 | ``` 74 | 75 | That means the second-level sections will be rows, and the third-level sections will be arranged as columns within rows. 76 | 77 | ### Attributes on sections 78 | 79 | The second-level section headers may have attributes on them, e.g., you can set the width of a column to 350: 80 | 81 | ```markdown 82 | A narrow column {data-width=350} 83 | -------------------------------- 84 | ``` 85 | 86 | For the row-oriented layout, you can set the `data-height` attribute for rows. The `{.tabset}` attribute can be applied on a column so that the third-level sections will be arranged in tabs, e.g., 87 | 88 | ```markdown 89 | Two tabs {.tabset} 90 | ------------------ 91 | 92 | ### Tab A 93 | 94 | ### Tab B 95 | ``` 96 | 97 | ### Multiple pages 98 | 99 | When you have multiple first-level sections in the document, they will be displayed as separate pages on the dashboard. Below is an example, and Figure \@ref(fig:dashboard-pages) shows the output. Note that a series of equal signs is the alternative Markdown syntax for the first-level section headers (you can use a single pound sign `#`, too). 100 | 101 | ````markdown 102 | `r xfun::file_string('examples/dashboard/02-pages.Rmd')` 103 | ```` 104 | 105 | Page titles are displayed as a navigation menu at the top of the dashboard. In this example, we applied icons to page titles through the `data-icon` attribute. You can find other available icons from https://fontawesome.com. 106 | 107 | ```{r dashboard-pages, echo=FALSE, fig.cap='Multiple pages on a dashboard.', out.width='100%'} 108 | knitr::include_graphics('images/dashboard-pages.png', dpi = NA) 109 | ``` 110 | 111 | ### Story boards 112 | 113 | Besides the column and row-based layouts, you may present a series of visualizations and related commentary through the "storyboard" layout. To enable this layout, you use the option `storyboard`. Below is an example, and Figure \@ref(fig:dashboard-story) shows the output, in which you can see left/right navigation buttons at the top to help you go through all visualizations and associated commentaries one by one. 114 | 115 | ````markdown 116 | `r xfun::file_string('examples/dashboard/03-storyboard.Rmd')` 117 | ```` 118 | 119 | ```{r dashboard-story, echo=FALSE, fig.cap='An example story board.', out.width='100%'} 120 | knitr::include_graphics('images/dashboard-story.png', dpi = NA) 121 | ``` 122 | 123 | ## Components {#dashboard-components} 124 | 125 | A wide variety of components can be included in a dashboard layout, including: 126 | 127 | 1. Interactive JavaScript data visualizations based on HTML widgets. 128 | 129 | 1. R graphical output including base, lattice, and grid graphics. 130 | 131 | 1. Tabular data (with optional sorting, filtering, and paging). 132 | 133 | 1. Value boxes for highlighting important summary data. 134 | 135 | 1. Gauges for displaying values on a meter within a specified range. 136 | 137 | 1. Text annotations of various kinds. 138 | 139 | 1. A navigation bar to provide more links related to the dashboard. 140 | 141 | The first three components work in most R Markdown documents regardless of output formats. Only the latter four are specific to dashboards, and we briefly introduce them in this section. 142 | 143 | ### Value boxes 144 | 145 | Sometimes you want to include one or more simple values within a dashboard. You can use the `valueBox()` function in the **flexdashboard** package to display single values along with a title and an optional icon. For example, here are three side-by-side sections, each displaying a single value (see Figure \@ref(fig:dashboard-valueboxes) for the output): 146 | 147 | ````markdown 148 | `r xfun::file_string('examples/dashboard/04-valueboxes.Rmd')` 149 | ```` 150 | 151 | ```{r dashboard-valueboxes, echo=FALSE, fig.cap='Three value boxes side by side on a dashboard.', out.width='100%'} 152 | knitr::include_graphics('images/dashboard-valueboxes.png', dpi = NA) 153 | ``` 154 | 155 | The `valueBox()` function is called to emit a value and specify an icon. 156 | 157 | The third code chunk ("Spam per Day") makes the background color of the value box dynamic using the `color` parameter. Available colors include `"primary"`, `"info"`, `"success"`, `"warning"`, and `"danger"` (the default is `"primary"`). You can also specify any valid CSS color (e.g., `"#ffffff"`, `"rgb(100, 100, 100)"`, etc.). 158 | 159 | ### Gauges 160 | 161 | Gauges display values on a meter within a specified range. For example, here is a set of three gauges (see Figure \@ref(fig:dashboard-gauges) for the output): 162 | 163 | ````markdown 164 | `r xfun::file_string('examples/dashboard/05-gauges.Rmd')` 165 | ```` 166 | 167 | ```{r dashboard-gauges, echo=FALSE, fig.cap='Three gauges side by side on a dashboard.', out.width='100%'} 168 | knitr::include_graphics('images/dashboard-gauges.png', dpi = NA) 169 | ``` 170 | 171 | There are a few things to note about this example: 172 | 173 | 1. The `gauge()` function is used to output a gauge. It has three required arguments: `value`, `min`, and `max` (these can be any numeric values). 174 | 175 | 1. You can specify an optional `symbol` to be displayed alongside the value (in the example "`%`" is used to denote a percentage). 176 | 177 | 1. You can specify a set of custom color "sectors" using the `gaugeSectors()` function. By default, the current theme's "success" color (typically green) is used for the gauge color. The `sectors` option enables you to specify a set of three value ranges (`success`, `warning`, and `danger`), which cause the gauge's color to change based on its value. 178 | 179 | ### Text annotations 180 | 181 | If you need to include additional narrative or explanation within your dashboard, you can do so in the following ways: 182 | 183 | 1. You can include content at the top of the page before dashboard sections are introduced. 184 | 185 | 1. You can define dashboard sections that do not include a chart but rather include arbitrary content (text, images, and equations, etc.). 186 | 187 | For example, the following dashboard includes some content at the top and a dashboard section that contains only text (see Figure \@ref(fig:dashboard-text) for the output): 188 | 189 | ````markdown 190 | `r xfun::file_string('examples/dashboard/06-text.Rmd')` 191 | ```` 192 | 193 | ```{r dashboard-text, echo=FALSE, fig.cap='Text annotations on a dashboard.', out.width='100%'} 194 | knitr::include_graphics('images/dashboard-text.png', dpi = NA) 195 | ``` 196 | 197 | Each component within a dashboard includes optional title and notes sections. The title is simply the text after the third-level (`###`) section heading. The notes are any text prefaced with `>` after the code chunk that yields the component's output (see the second component of the above example). 198 | 199 | You can exclude the title entirely by applying the `.no-title` attribute to a section heading. 200 | 201 | ### Navigation bar 202 | 203 | By default, the dashboard navigation bar includes the document's `title`, `author`, and `date`. When a dashboard has multiple pages (Section \@ref(multiple-pages)), links to the various pages are also included on the left side of the navigation bar. You can also add social links to the dashboard. 204 | 205 | In addition, you can add custom links to the navigation bar using the `navbar` option. For example, the following options add an "About" link to the navigation bar: 206 | 207 | ```yaml 208 | --- 209 | title: "Navigation Bar" 210 | output: 211 | flexdashboard::flex_dashboard: 212 | navbar: 213 | - { title: "About", href: "https://example.com/about" } 214 | --- 215 | ``` 216 | 217 | Navigation bar items must include either a `title` or `icon` field (or both). You should also include a `href` as the navigation target. The `align` field is optional (it can be "left" or "right" and defaults to "right"). 218 | 219 | You can include links to social sharing services via the `social` option. For example, the following dashboard includes Twitter and Facebook links as well as a drop-down menu with a more complete list of services: 220 | 221 | ```yaml 222 | --- 223 | title: "Social Links" 224 | output: 225 | flexdashboard::flex_dashboard: 226 | social: [ "twitter", "facebook", "menu" ] 227 | --- 228 | ``` 229 | 230 | The `social` option can include any number of the following services: `"facebook"`, `"twitter"`, `"google-plus"`, `"linkedin"`, and `"pinterest"`. You can also specify `"menu"` to provide a generic sharing drop-down menu that includes all of the services. 231 | 232 | ## Shiny 233 | 234 | By adding Shiny\index{Shiny} to a dashboard, you can let viewers change underlying parameters and see the results immediately, or let dashboards update themselves incrementally as their underlying data changes (see functions `reactiveFileReader()` and `reactivePoll()` in the **shiny** package). This is done by adding `runtime: shiny` to a standard dashboard document, and then adding one or more input controls and/or reactive expressions that dynamically drive the appearance of the components within the dashboard. 235 | 236 | Using Shiny with **flexdashboard** turns a static R Markdown report into an interactive document. It is important to note that interactive documents need to be deployed to a Shiny Server to be shared broadly (whereas static R Markdown documents are standalone web pages that can be attached to emails or served from any standard web server). 237 | 238 | Note that the [**shinydashboard**](https://rstudio.github.io/shinydashboard/) package provides another way to create dashboards with Shiny. 239 | 240 | ### Getting started 241 | 242 | The steps required to add Shiny components to a dashboard are: 243 | 244 | 1. Add `runtime: shiny` to the options declared at the top of the document (YAML metadata). 245 | 246 | 1. Add the `{.sidebar}` attribute to the first column of the dashboard to make it a host for Shiny input controls (note that this step is not strictly required, but this will generate a typical layout for Shiny-based dashboards). 247 | 248 | 1. Add Shiny inputs and outputs as appropriate. 249 | 250 | 1. When including plots, be sure to wrap them in a call to `renderPlot()`. This is important not only for dynamically responding to changes, but also to ensure that they are automatically re-sized when their container changes. 251 | 252 | ### A Shiny dashboard example 253 | 254 | Here is a simple example of a dashboard that uses Shiny (see Figure \@ref(fig:dashboard-shiny) for the output): 255 | 256 | ````markdown 257 | `r xfun::file_string('examples/dashboard/07-shiny.Rmd')` 258 | ```` 259 | 260 | ```{r dashboard-shiny, echo=FALSE, fig.cap='An interactive dashboard based on Shiny.', out.width='100%'} 261 | knitr::include_graphics('images/dashboard-shiny.png', dpi = NA) 262 | ``` 263 | 264 | The first column includes the `{.sidebar}` attribute and two Shiny input controls; the second column includes the Shiny code required to render the chart based on the inputs. 265 | 266 | One important thing to note about this example is the chunk labeled `global` at the top of the document. The `global` chunk has special behavior within **flexdashboard**: it is executed only once within the global environment, so that its results (e.g., data frames read from disk) can be accessed by all users of a multi-user dashboard. Loading your data within a `global` chunk will result in substantially better startup performance for your users, and hence is highly recommended. 267 | 268 | ### Input sidebar 269 | 270 | You add an input sidebar to a flexdashboard by adding the `{.sidebar}` attribute to a column, which indicates that it should be laid out flush to the left with a default width of 250 pixels and a special background color. Sidebars always appear on the left no matter where they are defined within the flow of the document. 271 | 272 | If you are creating a dashboard with multiple pages, you may want to use a single sidebar that applies across all pages. In this case, you should define the sidebar using a _first-level_ Markdown header. 273 | 274 | ### Learning more 275 | 276 | Below are some good resources for learning more about Shiny and creating interactive documents: 277 | 278 | 1. The official Shiny website (http://shiny.rstudio.com) includes extensive articles, tutorials, and examples to help you learn more about Shiny. 279 | 280 | 1. The article "[Introduction to Interactive Documents](http://shiny.rstudio.com/articles/interactive-docs.html)" on the Shiny website is a great guide for getting started with Shiny and R Markdown. 281 | 282 | 1. For deploying interactive documents, you may consider Shiny Server or RStudio Connect: https://www.rstudio.com/products/shiny/shiny-server/. 283 | -------------------------------------------------------------------------------- /12-bookdown.Rmd: -------------------------------------------------------------------------------- 1 | # Books 2 | 3 | We have introduced the basics of R Markdown in Chapter \@ref(documents), which highlighted how HTML, PDF, and Word documents can be produced from an R workflow. However, larger projects can become difficult to manage in a single R Markdown file. The **bookdown** package\index{bookdown} [@xie2016; @R-bookdown] addresses this limitation, and offers several key improvements: 4 | 5 | - Books and reports can be built from multiple R Markdown files. 6 | 7 | - Additional formatting features are added, such as cross-referencing, and numbering of figures, equations, and tables. 8 | 9 | - Documents can easily be exported in a range of formats suitable for publishing, including PDF, e-books and HTML websites. 10 | 11 | This book itself was created using **bookdown**, and acts as an example of what can be achieved. Despite the name containing the word "book", **bookdown** is not only for books, and it can be used for long reports, dissertations, or even single R Markdown documents (see Section \@ref(a-single-document)). It also works with other computing languages such as Python and C++ (see Section \@ref(language-engines)). If you want, you can even write documents irrelevant to computing, such as a novel. 12 | 13 | In this chapter, we cover the basics of **bookdown**, and explain how to start a **bookdown** project. Much of the the content is based on the work "*bookdown: Authoring Books and Technical Documents with R Markdown*" (https://bookdown.org/yihui/bookdown/) of @xie2016, which provides more detailed explanations of the concepts highlighted. 14 | 15 | ## Get started {#bookdown-start} 16 | 17 | You can install either the CRAN version or the development version on GitHub (https://github.com/rstudio/bookdown): 18 | 19 | ```{r eval=FALSE} 20 | # install from CRAN 21 | install.packages('bookdown') 22 | 23 | # or GitHub 24 | devtools::install_github('rstudio/bookdown') 25 | ``` 26 | 27 | If you use RStudio, you can start a new bookdown project from the menu `File -> New Project -> New Directory -> Book Project using bookdown`.^[Alternatively, the command `bookdown:::bookdown_skeleton(getwd())` will create a skeleton project in your current working directory.] Open the R Markdown file `index.Rmd`, and click the button `Build Book` on the `Build` tab of RStudio. This will compile the book and display the HTML version within the RStudio Viewer, which looks like Figure \@ref(fig:bookdown-template). 28 | 29 | ```{r bookdown-template, echo=FALSE, fig.cap= "The HTML output of the bookdown template.", out.width='100%'} 30 | knitr::include_graphics("images/bookdown-template.png", dpi = NA) 31 | ``` 32 | 33 | You may add or change the R Markdown files, and hit the `Knit` button again to preview the book. If you prefer not to use RStudio, you may also compile the book through the command line using `bookdown::render_book()`. 34 | 35 | ## Project structure {#bookdown-project} 36 | 37 | Below shows the basic structure of a default **bookdown** project: 38 | 39 | ```markdown 40 | directory/ 41 | ├── index.Rmd 42 | ├── 01-intro.Rmd 43 | ├── 02-literature.Rmd 44 | ├── 03-method.Rmd 45 | ├── 04-application.Rmd 46 | ├── 05-summary.Rmd 47 | ├── 06-references.Rmd 48 | ├── _bookdown.yml 49 | ├── _output.yml 50 | ├── book.bib 51 | ├── preamble.tex 52 | ├── README.md 53 | └── style.css 54 | ``` 55 | 56 | As a summary of these files: 57 | 58 | - `index.Rmd`: This is the only Rmd document to contain a YAML frontmatter as described within Chapter \@ref(basics), and is the first book chapter. 59 | 60 | - Rmd files: A typical **bookdown** book contains multiple chapters, and each chapter lives in one separate Rmd file. 61 | 62 | - `_bookdown.yml`: A configuration file for **bookdown**. 63 | 64 | - `_output.yml`: It specifies the formatting of the HTML, LaTeX/PDF, and e-books. 65 | 66 | - `preamble.tex` and `style.css`: They can be used to adjust the appearance and styles of the book output document(s). Knowledge of LaTeX and/or CSS is required. 67 | 68 | These files are explained in greater detail in the following subsections. 69 | 70 | ### Index file 71 | 72 | The `index.Rmd` file contains the first chapter and the YAML metadata, e.g., 73 | 74 | ```yaml 75 | --- 76 | title: "A Minimal Book Example" 77 | author: "Yihui Xie" 78 | date: "`r "\x60r Sys.Date()\x60"`" 79 | site: bookdown::bookdown_site 80 | documentclass: book 81 | bibliography: [book.bib, packages.bib] 82 | biblio-style: apalike 83 | link-citations: yes 84 | description: "This is a minimal example of using 85 | the bookdown package to write a book." 86 | --- 87 | ``` 88 | 89 | ### Rmd files 90 | 91 | By default, all Rmd files are merged with the `index.Rmd` to render the book. The Rmd files must start immediately with the chapter title using the first-level heading, e.g., `# Chapter Title`. Note that YAML metadata should not be included in these Rmd files, as it is inherited from the `index.Rmd` file. 92 | 93 | - 01-intro.Rmd 94 | 95 | ```markdown 96 | # Introduction 97 | 98 | This chapter is an overview of the methods that 99 | we propose to solve an **important problem**. 100 | ``` 101 | 102 | - 02-literature.Rmd 103 | 104 | ```markdown 105 | # Literature 106 | 107 | Here is a review of existing methods. 108 | ``` 109 | 110 | By default, **bookdown** merges all Rmd files by the order of filenames, e.g., `01-intro.Rmd` will appear before `02-literature.Rmd`. Filenames that start with an underscore `_` are skipped. 111 | 112 | ### `_bookdown.yml` 113 | 114 | The `_bookdown.yml` file allows you to specify optional settings to build the book. For example, you may want to override the order in which files are merged by including the field `rmd_files`: 115 | 116 | ```yaml 117 | rmd_files: ["index.Rmd", "02-literature.Rmd", "01-intro.Rmd"] 118 | ``` 119 | 120 | ### `_output.yml` 121 | 122 | The `_output.yml` file is used to specify the book output formats (see Section \@ref(bookdown-output)). Here is a brief example: 123 | 124 | ```yaml 125 | bookdown::gitbook: 126 | lib_dir: assets 127 | split_by: section 128 | config: 129 | toolbar: 130 | position: static 131 | bookdown::pdf_book: 132 | keep_tex: yes 133 | bookdown::html_book: 134 | css: toc.css 135 | ``` 136 | 137 | ## Markdown extensions {#bookdown-markdown} 138 | 139 | The **bookdown** package expands upon the Markdown syntax\index{Markdown syntax} outlined in Section \@ref(markdown-syntax), and provides additional powerful features that assist longer documents and academic writing. 140 | 141 | ### Number and reference equations {#equations} 142 | 143 | Section \@ref(math-expressions) highlighted how equations can be created using LaTeX syntax within Markdown. To number equations, put them in the `equation` environments, and assign labels to them using the syntax `(\#eq:label)`. Equation labels must start with the prefix `eq:` in **bookdown**. For example: 144 | 145 | ```latex 146 | \begin{equation} 147 | E=mc^2 148 | (\#eq:emc) 149 | \end{equation} 150 | ``` 151 | 152 | It renders the equation below \@ref(eq:emc): 153 | 154 | \begin{equation} 155 | E=mc^2 156 | (\#eq:emc) 157 | \end{equation} 158 | 159 | ### Theorems and proofs {#theorems} 160 | 161 | Theorems and proofs provide environments that are commonly used within articles and books in mathematics. To write a theorem, you can use the syntax below: 162 | 163 | ````markdown 164 | `r ''````{theorem, label, name="Theorem name"} 165 | Here is my theorem. 166 | ``` 167 | ```` 168 | 169 | For example: 170 | 171 | ```{theorem, pyth, name="Pythagorean theorem"} 172 | For a right triangle, if $c$ denotes the length of the hypotenuse 173 | and $a$ and $b$ denote the lengths of the other two sides, we have 174 | 175 | $$a^2 + b^2 = c^2$$ 176 | ``` 177 | 178 | Theorems can be numbered and cross-referenced, as you can see from Theorem \@ref(thm:pyth). The `proof` environment behaves similarly to theorem environments but is unnumbered. 179 | 180 | Variants of the `theorem` environments include: `r knitr::combine_words(names(bookdown:::theorem_abbr[-1]), before = '\x60')`. The abbreviations for references (e.g. `\@ref(lem:mylemma)`) are respectively `r knitr::combine_words(unlist(bookdown:::theorem_abbr[-1]), before = '\x60')`. 181 | Variants of the `proof` environments include `r knitr::combine_words(names(bookdown:::label_names_math2[-1]), before = '\x60')`. The syntax for these environments is similar to the `theorem` environment, e.g., ```` ```{lemma}````. 182 | 183 | ### Special headers 184 | 185 | There are two special types of first-level headers than can be used in **bookdown**: 186 | 187 | - A part can be created using `# (PART) Part Title {-}` before the chapters that belong to this part. 188 | 189 | - Appendices `# (APPENDIX) Appendix {-}`: All chapters after this header will be treated as the appendix. The numbering style of these chapters will be `A`, `B`, `C`, etc., and sections will be numbered as `A.1`, `A.2`, and so on. 190 | 191 | ### Text references 192 | 193 | A text reference is a paragraph with a label. The syntax is `(ref:label) text`, where `label` is a unique identifier, and `text` is a Markdown paragraph. For example: 194 | 195 | ```markdown 196 | (ref:foo) Define a text reference **here**. 197 | ``` 198 | 199 | Then you can use `(ref:foo)` to refer to the full text. Text references can be used anywhere in the document, and are particularly useful when assigning a long caption to a figure or including Markdown formatting in a caption. For example: 200 | 201 | ````markdown 202 | Some text. 203 | 204 | (ref:cool-plot) A boxplot of the data `iris` in **base** R. 205 | 206 | `r ''````{r cool-plot, fig.cap='(ref:cool-plot)'} 207 | boxplot(Sepal.Length ~ Species, data = iris) 208 | ``` 209 | ```` 210 | 211 | ### Cross referencing 212 | 213 | The **bookdown** package extends cross-referencing in R Markdown documents and allows section headers, tables, figures, equations, and theorems to be cross-referenced automatically. This only works for numbered environments, and therefore requires figures and tables to be assigned a label. Cross-references are made in the format `\@ref(type:label)`, where `label` is the chunk label and `type` is the environment being referenced. As examples: 214 | 215 | - Headers: 216 | 217 | ```markdown 218 | # Introduction {#intro} 219 | 220 | This is Chapter \@ref(intro) 221 | ``` 222 | 223 | - Figures: 224 | 225 | ````markdown 226 | See Figure \@ref(fig:cars-plot) 227 | 228 | `r ''````{r cars-plot, fig.cap="A plot caption"} 229 | plot(cars) # a scatterplot 230 | ``` 231 | ```` 232 | 233 | - Tables: 234 | 235 | ````markdown 236 | See Table \@ref(tab:mtcars) 237 | 238 | `r ''````{r mtcars} 239 | knitr::kable(mtcars[1:5, 1:5], caption = "A caption") 240 | ``` 241 | ```` 242 | 243 | - Theorems: 244 | 245 | ````markdown 246 | See Theorem \@ref(thm:boring) 247 | 248 | `r ''````{theorem, boring} 249 | Here is my theorem. 250 | ``` 251 | ```` 252 | 253 | - Equations: 254 | 255 | ````markdown 256 | See equation \@ref(eq:linear) 257 | 258 | \begin{equation} 259 | a + bx = c (\#eq:linear) 260 | \end{equation} 261 | ```` 262 | 263 | Note that only alphanumeric characters (`a-z`, `A-Z`, `0-9`), `-`, `/`, and `:` are allowed in these labels. 264 | 265 | ## Output Formats {#bookdown-output} 266 | 267 | The **bookdown** package includes the following output formats\index{output formats}: 268 | 269 | - HTML: 270 | - `gitbook` 271 | - `html_book` 272 | - `tufte_html_book` 273 | - PDF: 274 | - `pdf_book` 275 | - e-book: 276 | - `epub_book` 277 | - Single documents: 278 | - `html_document2` 279 | - `tufte_html2` 280 | - `pdf_document2` 281 | - `tufte_handout2` 282 | - `tufte_book2` 283 | - `word_document2` 284 | 285 | ### HTML 286 | 287 | Although multiple formats are available for HTML books in **bookdown**, we will focus on the Gitbook style, which appears to be the most popular format. It provides a clean style, with a table of contents on the left. The design is fully responsive to make the content suitable for both mobile and desktop devices. 288 | 289 | The output format `bookdown::gitbook` is built upon `rmarkdown::html_document`, which was explained in Section \@ref(html-document). The main difference between rendering in R Markdown and **bookdown** is that a book will generate multiple HTML pages by default. To change the way the HTML pages are split, the `split_by` argument can be specified. This defaults to `split_by: chapter`, but readers may prefer to use `split_by: section` if there are many sections within chapters, in which case a chapter page may be too long. 290 | 291 | ### LaTeX/PDF 292 | 293 | There are limited differences between the output of `pdf_book()` in **bookdown** compared to `pdf_document()` in **rmarkdown**. The primary purpose of the new format is to resolve the labels and cross-references written in the syntax described in Section \@ref(cross-referencing). 294 | 295 | Pandoc supports LaTeX commands in Markdown. Therefore if the only output format that you want for a book is LaTeX/PDF, you may use the syntax specific to LaTeX, such as `\newpage` to force a page break. A major disadvantage of this approach is that LaTeX syntax is not portable to other output formats, meaning that these changes will not be transferred to the HTML or e-book outputs. 296 | 297 | ### E-books 298 | 299 | The e-book formats can be read on devices like smartphones, tablets, or special e-readers such as Kindle. You can create an e-book of the EPUB format with `bookdown::epub_book`. 300 | 301 | ### A single document 302 | 303 | We highlighted in Section \@ref(bookdown-markdown) that **bookdown** extends the syntax provided by R Markdown, allowing automatic numbering of figures / tables / equations, and cross-referencing them. You may use **bookdown** within single-file R Markdown documents to benefit from these features. The functions `html_document2()`, `tufte_html2()`, `pdf_document2()`, `word_document2()`, `tufte_handout2()`, and `tufte_book2()` are designed for this purpose. To use this in a traditional R Markdown document, you can replace the output YAML option as follows: 304 | 305 | ````yaml 306 | --- 307 | title: "Document Title" 308 | output: bookdown::pdf_document2 309 | --- 310 | ```` 311 | 312 | ## Editing {#bookdown-edit} 313 | 314 | In this section, we explain how to edit, build, preview, and serve the book locally. 315 | 316 | ### Build the book 317 | 318 | To build all Rmd files into a book, you can call the function `bookdown::render_book()`. It uses the settings specified in the `_output.yml` (if it exists). If multiple output formats are specified in it, all formats will be built. If you are using RStudio, this can be done through the `Build` tab. Open the drop down menu `Build Book` if you only want to build one format. 319 | 320 | (ref:bookdown-build) The `Build` tab within RStudio highlighting **bookdown** output formats. 321 | 322 | ```{r bookdown-build, echo=FALSE, fig.cap="(ref:bookdown-build)", out.width='90%', fig.align='center'} 323 | knitr::include_graphics("images/bookdown-build.png", dpi = NA) 324 | ``` 325 | 326 | ### Preview a chapter 327 | 328 | Building the whole book can be slow when the size of the book is big or your book contains large amounts of computation. We can use the `preview_chapter()` function in **bookdown** to only build a single chapter at a time. Equivalently, you can click the `Knit` button in RStudio. 329 | 330 | ### Serve the book 331 | 332 | Instead of running `render_book()` or `preview_chapter()` each time you want to view the changes, you can use the function `bookdown::serve_book()` to start a live preview of the book. Any time a Rmd file is saved, the book will be recompiled automatically, and the preview will be updated to reflect the changes. 333 | 334 | ### RStudio addins 335 | 336 | The **bookdown** package comes with two addins for RStudio which assist the editing of books: 337 | 338 | - "Preview Book": this calls `bookdown::serve_book()` to compile and serve the book. 339 | 340 | - "Input LaTeX Math": provides a text box which allows you to write LaTeX equations, to avoid common errors when typing the raw LaTeX math expressions. 341 | 342 | ## Publishing {#bookdown-publish} 343 | 344 | You can generate books for both physical and electronic distribution. This section outlines some of the main options. 345 | 346 | ### RStudio Connect 347 | 348 | The easiest way to publish books online is through https://bookdown.org, which is a website provided by RStudio to host your books for free. Books can be pushed to this website by using `bookdown::publish_book()`. You will need to sign up for an account at https://bookdown.org/connect/, and your login details will be used to authorize **bookdown** the first time you call the `publish_book()` function. 349 | 350 | ### Other services 351 | 352 | You can host your book online with many other web services, such as Netlify or GitHub (via [GitHub Pages](https://pages.github.com)). Because the output from `bookdown::render_book()` is a collection of static files, you can host them using the same methods of hosting normal web pages. 353 | 354 | ### Publishers 355 | 356 | You can consider publishing physical copies of your book with a publisher or using self-publishing. Many publishers provide LaTeX style classes that can be used to set the overall appearance of the book, and these can be used easily by setting the `documentclass` option in the YAML metadata of `index.Rmd`. Further customization of the appearance of the PDF book can be achieved by altering the LaTeX preamble via the `includes: in_header` option of `bookdown::pdf_book`. 357 | -------------------------------------------------------------------------------- /19-shiny.Rmd: -------------------------------------------------------------------------------- 1 | # Shiny Documents 2 | 3 | We have briefly introduced Shiny\index{Shiny} documents in Section \@ref(intro-shiny). Shiny is a very powerful framework for building web applications based on R. It is out of the scope of this book to make a comprehensive introduction to Shiny (which is too big a topic). We recommend that readers who are not familiar with Shiny learn more about it from the website https://shiny.rstudio.com before reading this chapter. 4 | 5 | Unlike the more traditional workflow of creating static reports, you can create documents that allow your readers to change the parameters underlying your analysis and see the results immediately in Shiny R Markdown documents. In the example shown in Figure \@ref(fig:shiny), the histogram will be automatically updated to reflect the number of bins selected by the reader. 6 | 7 | A picture is worth a thousand words, and a Shiny document can potentially show you a thousand pictures as you interact with it. The readers are no longer tied to the fixed analysis and conclusions in the report. They may explore other possibilities by themselves, and possibly make new discoveries or draw different conclusions. 8 | 9 | ## Getting started {#shiny-start} 10 | 11 | You can turn any _HTML-oriented_ R Markdown documents to Shiny documents by adding `runtime: shiny` to the YAML metadata as a _top-level_ field, e.g., 12 | 13 | ```yaml 14 | --- 15 | title: "Shiny Document" 16 | output: html_document 17 | runtime: shiny 18 | --- 19 | ``` 20 | 21 | Note that the output format of the R Markdown document must be an HTML format. That is, the document should generate a web page (a `*.html` file). Non-HTML formats such as `pdf_document` and `word_document` will not work with the Shiny runtime. Please also note that some presentation formats are also HTML formats, such as `ioslides_presentation` and `slidy_presentation`. 22 | 23 | You can also create a new Shiny document from the RStudio menu `File -> New File -> R Markdown`, and choose the document type "Shiny" (see Figure \@ref(fig:shiny-new-document)). 24 | 25 | ```{r shiny-new-document, echo=FALSE, fig.cap='Create a new Shiny document in RStudio.', out.width='100%'} 26 | knitr::include_graphics('images/shiny-new-document.png', dpi = NA) 27 | ``` 28 | 29 | To run a Shiny document in RStudio, you need to click the button "Run Document" on the editor toolbar (RStudio will automatically replace the "Knit" button with "Run Document" when it detects a Shiny document). If you do not use RStudio, or want to run the document in the R console for troubleshooting, you can call the function `rmarkdown::run()` and pass the filename to it. 30 | 31 | You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change. In the following example, we create a numeric input (`numericInput`) with the name `rows`, and then refer to its value via `input$rows` when generating output: 32 | 33 | ````markdown 34 | `r ''````{r, echo=FALSE} 35 | numericInput("rows", "How many cars?", 5) 36 | 37 | renderTable({ 38 | head(cars, input$rows) 39 | }) 40 | ``` 41 | ```` 42 | 43 | ```{r shiny-table, echo=FALSE, fig.cap='Increase the number of rows in the table in a Shiny document.', out.width='100%'} 44 | knitr::include_graphics('images/shiny-table.png', dpi = NA) 45 | ``` 46 | 47 | In the above example, the output code was wrapped in a call to `renderTable()`. There are many other render functions in Shiny that can be used for plots, printed R output, and more. This example uses `renderPlot()` to create dynamic plot output: 48 | 49 | ````markdown 50 | `r ''````{r, echo=FALSE} 51 | sliderInput("bins", "Number of bins:", 30, min = 1, max = 50) 52 | 53 | renderPlot({ 54 | x = faithful[, 2] # Old Faithful Geyser data 55 | bins = seq(min(x), max(x), length.out = input$bins + 1) 56 | 57 | # draw the histogram with the specified number of bins 58 | hist(x, breaks = bins, col = 'darkgray', border = 'white') 59 | }) 60 | ``` 61 | ```` 62 | 63 | ```{r shiny-plot, echo=FALSE, fig.cap='Change the number of bins of a histogram in a Shiny document.', out.width='100%'} 64 | knitr::include_graphics('images/shiny-plot.png', dpi = NA) 65 | ``` 66 | 67 | ## Deployment {#shiny-deploy} 68 | 69 | Shiny documents must be supported by a live R session running behind the scenes. When you run a Shiny document locally, it uses your local R session. Usually only you can see and interact with the document. If you want to share the document with people who do not have R installed, or do not want to run the document locally, you will have to deploy the document on a server, and share the URL of the document. Then other people only need a web browser to visit your document. 70 | 71 | There are two ways to deploy a Shiny document. You can either use a hosted service provided by RStudio, or set up your own server. The first way is technically easier, but sometimes you may not be allowed to use an external hosted service, so you have to install the required software (Shiny Server or RStudio Connect)\index{Shiny Server}\index{RStudio Connect} on your own server to deploy the Shiny documents. 72 | 73 | ### ShinyApps.io 74 | 75 | You can publish Shiny documents to the ShinyApps (https://shinyapps.io) hosted service. To do this you, should ensure that you have: 76 | 77 | 1. An account on ShinyApps (use the signup form to request an account). 78 | 79 | 2. A latest version of the **rsconnect** R package. You can install this as follows: 80 | 81 | ```r 82 | install.packages("rsconnect") 83 | ``` 84 | 85 | You can then deploy an interactive Shiny document in the same way that you currently deploy normal Shiny applications. From the working directory containing the document(s), just execute: 86 | 87 | ```r 88 | rsconnect::deployApp() 89 | ``` 90 | 91 | If you are using RStudio, you can also use the `Publish` button available at the top-right of the window when running a Shiny document (see Figure \@ref(fig:shiny-deploy)). 92 | 93 | ```{r shiny-deploy, echo=FALSE, fig.cap='Deploy a Shiny document to ShinyApps.io.', out.width='100%'} 94 | knitr::include_graphics('images/shiny-deploy.png', dpi = NA) 95 | ``` 96 | 97 | If there is a file named `index.Rmd` in the directory, it will be served as the default document for that directory, otherwise an explicit path to the Rmd file should be specified in the URL if you want to visit this Rmd document. For example, the URL for `index.Rmd` deployed to ShinyApps may be of the form `https://example.shinyapps.io/appName/`, and the URL for `test.Rmd` may be of the form `https://example.shinyapps.io/appName/test.Rmd`. 98 | 99 | ### Shiny Server / RStudio Connect 100 | 101 | Both Shiny Server (https://www.rstudio.com/products/shiny/shiny-server/) and RStudio Connect (https://www.rstudio.com/products/connect/) can be used to publish Shiny documents. They require knowledge about Linux. Installing and configuring them should normally be a task for your system administrator if you are not familiar with Linux or do not have the privilege. 102 | 103 | ## Embedded Shiny apps {#shiny-embedded} 104 | 105 | Besides embedding individual Shiny inputs and outputs in R Markdown, it is also possible to embed a standalone Shiny application within a document. There are two ways to do this: 106 | 107 | 1. Defining the application inline using the `shinyApp()` function; or 108 | 109 | 1. Referring to an external application directory using the `shinyAppDir()` function. 110 | 111 | Both functions are available in the **shiny** package (not **rmarkdown**), which will be automatically loaded when `runtime: shiny` is specified in the YAML metadata of the document, so you do not have to call `library(shiny)` to load **shiny** (although it does not hurt if you load a package twice). 112 | 113 | ### Inline applications {#shiny-embed-inline} 114 | 115 | This example uses an inline definition: 116 | 117 | ````markdown 118 | `r ''````{r, echo=FALSE} 119 | shinyApp( 120 | 121 | ui = fluidPage( 122 | selectInput("region", "Region:", 123 | choices = colnames(WorldPhones)), 124 | plotOutput("phonePlot") 125 | ), 126 | 127 | server = function(input, output) { 128 | output$phonePlot = renderPlot({ 129 | barplot(WorldPhones[,input$region]*1000, 130 | ylab = "Number of Telephones", xlab = "Year") 131 | }) 132 | }, 133 | 134 | options = list(height = 500) 135 | ) 136 | ``` 137 | ```` 138 | 139 | Note the use of the `height` parameter to determine how much vertical space the embedded application should occupy. 140 | 141 | ### External applications 142 | 143 | This example embeds a Shiny application defined in another directory: 144 | 145 | ````markdown 146 | `r ''````{r, echo = FALSE} 147 | shinyAppDir( 148 | system.file("examples/06_tabsets", package="shiny"), 149 | options = list(width = "100%", height = 700) 150 | ) 151 | ``` 152 | ```` 153 | 154 | Note that in all of R code chunks above, the chunk option `echo = FALSE` is used. This is to prevent the R code within the chunk from rendering to the output document alongside the Shiny components. 155 | 156 | ## Shiny widgets {#shiny-widgets} 157 | 158 | Shiny widgets\index{Shiny widget} enable you to create re-usable Shiny components that are included within an R Markdown document using a single function call. Shiny widgets can also be invoked directly from the console (useful during authoring) and show their output within the RStudio Viewer pane or an external web browser. 159 | 160 | ### The `shinyApp()` function 161 | 162 | At their core, Shiny widgets are mini-applications created using the `shinyApp()` function. Rather than creating a `ui.R` and `server.R` (or `app.R`) as you would for a typical Shiny application, you pass the UI and server definitions to the `shinyApp()` function as arguments. We have given an example in Section \@ref(shiny-embed-inline). 163 | 164 | The simplest type of Shiny widget is just an R function that returns a `shinyApp()`. 165 | 166 | ### Example: k-Means clustering 167 | 168 | The **rmdexamples** package (https://github.com/rstudio/rmdexamples) includes an example of a Shiny widget implemented in this fashion. The `kmeans_cluster()` function takes a single `dataset` argument and returns a Shiny widget to show the result of k-Means clustering. You can use it within an R Markdown document like this: 169 | 170 | ````markdown 171 | `r ''````{r, echo = FALSE} 172 | library(rmdexamples) 173 | kmeans_cluster(iris) 174 | ``` 175 | ```` 176 | 177 | Figure \@ref(fig:shiny-widget-kmeans) shows what the widget looks like inside a running document. 178 | 179 | ```{r shiny-widget-kmeans, echo=FALSE, fig.cap='A Shiny widget to apply k-Means clustering on a dataset.', out.width='100%'} 180 | knitr::include_graphics('images/shiny-widget-kmeans.png', dpi = NA) 181 | ``` 182 | 183 | Below is the source code of the `kmeans_cluster()` function: 184 | 185 | ```r 186 | kmeans_cluster = function(dataset) { 187 | 188 | library(shiny) 189 | vars = names(dataset) 190 | 191 | shinyApp( 192 | ui = fluidPage( 193 | fluidRow(style = "padding-bottom: 20px;", 194 | column(4, selectInput('xcol', 'X Variable', vars)), 195 | column(4, selectInput('ycol', 'Y Variable', vars, 196 | selected = vars[2])), 197 | column(4, numericInput('clusters', 'Cluster count', 3, 198 | min = 1, max = 9)) 199 | ), 200 | fluidRow( 201 | plotOutput('kmeans', height = "400px") 202 | ) 203 | ), 204 | 205 | server = function(input, output, session) { 206 | 207 | # Combine the selected variables into a new data frame 208 | selectedData = reactive({ 209 | dataset[, c(input$xcol, input$ycol)] 210 | }) 211 | 212 | clusters = reactive({ 213 | kmeans(selectedData(), input$clusters) 214 | }) 215 | 216 | output$kmeans = renderPlot(height = 400, { 217 | res = clusters() 218 | par(mar = c(5.1, 4.1, 0, 1)) 219 | plot(selectedData(), 220 | col = res$cluster, pch = 20, cex = 3) 221 | points(res$centers, pch = 4, cex = 4, lwd = 4) 222 | }) 223 | }, 224 | 225 | options = list(height = 500) 226 | ) 227 | } 228 | ``` 229 | 230 | ### Widget size and layout 231 | 232 | Shiny widgets may be embedded in various places including standard full width pages, smaller columns within pages, and even HTML5 presentations. For the widget size and layout to work well in all of these contexts, we recommend that the total height of the widget is no larger than 500 pixels. This is not a hard and fast rule, but HTML5 slides can typically only display content less than 500px in height, so if you want your widget to be usable within presentations, this is a good guideline to follow. 233 | 234 | You can also add an explicit `height` argument to the function that creates the widget (default to 500 so it works well within slides). 235 | 236 | ## Multiple pages {#shiny-multiple} 237 | 238 | You can link to other Shiny documents by using the Markdown link syntax and specifying the *relative* path to the document, e.g., `[Another Shiny Document](another.Rmd)`. If you click the link to another Rmd document on one page, that Rmd document will be launched as the current interactive Shiny document. 239 | 240 | Currently, only one document can be active at a time, so documents cannot easily share state, although some primitive global sharing is possible via the R script `global.R` (see the help page `?rmarkdown::run`). 241 | 242 | By default, it is only possible to link to R Markdown files in the same directory subtree as the file on which `rmarkdown::run()` was invoked (e.g., you cannot link to `../foo.Rmd`). You can use the `dir` argument of `rmarkdown::run()` to indicate the directory to be treated as the root. 243 | 244 | ## Delayed rendering {#shiny-delay} 245 | 246 | A Shiny document is typically rendered every time it is shown, and is not shown to the user until the rendering is complete. Consequently, a document that is large or contains expensive computations may take some time to load. 247 | 248 | If your document contains interactive Shiny components that do not need to be rendered right away, you can wrap Shiny code in the `rmarkdown::render_delayed()` function. This function saves its argument until the document's rendering is done and has been shown to the user, then evaluates it and injects it into the output document when the computation is finished. 249 | 250 | Here is an example that demonstrates how `render_delayed()` works. The code enclosed within the `render_delayed()` call will execute only after the document has been loaded and displayed to the user: 251 | 252 | ````markdown 253 | `r ''````{r, echo = FALSE} 254 | numericInput("rows", "How many cars?", 5) 255 | 256 | rmarkdown::render_delayed({ 257 | renderTable({ 258 | head(cars, input$rows) 259 | }) 260 | }) 261 | ``` 262 | ```` 263 | 264 | ## Output arguments for render functions {#shiny-args} 265 | 266 | In a typical Shiny application, you specify an output element in the UI using functions like `plotOutput()` and `verbatimTextOutput()`, and render its content using functions like `renderPlot()` and `renderPrint()`. 267 | 268 | By comparison, in a Shiny document, the UI elements are often implicitly and automatically created when you call the `renderXXX()` functions. For example, you may want to use a `renderPlot()` function without having to create a `plotOutput()` slot beforehand. In this case, Shiny helpfully associates the corresponding output object to each `renderXXX()` function, letting you use Shiny code outside of a full Shiny app. However, some functionality can be lost in this process. In particular, `plotOutput()` can take in some optional arguments to set things like width and height, or allow you to click or brush over the plot (and store that information). 269 | 270 | To pass options from `renderXXX()` to `xxxOutput()`, you can use the `outputArgs` argument, if it is available to specific `renderXXX()` functions. For example, suppose that you want to render a plot and specify its width to be 200px and height to be 100px. Then you should use: 271 | 272 | ````markdown 273 | `r ''````{r, echo = FALSE} 274 | renderPlot({ 275 | plot(yourData) 276 | }, outputArgs = list(width = "200px", height = "100px") 277 | ) 278 | ``` 279 | ```` 280 | 281 | No matter how many output arguments you want to set (all the way from zero to all possible ones), `outputArgs` always takes in a list (the default is an empty list, which sets no output arguments). If you try to pass in a non-existent argument, you will get an error like the following message (in this example, you tried to set an argument named `not_an_argument`): 282 | 283 | ```markdown 284 | **Error**: Unused argument: in `outputArgs`, `not_an_argument` 285 | is not an valid argument for the output function 286 | ``` 287 | 288 | To see `outputArgs` in action, run the R Markdown document below or visit https://gallery.shinyapps.io/output-args/ for the live version online. The document is interactive: brush over the image and see the `xmin`, `xmax`, `ymin`, and `ymax` values change (printed right under the image). 289 | 290 | ````markdown 291 | `r xfun::file_string('examples/shiny-output-args.Rmd')` 292 | ```` 293 | 294 | ### A caveat 295 | 296 | We want to emphasize that you can only use this functionality within a Shiny R Markdown document (i.e., you must set `runtime: shiny` in the YAML metadata). But even if that is the case, this is only applicable to pieces of Shiny code that render output without the corresponding explicit output elements in the UI. If you embed a full Shiny application in your document and try to use `outputArgs`, it will be ignored and print the following warning to the R Markdown console (in this case, your `ui` function would be something like `ui = plotOutput("plot")`): 297 | 298 | ```markdown 299 | Warning in `output$plot`(...) : 300 | Unused argument: outputArgs. The argument outputArgs is only 301 | meant to be used when embedding snippets of Shiny code in an 302 | R Markdown code chunk (using runtime: shiny). When running a 303 | full Shiny app, please set the output arguments directly in 304 | the corresponding output function of your UI code. 305 | ``` 306 | 307 | The same will happen if you try to use `outputArgs` in any other context, such as inside a regular (i.e., not embedded) Shiny app. The rationale is that if you are already specifying a `ui` function with all the `output` objects made explicit, you should set their arguments directly there instead of going through this round-about way. 308 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public 421 | licenses. Notwithstanding, Creative Commons may elect to apply one of 422 | its public licenses to material it publishes and in those instances 423 | will be considered the “Licensor.” The text of the Creative Commons 424 | public licenses is dedicated to the public domain under the CC0 Public 425 | Domain Dedication. Except for the limited purpose of indicating that 426 | material is shared under a Creative Commons public license or as 427 | otherwise permitted by the Creative Commons policies published at 428 | creativecommons.org/policies, Creative Commons does not authorize the 429 | use of the trademark "Creative Commons" or any other trademark or logo 430 | of Creative Commons without its prior written consent including, 431 | without limitation, in connection with any unauthorized modifications 432 | to any of its public licenses or any other arrangements, 433 | understandings, or agreements concerning use of licensed material. For 434 | the avoidance of doubt, this paragraph does not form part of the 435 | public licenses. 436 | 437 | Creative Commons may be contacted at creativecommons.org. 438 | 439 | -------------------------------------------------------------------------------- /index.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "R Markdown: The Definitive Guide" 3 | author: "Yihui Xie, J. J. Allaire, Garrett Grolemund" 4 | date: "`r Sys.Date()`" 5 | documentclass: krantz 6 | bibliography: [book.bib, packages.bib] 7 | biblio-style: apalike 8 | link-citations: yes 9 | colorlinks: yes 10 | graphics: yes 11 | lot: yes 12 | lof: yes 13 | fontsize: 11pt 14 | site: bookdown::bookdown_site 15 | description: "The first official book authored by the core R Markdown developers that provides a comprehensive and accurate reference to the R Markdown ecosystem. With R Markdown, you can easily create reproducible data analysis reports, presentations, dashboards, interactive applications, books, dissertations, websites, and journal articles, while enjoying the simplicity of Markdown and the great power of R and other languages." 16 | url: 'https\://bookdown.org/yihui/rmarkdown/' 17 | github-repo: rstudio/rmarkdown-book 18 | cover-image: images/cover.png 19 | --- 20 | 21 | ```{r setup, include=FALSE} 22 | options( 23 | htmltools.dir.version = FALSE, formatR.indent = 2, 24 | width = 55, digits = 4, warnPartialMatchAttr = FALSE, warnPartialMatchDollar = FALSE 25 | ) 26 | 27 | options(bookdown.post.latex = function(x) { 28 | # only build a skeleton for the online version 29 | if (Sys.getenv('BOOKDOWN_FULL_PDF', '') == 'false') return(bookdown:::strip_latex_body( 30 | x, '\nThis PDF is only a skeleton. Please either read the free online HTML version, or purchase a hard-copy of this book.\n' 31 | )) 32 | 33 | # fix syntax highlighting: 34 | # \FunctionTok{tufte:}\AttributeTok{:tufte_html: default} -> 35 | # \FunctionTok{tufte::tufte_html:}\AttributeTok{ default} 36 | x = gsub('(\\\\FunctionTok\\{[^:]+:)(})(\\\\AttributeTok\\{)(:[^:]+:)', '\\1\\4\\2\\3', x) 37 | # an ugly hack for Table 16.1 (Pandoc's widths are not good) 38 | if (length(i <- grep('\\caption{\\label{tab:sizing-policy}', x, fixed = TRUE)) == 0) 39 | stop('Table 16.1 not found') 40 | x[i - 1] = gsub('\\real{0.50}', '\\real{0.67}', x[i - 1], fixed = TRUE) 41 | x[i - 2] = gsub('\\real{0.50}', '\\real{0.33}', x[i - 2], fixed = TRUE) 42 | # not sure if the following tweaks are still necessary 43 | if (FALSE) { 44 | if (length(i <- grep('^\\\\begin\\{longtable\\}', x)) == 0) return(x) 45 | i1 = bookdown:::next_nearest(i, which(x == '\\toprule')) 46 | i2 = bookdown:::next_nearest(i, which(x == '\\endfirsthead')) 47 | x[i1 - 1] = paste0(x[i1 - 1], '\n\\begin{tabular}{', gsub('[^lcr]', '', gsub('.*\\[]', '', x[i])), '}') 48 | x[i] = '\\begin{table}' 49 | x[x == '\\end{longtable}'] = '\\end{tabular}\n\\end{table}' 50 | x[x == '\\endhead'] = '' 51 | x = x[-unlist(mapply(seq, i1, i2, SIMPLIFY = FALSE))] 52 | } 53 | x 54 | }) 55 | 56 | knitr::opts_chunk$set(webshot = "webshot2") 57 | ``` 58 | 59 | # Preface {-} 60 | 61 | ```{asis, echo=identical(knitr:::pandoc_to(), 'html')} 62 | **Note**: This book has been published by [Chapman & Hall/CRC](https://www.crcpress.com/p/book/9781138359338). The online version of this book is free to read here (thanks to Chapman & Hall/CRC), and licensed under the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-nc-sa/4.0/). 63 | 64 |

    The R Markdown book cover

    65 | ``` 66 | 67 | The document format "R Markdown" was first introduced in the **knitr** package [@xie2015; @R-knitr] in early 2012. The idea was to embed code chunks (of R or other languages) in Markdown documents. In fact, **knitr** supported several authoring languages from the beginning in addition to Markdown, including LaTeX, HTML, AsciiDoc, reStructuredText, and Textile. Looking back over the five years, it seems to be fair to say that Markdown has become the most popular document format, which is what we expected. The simplicity of Markdown clearly stands out among these document formats. 68 | 69 | However, the original version of Markdown [invented by John Gruber](https://en.wikipedia.org/wiki/Markdown) was often found overly simple and not suitable to write highly technical documents. For example, there was no syntax for tables, footnotes, math expressions, or citations. Fortunately, John MacFarlane created a wonderful package named Pandoc (http://pandoc.org) to convert Markdown documents (and many other types of documents) to a large variety of output formats. More importantly, the Markdown syntax was significantly enriched. Now we can write more types of elements with Markdown while still enjoying its simplicity. 70 | 71 | In a nutshell, R Markdown stands on the shoulders of **knitr** and Pandoc. The former executes the computer code embedded in Markdown, and converts R Markdown to Markdown. The latter renders Markdown to the output format you want (such as PDF, HTML, Word, and so on). 72 | 73 | ```{r fig.align='center', echo=FALSE, include=identical(knitr:::pandoc_to(), 'html'), fig.link='https://github.com/rstudio/rmarkdown', out.width='30%'} 74 | knitr::include_graphics('images/hex-rmarkdown.png', dpi = NA) 75 | ``` 76 | 77 | The **rmarkdown** package [@R-rmarkdown] was first created in early 2014. During the past four years, it has steadily evolved into a relatively complete ecosystem for authoring documents, so it is a good time for us to provide a definitive guide to this ecosystem now. At this point, there are a large number of tasks that you could do with R Markdown: 78 | 79 | - Compile a single R Markdown document to a report in different formats, such as PDF, HTML, or Word. 80 | 81 | - Create notebooks in which you can directly run code chunks interactively. 82 | 83 | - Make slides for presentations (HTML5, LaTeX Beamer, or PowerPoint). 84 | 85 | - Produce dashboards with flexible, interactive, and attractive layouts. 86 | 87 | - Build interactive applications based on Shiny. 88 | 89 | - Write journal articles. 90 | 91 | - Author books of multiple chapters. 92 | 93 | - Generate websites and blogs. 94 | 95 | There is a fundamental assumption underneath R Markdown that users should be aware of: we assume it suffices that only a limited number of features are supported in Markdown. By "features", we mean the types of elements you can create with native Markdown. The limitation is a great feature, not a bug. R Markdown may not be the right format for you if you find these elements not enough for your writing: paragraphs, (section) headers, block quotations, code blocks, (numbered and unnumbered) lists, horizontal rules, tables, inline formatting (emphasis, strikeout, superscripts, subscripts, verbatim, and small caps text), LaTeX math expressions, equations, links, images, footnotes, citations, theorems, proofs, and examples. We believe this list of elements suffice for most technical and non-technical documents. It may not be impossible to support other types of elements in R Markdown, but you may start to lose the simplicity of Markdown if you wish to go that far. 96 | 97 | Epictetus once said, "_Wealth consists not in having great possessions, but in having few wants._" The spirit is also reflected in Markdown. If you can control your preoccupation with pursuing typesetting features, you should be much more efficient in writing the content and can become a prolific author. It is entirely possible to succeed with simplicity. Jung Jae-sung was a legendary badminton player with a remarkably simple playing style: he did not look like a talented player and was very short compared to other players, so most of the time you would just see him jump three feet off the ground and smash like thunder over and over again in the back court until he beats his opponents. 98 | 99 | Please do not underestimate the customizability of R Markdown because of the simplicity of its syntax. In particular, Pandoc templates can be surprisingly powerful, as long as you understand the underlying technologies such as LaTeX and CSS, and are willing to invest time in the appearance of your output documents (reports, books, presentations, and/or websites). As one example, you may check out the [PDF report](http://files.kff.org/attachment/Report-Employer-Health-Benefits-Annual-Survey-2017) of the [2017 Employer Health Benefits Survey](https://www.kff.org/health-costs/report/2017-employer-health-benefits-survey/). It looks fairly sophisticated, but was actually produced via **bookdown** [@xie2016], which is an R Markdown extension. A custom LaTeX template and a lot of LaTeX tricks were used to generate this report. Not surprisingly, this very book that you are reading right now was also written in R Markdown, and its full source is publicly available in the GitHub repository https://github.com/rstudio/rmarkdown-book. 100 | 101 | R Markdown documents are often portable in the sense that they can be compiled to multiple types of output formats. Again, this is mainly due to the simplified syntax of the authoring language, Markdown. The simpler the elements in your document are, the more likely that the document can be converted to different formats. Similarly, if you heavily tailor R Markdown to a specific output format (e.g., LaTeX), you are likely to lose the portability, because not all features in one format work in another format. 102 | 103 | Last but not least, your computing results will be more likely to be reproducible if you use R Markdown (or other **knitr**-based source documents), compared to the manual cut-and-paste approach. This is because the results are dynamically generated from computer source code. If anything goes wrong or needs to be updated, you can simply fix or update the source code, compile the document again, and the results will be automatically updated. You can enjoy reproducibility and convenience at the same time. 104 | 105 | ## How to read this book {-} 106 | 107 | This book may serve you better as a reference book than a textbook. It contains a large number of technical details, and we do not expect you to read it from beginning to end, since you may easily feel overwhelmed. Instead, think about your background and what you want to do first, and go to the relevant chapters or sections. For example: 108 | 109 | - I just want to finish my course homework (Chapter \@ref(basics) should be more than enough for you). 110 | 111 | - I know this is an R Markdown book, but I use Python more than R (Go to Section \@ref(python)). 112 | 113 | - I want to embed interactive plots in my reports, or want my readers to be able change my model parameters interactively and see results on the fly (Check out Section \@ref(interactive-documents)). 114 | 115 | - I know the output format I want to use, and I want to customize its appearance (Check out the documentation of the specific output format in Chapter \@ref(documents) or Chapter \@ref(presentations)). For example, I want to customize the template for my PowerPoint presentation (Go to Section \@ref(ppt-templates)). 116 | 117 | - I want to build a business dashboard highlighting some key figures and indicators (Go to Chapter \@ref(dashboards)). 118 | 119 | - I heard about `yolo = TRUE` from a friend, and I'm curious what that means in the **xaringan** package (Go to Chapter \@ref(xaringan)). 120 | 121 | - I want to build a personal website (Go to Chapter \@ref(websites)), or write a book (Go to Chapter \@ref(books)). 122 | 123 | - I want to write a paper and submit to the Journal of Statistical Software (Go to Chapter \@ref(journals)). 124 | 125 | - I want to build an interactive tutorial with exercises for my students to learn a topic (Go to Chapter \@ref(learnr)). 126 | 127 | - I'm familiar with R Markdown now, and I want to generate personalized reports for all my customers using the same R Markdown template (Try parameterized reports in Chapter \@ref(parameterized-reports)). 128 | 129 | - I know some JavaScript, and want to build an interface in R to call an interested JavaScript library from R (Learn how to develop HTML widgets in Chapter \@ref(html-widgets)). 130 | 131 | - I want to build future reports with a company branded template that shows our logo and uses our unique color theme (Go to Chapter \@ref(document-templates)). 132 | 133 | If you are not familiar with R Markdown, we recommend that you read at least Chapter \@ref(basics) to learn the basics. All the rest of the chapters in this book can be read in any order you desire. They are pretty much orthogonal to each other. However, to become familiar with R Markdown output formats, you may want to thumb through the HTML document format in Section \@ref(html-document), because many other formats share the same options as this format. 134 | 135 | ## Structure of the book {-} 136 | 137 | This book consists of four parts. Part I covers the basics: Chapter \@ref(installation) introduces how to install the relevant packages, and Chapter \@ref(basics) is an overview of R Markdown, including the possible output formats, the Markdown syntax, the R code chunk syntax, and how to use other languages in R Markdown. 138 | 139 | Part II is the detailed documentation of built-in output formats in the **rmarkdown** package, including document formats and presentation formats. 140 | 141 | Part III lists about ten R Markdown extensions that enable you to build different applications or generate output documents with different styles. Chapter \@ref(dashboards) introduces the basics of building flexible dashboards with the R package **flexdashboard**. Chapter \@ref(tufte-handouts) documents the **tufte** package, which provides a unique document style used by Edward Tufte. Chapter \@ref(xaringan) introduces the **xaringan** package for another highly flexible and customizable HTML5 presentation format based on the JavaScript library remark.js. Chapter \@ref(revealjs) documents the **revealjs** package, which provides yet another appealing HTML5 presentation format based on the JavaScript library reveal.js. Chapter \@ref(community) introduces a few output formats created by the R community, such as the **prettydoc** package, which features lightweight HTML document formats. Chapter \@ref(websites) teaches you how to build websites using either the **blogdown** package or **rmarkdown**'s built-in site generator. Chapter \@ref(pkgdown) explains the basics of the **pkgdown** package, which can be used to quickly build documentation websites for R packages. Chapter \@ref(books) introduces how to write and publish books with the **bookdown** package. Chapter \@ref(journals) is an overview of the **rticles** package for authoring journal articles. Chapter \@ref(learnr) introduces how to build interactive tutorials with exercises and/or quiz questions. 142 | 143 | Part IV covers other topics about R Markdown, and some of them are advanced (in particular, Chapter \@ref(html-widgets)). Chapter \@ref(parameterized-reports) introduces how to generate different reports with the same R Markdown source document and different parameters. Chapter \@ref(html-widgets) teaches developers how to build their own HTML widgets for interactive visualization and applications with JavaScript libraries. Chapter \@ref(document-templates) shows how to create custom R Markdown and Pandoc templates so that you can fully customize the appearance and style of your output document. Chapter \@ref(new-formats) explains how to create your own output formats if the existing formats do not meet your need. Chapter \@ref(shiny-documents) shows how to combine the Shiny framework with R Markdown, so that your readers can interact with the reports by changing the values of certain input widgets and seeing updated results immediately. 144 | 145 | Note that this book is intended to be a guide instead of the comprehensive documentation of all topics related to R Markdown. Some chapters are only overviews, and you may need to consult the full documentation elsewhere (often freely available online). Such examples include Chapters \@ref(dashboards), \@ref(websites), \@ref(pkgdown), \@ref(books), and \@ref(learnr). 146 | 147 | ## Software information and conventions {#software-info .unnumbered} 148 | 149 | The R session information when compiling this book is shown below: 150 | 151 | ```{r tidy=FALSE} 152 | xfun::session_info(c( 153 | 'blogdown', 'bookdown', 'knitr', 'rmarkdown', 'htmltools', 154 | 'reticulate', 'rticles', 'flexdashboard', 'learnr', 'shiny', 155 | 'revealjs', 'pkgdown', 'tinytex', 'xaringan', 'tufte' 156 | ), dependencies = FALSE) 157 | ``` 158 | 159 | We do not add prompts (`>` and `+`) to R source code in this book, and we comment out the text output with two hashes `##` by default, as you can see from the R session information above. This is for your convenience when you want to copy and run the code (the text output will be ignored since it is commented out). Package names are in bold text (e.g., **rmarkdown**), and inline code and filenames are formatted in a typewriter font (e.g., `knitr::knit('foo.Rmd')`). Function names are followed by parentheses (e.g., `blogdown::serve_site()`). The double-colon operator `::` means accessing an object from a package. 160 | 161 | "Rmd" is the filename extension of R Markdown files, and also an abbreviation of R Markdown in this book. 162 | 163 | ## Acknowledgments {-} 164 | 165 | I started writing this book after I came back from the 2018 RStudio Conference in early February, and finished the first draft in early May. This may sound fast for a 300-page book. The main reason I was able to finish it quickly was that I worked full-time on this book for three months. My employer, RStudio, has always respected my personal interests and allowed me to focus on projects that I choose by myself. More importantly, I have been taught several lessons on how to become a professional software engineer since I joined RStudio as a fresh PhD, although [the initial journey turned out to be painful.](https://yihui.name/en/2018/02/career-crisis/) It is a great blessing for me to work in this company. 166 | 167 | The other reason for my speed was that JJ and Garrett had already prepared a lot of materials that I could adapt for this book. They had also been offering suggestions as I worked on the manuscript. In addition, [Michael Harper](http://mikeyharper.uk) contributed the initial drafts of Chapters \@ref(books), \@ref(journals), \@ref(parameterized-reports), \@ref(document-templates), and \@ref(new-formats). I would definitely not be able to finish this book so quickly without their help. 168 | 169 | The most challenging thing to do when writing a book is to find large blocks of uninterrupted time. This is just so hard. Both others and myself could interrupt me. I do not consider my willpower to be strong: I read random articles, click on the endless links on Wikipedia, look at random Twitter messages, watch people fight on meaningless topics online, reply to emails all the time as if I were able to reach "Inbox Zero", and write random blog posts from time to time. The two most important people in terms of helping keep me on track are Tareef Kawaf (President of RStudio), to whom I report my progress on the weekly basis, and [Xu Qin](https://www.education.pitt.edu/people/XuQin), from whom [I really learned](https://d.cosx.org/d/419325) the importance of making plans on a daily basis (although I still fail to do so sometimes). For interruptions from other people, it is impossible to isolate myself from the outside world, so I'd like to thank those who did not email me or ask me questions in the past few months and used public channels instead [as I suggested](https://yihui.name/en/2017/08/so-gh-email/). I also thank those who did not get mad at me when my responses were extremely slow or even none. I appreciate all your understanding and patience. Besides, several users have started helping me answer GitHub and Stack Overflow questions related to R packages that I maintain, which is even better! These users include [Marcel Schilling](https://yihui.name/en/2018/01/thanks-marcel-schilling/), [Xianying Tan](https://shrektan.com), [Christophe Dervieux](https://github.com/cderv), and [Garrick Aden-Buie](https://www.garrickadenbuie.com), just to name a few. As someone who works from home, apparently I would not even have ten minutes of uninterrupted time if I do not send the little ones to daycare, so I want to thank all teachers at Small Miracle for freeing my daytime. 170 | 171 | There have been a large number of contributors to the R Markdown ecosystem. [More than 60 people](https://github.com/rstudio/rmarkdown/graphs/contributors) have contributed to the core package, **rmarkdown**. Several authors have created their own R Markdown extensions, as introduced in Part III of this book. Contributing ideas is no less helpful than contributing code. We have gotten numerous inspirations and ideas from the R community via various channels (GitHub issues, Stack Overflow questions, and private conversations, etc.). As a small example, Jared Lander, author of the book _R for Everyone_, does not meet me often, but every time he chats with me, I will get something valuable to work on. "How about writing books with R Markdown?" he asked me at the 2014 Strata conference in New York. Then we invented **bookdown** in 2016. "I really need fullscreen background images in ioslides. [Look, Yihui, here are my ugly JavaScript hacks,](https://www.jaredlander.com/2017/07/fullscreen-background-images-in-ioslides-presentations/)" he showed me on the shuttle to dinner at the 2017 RStudio Conference. A year later, background images were officially supported in ioslides presentations. 172 | 173 | As I mentioned previously, R Markdown is standing on the shoulders of the giant, Pandoc. I'm always amazed by how fast John MacFarlane, the main author of Pandoc, responds to my GitHub issues. It is hard to imagine a person dealing with [5000 GitHub issues](https://github.com/jgm/pandoc) over the years while maintaining the excellent open-source package and driving the Markdown standards forward. We should all be grateful to John and contributors of Pandoc. 174 | 175 | As I was working on the draft of this book, I received a lot of helpful reviews from these reviewers: John Gillett (University of Wisconsin), Rose Hartman (UnderstandingData), Amelia McNamara (Smith College), Ariel Muldoon (Oregon State University), Yixuan Qiu (Purdue University), Benjamin Soltoff (University of Chicago), 176 | David Whitney (University of Washington), and Jon Katz (independent data analyst). Tareef Kawaf (RStudio) also volunteered to read the manuscript and provided many helpful comments. [Aaron Simumba](https://asimumba.rbind.io), [Peter Baumgartner](http://peter.baumgartner.name), and [Daijiang Li](https://daijiang.name) volunteered to carefully correct many of my typos. In particular, Aaron has been such a big helper with my writing (not limited to only this book) and [sometimes I have to compete with him](https://github.com/rbind/yihui/commit/d8f39f7aa) in correcting my typos! 177 | 178 | There are many colleagues at RStudio whom I want to thank for making it so convenient and even enjoyable to author R Markdown documents, especially the RStudio IDE team including J.J. Allaire, Kevin Ushey, Jonathan McPherson, and many others. 179 | 180 | Personally I often feel motivated by members of the R community. My own willpower is weak, but I can gain a lot of power from this amazing community. Overall the community is very encouraging, and sometimes even fun, which makes me enjoy my job. For example, I do not think you can often use the picture of a professor for fun in your software, but the ["desiccated baseR-er"](https://twitter.com/kwbroman/status/922545181634768897) Karl Broman is an exception (see Section \@ref(yolo-true)), as he allowed me to use a mysteriously happy picture of him. 181 | 182 | Lastly, I want to thank my editor, John Kimmel, for his continued help with my fourth book. I think I have said enough about him and his team at Chapman & Hall in my previous books. The publishing experience has always been so smooth. I just wonder if it would be possible someday that our meticulous copy-editor, Suzanne Lassandro, would fail to identify more than 30 issues for me to correct in my first draft. Probably not. Let's see. 183 | 184 | ```{block2, type='flushright', html.tag='p'} 185 | Yihui Xie 186 | Elkhorn, Nebraska 187 | ``` 188 | --------------------------------------------------------------------------------