` 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 | 
185 | 
186 |
187 | 
188 | 
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 | {width="90%"}
197 |
198 | {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 |

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 |
--------------------------------------------------------------------------------