Finishes Reproducible Research (R Markdown) chapter.

This commit is contained in:
Garrett 2016-08-18 17:34:32 -04:00
parent 4cf15b541d
commit adadde3d9f
3 changed files with 314 additions and 79 deletions

BIN
images/inline-1-heat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 341 KiB

View File

@ -19,7 +19,7 @@ install.packages("rmarkdown")
## Basics
[This](https://github.com/hadley/r4ds/tree/master/rmarkdown-demos/1-example.Rmd) is an R Markdown file, a plain text file that has the extension `.Rmd`. Notice that it contains three types of content:
[This](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/1-example.Rmd) is an R Markdown file, a plain text file that has the extension `.Rmd`. Notice that it contains three types of content:
* An (optional) YAML header surrounded by `---`s
* code chunks surrounded by <code>```</code>s
@ -31,7 +31,7 @@ cat(htmltools::includeText("rmarkdown-demos/1-example.Rmd"))
### A Notebook Interface
When you open the file in the RStudio IDE, it becomes a [notebook interface for R](http://rmarkdown.rstudio.com/r_notebooks.html). You can run each code chunk by clicking the Run icon (it looks like a play button at the top of the chunk). RStudio executes the code and display the results inline with your file.
When you open the file in the RStudio IDE, it becomes a notebook interface for R. You can run each code chunk by clicking the Run icon (it looks like a play button at the top of the chunk). RStudio executes the code and displays the results inline with your file.
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/how-1-file.png")
@ -39,7 +39,7 @@ knitr::include_graphics("images/how-1-file.png")
### Rendering output
To generate a report from the file, run the `render()` command:
To generate a report from an R Markdown file, run the `render()` command:
```{r eval = FALSE}
library(rmarkdown)
@ -66,7 +66,7 @@ This may sound complicated, but R Markdown makes it extremely simple by encapsul
## Get Started
To open a new .Rmd file, open the RStudio IDE and select File > New File > R Markdown... in the menubar. RStudio will launch a wizard that you can use to pre-populate your file with useful content. You can erase or add to the content as you wish.
To open a new .Rmd file, open the RStudio IDE and select *File > New File > R Markdown...* in the menubar. RStudio will launch a wizard that you can use to pre-populate your file with useful content. You can erase or add to the content as you wish.
## Code Chunks
@ -76,13 +76,13 @@ You can quickly insert code chunks into your file with
* the Add Chunk icon in the editor toolbar (it looks like a green box with a C in it)
* or by typing the chunk delimiters ` ```{r} ` and ` ``` `.
Test chunks as you write by clicking the "Run Current Chunk" and "Run All Chunks Above" icons at the top of each chunk. R Markdown will run the code in the chunks in your current environment and display the results in your file editor. To turn off this behavior, click the gear icon at the top of the .Rmd file and select "Chunk Output in the Console." RStudio will then run code chunks at the command line as if your .Rmd file were an R Script.
Test code as you write by clicking the "Run Current Chunk" and "Run All Chunks Above" icons at the top of each chunk. R Markdown will run the code in the chunks in your current environment and display the results in your file editor. To turn off this behavior, click the gear icon at the top of the .Rmd file and select "Chunk Output in the Console." RStudio will then run code chunks at the command line as if your .Rmd file were an R Script.
When you render your .Rmd file, R Markdown will create a fresh environment to run the code chunks in. It will run each code chunk in order and embed the results beneath the chunk in your final report.
When you render your .Rmd file, R Markdown will create a fresh environment to run the code chunks in. It will run each chunk, in order, and embed the results beneath the chunk in your final report.
### Chunk Options
Chunk output can be customized with [knitr options](http://yihui.name/knitr/options/), arguments set in the `{}` of a chunk header. For example, the above file uses five arguments:
Chunk output can be customized with [knitr options](http://yihui.name/knitr/options/), arguments set in the `{}` of a chunk header. For example, the above file (1-example.Rmd) uses five arguments:
* `include = FALSE` prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks.
* `echo = FALSE` prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
@ -90,8 +90,6 @@ Chunk output can be customized with [knitr options](http://yihui.name/knitr/opti
* `warning = FALSE` prevents warnings that are generated by code from appearing in the finished.
* `fig.cap = "..."` adds a caption to graphical results.
See the [R Markdown Reference Guide](https://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf) for a complete list of knitr chunk options.
Knitr provides almost 60 options that you can use to customize your code chunks. Since the options are not associated with an R function, it can be difficult to figure out where to learn about them. The best place is the knitr options web page at <http://yihui.name/knitr/options/>.
You can also find a list of knitr options with concise descriptions in the *R Markdown Reference Guide*, which is available in the RStudio IDE under *Help > Cheatsheets > R Markdown Reference Guide*.
@ -101,7 +99,7 @@ Here are some of the most useful options not listed above.
* `cache = TRUE` caches code results to minimize future computation (caching is explained further below).
* `child = "file.Rmd"` renders a file and inserts the results into the main document at the chunk location.
* `comment = "##"` changes the prefix to put before each line of output.
* `error = FALSE` causes the render to stop is code returns an error.
* `error = FALSE` causes the render to stop if code returns an error.
* `eval = FALSE` prevents code from being evaluated. Useful for displaying example code.
* `out.width = "50%"` adjusts the width of the plot in the final output file.
* `results = 'hide'` prevents the results, but not the code, from appearing in the final document. Knitr still runs the code.
@ -114,17 +112,51 @@ To set global options that apply to every chunk in your file, call `knitr::opts_
knitr::opts_chunk$set(echo = FALSE, cache = TRUE)
```
Knitr will treat each option that you pass to `knitr::opts_chunk$set` as a global default that applies to all chunks, but can be overwritten in individual chunk headers.
Knitr will treat each option that you pass to `knitr::opts_chunk$set` as a global default that applies to all chunks. You can overwrite global options locally in individual chunk headers.
### Caching
If document rendering becomes time consuming due to long computations you can use knitr caching to improve performance.
If document rendering becomes time consuming due to long computations, you can use knitr caching to improve performance.
TO DO
Knitr will save the output of any chunk that contains the option `cache = TRUE` along with a MD5 digest of its contents to a folder alongside your .Rmd file. On subsequent renders, knitr will check the digest to see if the chunk contents have changed. If they have not, knitr will skip the chunk and insert the cached contents. If they have changed (i.e. if the chunk has been modified) Knitr will execute the chunk, embed the results, and save the new results to use for future renders.
Knitr's caching system is straightforward but can become complicated when one code chunk depends on the contents of another. For example, here chunk 2 depends on chunk 1.
```{r eval = FALSE}
# chunk 1
` ``{r}
a <- 1
` ``
# chunk 2
` ``{r cached=TRUE}
a + 1
` ``
```
To ensure that caching works properly in this situation, give each chunk a chunk label (Knitr assumes that the first unnamed option in the chunk header is a label). Then set the `dependson` option of the cached chunk.
```{r eval = FALSE}
# chunk 1
` ``{r chunk1}
a <- 1
` ``
# chunk 2
` ``{r chunk2, cached = TRUE, dependson = "chunk1"}
a + 1
` ``
```
`dependson` should contain a character vector of *every* chunk that the cached chunk depends on. Knitr will update the results for the cached chunk whenever it detects that one of its dependencies have changed.
## Inline code
Code results can be inserted directly into the *text* of a .Rmd file by enclosing the code with `` `r ` ``. The [file below](rmarkdown-demos/3-inline.Rmd) uses `` `r ` `` twice to call `colorFunc`, which returns "heat.colors." This makes it easy to update the report to refer to another function.
Code results can be inserted directly into the *text* of a .Rmd file by enclosing the code with `` `r ` ``. The [file below](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/3-inline.Rmd) uses `` `r ` `` twice to call `colorFunc`, which returns "heat.colors." This makes it easy to update the report to refer to another function.
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/inline-1-heat.png")
```
Inline expressions do not take knitr options. When processing inline code, R Markdown will always
@ -135,7 +167,7 @@ As a result, inline output is indistinguishable from the surrounding text.
## Code Languages
[knitr](http://yihui.name/knitr/) can execute code in many languages besides R, which makes it easy to write R Markdown files that are multiple languages. Some of the available language engines include:
[knitr](http://yihui.name/knitr/) can execute code in many languages besides R, which makes it easy to write R Markdown files that use multiple languages. Some of the available language engines include:
* Python
* SQL
@ -158,21 +190,21 @@ Note that chunk options like `echo` and `results` are all valid when using a lan
## Parameters
R Markdown documents can include one or more parameters whose values can be set when you render the report. For example, the [file below](rmarkdown-demos/5-parameters.Rmd) uses a `data` parameter that determines which data set to plot.
R Markdown documents can include one or more parameters whose values can be set when you render the report. Parameters are useful when you want to re-render the same report with distinct values for various key inputs, for example, to run:
* a report specific to a department or geographic region.
* a report that covers a specific period in time.
* multiple versions of a report for distinct sets of core assumptions.
To declare one or more parameters for your file, use the `params` field within the YAML header of the document. For example, the [file below](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/5-parameters.Rmd) uses a `data` parameter that determines which data set to plot.
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/params-1-hawaii.png")
```
Parameters are useful when you want to re-render the same report with distinct values for various key inputs, for example:
* Running a report specific to a department or geographic region.
* Running a report that covers a specific period in time.
* Running multiple versions of a report for distinct sets of core assumptions.
To declare one or more parameters for your file, use the `params` field within the YAML header of the document. Here we create the parameter `data` and assign it the default value `"hawaii"`. R Markdown recognizes the atomic data types: numerics, character strings, logicals, etc. You can also pass an R expression as a parameter by prefacing the parameter value with `!R`, e.g.
R Markdown recognizes the atomic data types: numerics, character strings, logicals, etc. You can also pass an R expression as a parameter by prefacing the parameter value with `!R`, e.g.
```{r eval = FALSE}
---
@ -204,7 +236,7 @@ knitr::include_graphics("images/params-3-florida.png")
## Tables
By default, R Markdown displays data frames and matrixes as they would be in the R terminal (in a monospaced font). If you prefer that data be displayed with additional formatting you can use the `knitr::kable` function, as in the [.Rmd file below](rmarkdown-demos/6-tables.Rmd).
By default, R Markdown displays data frames and matrixes as they would be in the R terminal (in a monospaced font). If you prefer that data be displayed with additional formatting you can use the `knitr::kable` function, as in the [.Rmd file below](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/6-tables.Rmd).
Note the use of the `results='asis'` chunk option. This is required to ensure that the raw table output isnt processed further by knitr.
@ -212,47 +244,236 @@ Note the use of the `results='asis'` chunk option. This is required to ensure th
knitr::include_graphics("images/tables-2-kable.png")
```
If you'd like to customize your tables at a deeper level consider the xtable, stargazer, pander, tables, and ascii packages. Each provides an extensive set of tools for returning formatted tables from R code.
If you'd like to customize your tables at a deeper level, consider the xtable, stargazer, pander, tables, and ascii packages. Each provides a set of tools for returning formatted tables from R code.
## Formatted Text
Format the text in your R Markdown files with Markdown, a set of markup annotations for plain text files. When you render your file, Pandoc transforms the marked up text into formatted text in your final file format:
TO DO - IMAGE
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/markdown-1-markup.png")
```
Markdown is designed to be easy to be easy to read and easy to write. It is also very easy to learn. The guide below shows how to use Pandoc's Markdown, a slightly extended version of Markdown that R Markdown understands.
Markdown is designed to be easy to read and easy to write. It is also very easy to learn. The guide below shows how to use Pandoc's Markdown, a slightly extended version of Markdown that R Markdown understands.
To make a level one header in your R Markdown file,
#### Text formatting
TO DO
```markdown
*italic* _italic_
**bold** __bold__
`code`
superscript^2^
subscript~2~
~~strikethrough~~
```
#### Headers
```markdown
# 1st Level Header
## 2nd Level Header
### 3rd Level Header
#### 4th Level Header
##### 5th Level Header
###### 6th Level Header
```
#### Lists
Unordered List:
```markdown
* Item 1
* Item 2
+ Item 2a
+ Item 2b
```
Ordered List:
```markdown
1. Item 1
2. Item 2
3. Item 3
+ Item 3a
+ Item 3b
```
#### Links
Use a plain http address or add a link to a phrase:
```markdown
http://example.com
[linked phrase](http://example.com)
```
#### Images
Images on the web or local files in the same directory:
```markdown
![](http://example.com/logo.png)
![optional caption text](figures/img.png)
```
#### Footnotes
```markdown
A [linked phrase][id].
```
At the bottom of the document:
```markdown
[id]: text of the note
```
#### Blockquotes
```markdown
As George Box said:
> All models are wrong
> but some are useful.
```
#### Plain Code Blocks
Plain code blocks are displayed in a fixed-width font but not evaulated
<pre class="markdown"><code>&#96;&#96;&#96;
This text is displayed verbatim / preformatted
&#96;&#96;&#96;
</code></pre>
#### LaTeX Equations
Use latex math syntax to create formatted equations.
Inline equation:
```markdown
$E = mc^{2}$
```
Display equation:
```markdown
$$E = mc^{2}$$
```
#### Manual Line Breaks
End a line with two or more spaces:
```markdown
Roses are red,
Violets are blue.
```
#### Paragraphs
Insert a blank line at the end of a paragraph:
```markdown
Paragraph 1.
Paragraph 2.
Still paragraph 2.
```
#### Horizontal Rule / Page Break
Three or more asterisks or dashes:
```markdown
***
---
```
#### Tables
```markdown
First Header | Second Header
------------- | -------------
Content Cell | Content Cell
Content Cell | Content Cell
Reference Style Links and Images
```
### Bibliographies and Citations
Pandoc can automatically generate citations and a bibliography in a number of styles. To use this feature, specify a bibliography file using the `bibliography` field in your file's header. The field should contain a filepath from the directory that contains your .Rmd file to the file that contains the bibliography file:
```yaml
---
title: "Markdown Demo"
output: html_document
bibliography: rmarkdown.bib
---
```
You can use any of the following formats: .bib (BibLaTeX), .bibtex (BibTeX), .copac (Copac), .enl (EndNote), .json (JSON citeproc), .medline (MEDLINE), .mods (MODS), .ris (RIS),
.wos (ISI), .xml (XML).
To create a citation within your .Rmd file, use a key composed of @ + the citation identifier from the bibliography file. Then place the citation in square brackets. Here are some example citations from rmarkdown.rstudio.com. Notice that you can
* Separate multiple citations with a `;`
* Remove the square brackets to create an in-text citation
* Add a `-` before the citation to supress the author's name
```markdown
Blah blah [see @doe99, pp. 33-35; also @smith04, ch. 1].
Blah blah [@doe99, pp. 33-35, 38-39 and *passim*].
Blah blah [@smith04; @doe99].
@smith04 says blah.
@smith04 [p. 33] says blah.
Smith says blah [-@smith04].
```
When R Markdown renders your file, it will build and append a bibliography to the end of your document. The bibliography will contain each of the cited references from your bibiliography file, but it will not contain a section heading. As a result it is common practice to end your file with a section header for the bibliography, such as `# References` or `# Bibliography`.
You can change the style of your citations and bibliography by adding a CSL 1.0 style file to the `csl` field of your file's header.
```yaml
---
title: "Markdown Demo"
output: html_document
bibliography: rmarkdown.bib
csl: apa.csl
---
```
As with the bibliography field, your csl file should contain a filepath to the file (here I assume that the csl file is in the same directory as the .Rmd file). http://github.com/citation-style-language/styles contains a useful repository of CSL style files.
* Headers
* Lists
* Links
* Images
* Block quotes
* Latex equations
* Horizontal rules
* Tables
* Slide breaks
* Italicized text
* Bold text
* Superscripts
* Subscripts
* Strikethrough text
* Footnotes
* Bibliographies and Citations
## Output Formats
Set the `output_format` argument of `render()` to render your .Rmd file into any of R Markdown's supported formats. For example, the code below renders [1-example.Rmd](rmarkdown-demos/1-example.Rmd) to a Microsoft Word document:
Set the `output_format` argument of `render()` to render your .Rmd file into any of R Markdown's supported formats. For example, the code below renders [1-example.Rmd](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/1-example.Rmd) to a Microsoft Word document:
```{r eval = FALSE}
library(rmarkdown)
render("1-example.Rmd", output_format = "word_document")
```
If you do not select a format, R Markdown renders the file to its default format, which you can set in the `output` field of a .Rmd file's header. The header of [1-example.Rmd](rmarkdown-demos/1-example.Rmd) shows that it renders to an HTML file by default:
If you do not select a format, R Markdown renders the file to its default format, which you can set in the `output` field of a .Rmd file's header. The header of [1-example.Rmd](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/1-example.Rmd) shows that it renders to an HTML file by default:
```{r eval = FALSE}
---
@ -267,39 +488,39 @@ RStudio's knit button renders a file to the first format listed in its `output`
knitr::include_graphics("images/outputs-2-pdf.png")
```
The following output formats are available to use with R Markdown.
The menu contains a list of formats that are similar to the default format. To update the list, change the default format in your YAML. The following output formats are available to use with R Markdown.
### Documents
* [html_notebook]( http://rmarkdown.rstudio.com/r_notebooks.html) - Interactive R Notebooks
* [html_document](http://rmarkdown.rstudio.com/html_document_format.html) - HTML document w/ Bootstrap CSS
* [pdf_document](http://rmarkdown.rstudio.com/pdf_document_format.html) - PDF document (via LaTeX template)
* [word_document](http://rmarkdown.rstudio.com/word_document_format.html) - Microsoft Word document (docx)
* [odt_document](http://rmarkdown.rstudio.com/odt_document_format.html) - OpenDocument Text document
* [rtf_document](http://rmarkdown.rstudio.com/rtf_document_format.html) - Rich Text Format document
* [md_document](http://rmarkdown.rstudio.com/markdown_document_format.html) - Markdown document (various flavors)
* `html_notebook` - Interactive R Notebooks
* `html_document` - HTML document w/ Bootstrap CSS
* `pdf_document` - PDF document (via LaTeX template)
* `word_document` - Microsoft Word document (docx)
* `odt_document` - OpenDocument Text document
* `rtf_document` - Rich Text Format document
* `md_document` - Markdown document (various flavors)
### Presentations (slides)
* [ioslides_presentation](http://rmarkdown.rstudio.com/ioslides_presentation_format.html) - HTML presentation with ioslides
* [revealjs::revealjs_presentation](http://rmarkdown.rstudio.com/revealjs_presentation_format.html) - HTML presentation with reveal.js. Requires the revealjs package.
* [slidy_presentation](http://rmarkdown.rstudio.com/slidy_presentation_format.html) - HTML presentation with W3C Slidy
* [beamer_presentation](http://rmarkdown.rstudio.com/beamer_presentation_format.html) - PDF presentation with LaTeX Beamer
* `ioslides_presentation` - HTML presentation with ioslides
* `revealjs::revealjs_presentation` - HTML presentation with reveal.js. Requires the revealjs package.
* `slidy_presentation` - HTML presentation with W3C Slidy
* `beamer_presentation` - PDF presentation with LaTeX Beamer
### More
* [flexdashboard::flex_dashboard](http://rmarkdown.rstudio.com/flexdashboard/) - Administrative dashboards. Requires the flexdashboard package.
* [tufte::tufte_handout](http://rmarkdown.rstudio.com/tufte_handout_format.html) - PDF handouts in the style of Edward Tufte. Requires the tufte package.
* [tufte::tufte_html](http://rmarkdown.rstudio.com/tufte_handout_format.html) - HTML handouts in the style of Edward Tufte. Requires the tufte package.
* [tufte::tufte_book](http://rmarkdown.rstudio.com/tufte_handout_format.html) - PDF books in the style of Edward Tufte. Requires the tufte package.
* [html_vignette](http://rmarkdown.rstudio.com/package_vignette_format.html) - R package vignette (HTML)
* [github_document](http://rmarkdown.rstudio.com/github_document_format.html) - GitHub Flavored Markdown document
* `flexdashboard::flex_dashboard` - Administrative dashboards. Requires the flexdashboard package.
* `tufte::tufte_handout` - PDF handouts in the style of Edward Tufte. Requires the tufte package.
* `tufte::tufte_html` - HTML handouts in the style of Edward Tufte. Requires the tufte package.
* `tufte::tufte_book` - PDF books in the style of Edward Tufte. Requires the tufte package.
* `html_vignette` - R package vignette (HTML)
* `github_document` - GitHub Flavored Markdown document
You can also build [books](https://bookdown.org/), [websites](http://rmarkdown.rstudio.com/rmarkdown_websites.html), and [interactive documents](http://rmarkdown.rstudio.com/authoring_shiny.html) with R Markdown, as described in the sections below.
You can also build books, websites, and interactive documents with R Markdown, as described in the sections below.
### Output Options
Each output format is implemented as a function in R. You can customize the output by passing arguments to the function as sub-values of the `output` field. For example, we can change [1-example.Rmd](rmarkdown-demos/1-example.Rmd) to render with a floating table of contents,
Each output format is implemented as a function in R, e.g. `html_document()`. To customize a format, pass arguments to the output function as sub-values of the `output` field. For example, we can change [1-example.Rmd](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/1-example.Rmd) to render with a floating table of contents,
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/outputs-3-toc.png")
@ -309,7 +530,7 @@ To learn which arguments a format takes, read the format's help page in R, e.g.
## HTML Notebooks
In How It Works, you learned that R Markdown files provide a notebook interface that makes it easy to test and iterate when writing code.
In How It Works, you learned that R Markdown files provide a notebook interface for editing that makes it easy to test and iterate your code.
To share this experience with colleagues, simply share your .Rmd file for them to open in their RStudio IDE. If your colleagues do not use R, you can recreate the notebook interface by rendering your file to an HTML notebook with `output: html_notebook`.
@ -332,11 +553,14 @@ Each format will intuitively divide your content into slides, with a new slide b
Insert a horizontal rule (`***`) into your document to create a manual slide break. Create bullet points that display incrementally with `>-`. Here is a version of 1-example.Rmd displayed as a reveal.js slide presentation.
TO DO - IMAGE
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/slides-1-viridis.png")
```
## Dashboards
Dashboards are a useful way to communicate large amounts of information visually and quickly. Create one with the `flex_dashboard` output format of the flexdashboard package, as in the [.Rmd file below](rmarkdown-demos/11-dashboard.Rmd):
Dashboards are a useful way to communicate large amounts of information visually and quickly. Create one with the `flex_dashboard` output format of the flexdashboard package, as in the [.Rmd file below](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/11-dashboard.Rmd):
Flexdashboard makes it easy to organize your content into a visual layout:
@ -364,13 +588,14 @@ Use `rmarkdown::render_site()` to render collections of R Markdown documents int
* any support material
Execute `rmarkdown::render_site("<path to directory>")` to build `_site`, a directory of files ready to deploy as a standalone static website. [This collection of files](rmarkdown-demos/12-website.zip) creates the simple site below
Execute `rmarkdown::render_site("<path to directory>")` to build `_site`, a directory of files ready to deploy as a standalone static website.
Better yet, create an [RStudio Project](https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects) for your website directory. RStudio will add a Build tab to the IDE that you can use to build and preview your site. [This collection of files](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/12-website.zip) creates the simple site below
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/website-2-website.png")
```
Better yet, create an [RStudio Project](https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects) for your website directory. RStudio will add a Build tab to the IDE that you can use to build and preview your site.
## Interactive Documents
@ -381,7 +606,7 @@ R Markdown documents are a useful platform for interactive content. You can make
### htmlwidgets
[Htmlwidgets](http://www.htmlwidgets.org/) are R functions that return JavaScript visualizations. You do not need to know any JavaScript to use htmlwidgets. The R functions take care of all of the coding for you. The [document below](rmarkdown-demos/13-htmlwidget.Rmd) uses a [leaflet](http://rstudio.github.io/leaflet/) htmlwidget to create an interactive map.
[Htmlwidgets](http://www.htmlwidgets.org/) are R functions that return JavaScript visualizations. You do not need to know any JavaScript to use htmlwidgets. The R functions take care of all of the coding for you. The [document below](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/13-htmlwidget.Rmd) uses a [leaflet](http://rstudio.github.io/leaflet/) htmlwidget to create an interactive map.
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/interactive-1-htmlwidget.png")
@ -393,7 +618,7 @@ Learn more about packages that build htmlwidgets at [www.htmlwidgets.org](http:/
### Shiny
The [Shiny](http://shiny.rstudio.com/) package helps developers build interactive web apps powered by R. You can use components from the Shiny package to turn your R Markdown into such an app. To call Shiny code from an R Markdown document, add `runtime: shiny` to the header, like in [this document](rmarkdown-demos/14-shiny.Rmd).
The [Shiny](http://shiny.rstudio.com/) package helps developers build interactive web apps powered by R. You can use components from the Shiny package to turn your R Markdown into such an app. To call Shiny code from an R Markdown document, add `runtime: shiny` to the header, like in [this document](http://github.com/hadley/r4ds/tree/master/rmarkdown-demos/14-shiny.Rmd).
```{r, echo = FALSE, out.width = "100%"}
knitr::include_graphics("images/interactive-2-shiny.png")
@ -409,6 +634,10 @@ But it also introduces a logistical issue: Shiny apps require a special server,
Learn more about Shiny at the [Shiny Development Center](http://shiny.rstudio.com/).
## Books
The bookdown package extends R Markdown to create book length documents, like *R for Data Science*, which was written with R Markdown and bookdown. To learn more about bookdown, see the free ebook [Authoring Books with R Markdown](https://bookdown.org/yihui/bookdown/) or [www.bookdown.org](www.bookdown.org).
## Getting Help
R Markdown documents rely on several technologies that go beyond R functions. To help you navigate these, the developers of RStudio have placed three R Markdown references in the RStudio IDE.
@ -421,7 +650,7 @@ R Markdown documents rely on several technologies that go beyond R functions. To
## Take Away
R Markdown is a useful organizing tool for data science. You can use an R Markdown file to create a reproducible record of how you
R Markdown provides a useful way to organize your data science projects. You can use an R Markdown file to create a reproducible record of how you
* Import
* Tidy
@ -429,6 +658,12 @@ R Markdown is a useful organizing tool for data science. You can use an R Markdo
* Visualize, and
* Model data
and then generate a report from your .Rmd file to communicate your results.
and then generate a report from your .Rmd file to communicate your results. This process is very efficient: you can write your report once and then deploy it many times in different formats or with different parameters. Moreover, by creating an R Markdown file, you participate in two movements that are leading to better scientific practices:
More than this, R Markdown files provide the data science equivalent of [literate programming](https://en.wikipedia.org/wiki/Literate_programming), i.e. literate data science. A literate program mixes code with text that explains what the code does in the context of the program. A .Rmd file mixes code with text that explains what the code does in the context of a data analysis, as well as what the results of the code mean. The result is a reproducible, human-readable record of data science.
1. **Reproducible Research** - The familiar scientific report format (*Introduction*, *Methods and Materials*, *Results*, *Discussion* and *Conclusion*) helps experimental scientists report their results in a reproducible way. Embedded in the format are the details that a scientist would need to reproduce the experiment.
R Markdown files provide the same service for data science. Embedded in the file is the code that a data scientist would need to repeat your analysis.
2. **Literate Programming** - [literate programs](https://en.wikipedia.org/wiki/Literate_programming) intermingle code with human-readable text to build a program that is easy to understand and easy to debug (and often more streamlined than a program written in a non-literate way).
R Markdown documents do not build a program, but they do build a data analysis. By intermingling your code with text, you create an artifact of Literate Data Science. Your work becomes easier to understand and easier to check.