Source & Inspiration: [R Studio](https://rmarkdown.rstudio.com/lesson-1.html), add others...
### What is R Markdown?
R Markdown is a R package that provides an authoring framework for data deliverables. R Markdown file is a plain text file that has the extension `.Rmd`. You can use a single R Markdown file to both **save and execute R code** and to **generate high quality reports that can be shared**. R Markdown documents are fully reproducible and support dozens of static and dynamic output formats. R Markdown is an attempt at [[Literate Programming]].
See the next generation R Markdown : [[Quarto]]
### Why use R Markdown?
- **Save and run code.** Develop, save, and run code as individual chunks or as an entire document.
- **Generate high quality reports.** Develop code and presentation side-by-side in a single .rmd document.
- **Dynamic Documents.** Knit together plots, tables, and results with narrative text.
- **Multiple [[R Markdown Output Formats]].** Render to a variety of formats like HTML, PDF, MS Word, or MS Powerpoint.
- **Reproducible Research.** Anyone can read or run your code to reproduce your work.
- **Share easily.** Upload, link to, or attach your R Markdown report.
- **Notebook interface.** A [notebook interface](https://bookdown.org/yihui/rmarkdown/notebook.html) can be used to weave together narrative text and code to produce elegantly formatted output.
- Create multi-section documents using [[Bookdown]] R package.
- **Mutiple programming languages.** Use [multiple languages](https://bookdown.org/yihui/rmarkdown/language-engines.html) including R, Python, and SQL.
### Writing R Markdown
Use Markdown or use the visual editor to write an R Markdown document.
[[Markdown Syntax]] is simple yet gives another set of things to remember. For example, to bold a word, surround it with two asterisks:
This code:
```{r echo}
**bold this text**
```
results in :
**bold this text**
[[Markdown Syntax]]
The visual editor in RStudio version 1.4 or newer incudes a visual editor for R Markdown documents [[https://rstudio.github.io/visual-markdown-editing/](https://rstudio.github.io/visual-markdown-editing/).]. The visual is s WYSIWYG editor similar to Microsoft Word.
### R Markdown Files Components
R Markdown files have 3 types of content:
1. **YAML (Metadata) Header.** *Optional* Each R Markdown file can have a "YAML header", which is a section of rmd file that is at the top where many of the settings or options for file creation are placed. In RStudio, these often update automatically as different settings are invoked in the Options menu. The YAML header is surrounded by `---`s.
2. **R Code Chunks.** R code within a R Markdown file can be included in two ways, either as in-line code (e.g., the total number of oranges was `` `r`` ``sum(fruit$oranges)` `` or as a “chunk." R code chunks surrounded by ` ``` `s.
3. **Markdown text.** Markdown text can be included as narrative around your chunks of code. The text is mixed with simple text formatting. Adding narrative with your code is a great way of getting into the habit of explicitly documenting your analysis. When you come back to a file many months later, all of your thinking (and code and analytical approach and data used) is there, rather than having to work out exactly what you did! Adding narrative can also assist others in reproducing your data analysis objectives.
#### YAML Header
It is possible to set different options for different output types by including these in the YAML header:
````
---
title: "R Notebook"
output:
html_document:
toc: true
toc_float:
collapsed: true
smooth_scroll: true
toc_depth: 4
number_sections: true
rmarkdown::theme: architect
highlight: tango
code_download: yes
fig_width: 5
fig_height: 8
fig_caption: true
code_folding: hide
pdf_document:
fig_height: 3
fig_width: 4
---
````
#### Code chunks are flexible and come with lots of options.
Code chunks can be run (or not) or displayed (or hidden):
Show output only <-- echo=FALSE
Show code and output <-- echo=TRUE
Show code (don’t run code) <-- eval=FALSE
Show nothing (run code) <-- include=FALSE
Show nothing (don’t run code) <-- include=FALSE, eval=FALSE
Hide warnings <-- warnings=FALSE
Hide messages <-- messages=FALSE
Do you want to save the output of the chunk so it doesn’t have to run next time? <-- cache=TRUE or FALSE
#### Default Options for Code Chunks
We can set default options for all our chunks at the top of our document by adding and editing `knitr::opts_chunk$set(echo = TRUE)` at the top of the document in the YAML header.
````
```{r}
knitr::opts_chunk$set(echo = TRUE,
warning = FALSE)
```
````
#### Code Chunk
````
```{r echo=TRUE}
# This is basic chunk.
# Starts with ```{r}
# Ends with ```
# Code goes here
sum(cars$mpg)
```
````
*Add naming chunks and adding options to chunks *
##### Run Code Inside Text
You can run the code inside a text sentence - running the code “inline” using 'r *code*'.
``` {r echo=TRUE}
There are `r nrow(airquality) ` observations in the airquality dataset,
and `r 'ncol(airquality) ` variables.
```
### Presenting Data
By default, R Markdown prints data frames and matrices as you’d see them in the console. If you prefer that data be displayed with additional formatting you can use the `[knitr::kable](https://rdrr.io/pkg/knitr/man/kable.html)` function. For even deeper customisation, consider the **xtable**, **stargazer**, **pander**, **tables**, and **ascii** packages.
### Caching
Normally, each knit of a document starts from a completely clean slate. This is great for reproducibility, because it ensures that you’ve captured every important computation in code. However, it can be painful if you have some computations that take a long time. The solution is `cache = TRUE`. When set, this will save the output of the chunk to a specially named file on disk. On subsequent runs, knitr will check to see if the code has changed, and if it hasn’t, it will reuse the cached results.
### R Markdown Notebook
"Most people use the terms R Notebook and R Markdown interchangeably and that is fine. Technically, **R Markdown is a file, whereas R Notebook is a way to work with R Markdown files. R Notebooks do not have their own file format, they all use .Rmd** ." - [12.3 What is the difference between a Notebook and an R Markdown file? | R for Health Data Science](https://argoshare.is.ed.ac.uk/healthyr_book/what-is-the-difference-between-a-notebook-and-an-r-markdown-file.html)
### Getting Started
- Install R and RStudio.
- Install several R packages. For example:
``` (r echo=TRUE)
install.packages("rmarkdown")
install.packages("knitr")
install.packages("tinytex")
install.packages("here")
install.packages("tidyverse")
install.packages("broom")
install.packages("fs")
install.packages("usethis")
```
- Use a [[R Markdown Document Template]]
- Create a R Markdown file.
### R Markdown Resources
| # | Resource |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | [R Markdown Cookbook (bookdown.org)](https://bookdown.org/yihui/rmarkdown-cookbook/) |
| 2 | [bookdown: Authoring Books and Technical Documents with R Markdown](https://bookdown.org/yihui/bookdown/) |
| 3 | [blogdown: Creating Websites with R Markdown (bookdown.org)](https://bookdown.org/yihui/blogdown/) |
| 4 | [R Markdown: The Definitive Guide (bookdown.org)](https://bookdown.org/yihui/rmarkdown/) |
| 5 | [RMarkdown for Scientists (njtierney.com)](https://rmd4sci.njtierney.com/) |
| 6 | [rstudio’s R Markdown cheatsheet](https://github.com/rstudio/cheatsheets/raw/master/rmarkdown-2.0.pdf) |
| 7 | [Bookdown’s section on Markdown syntax](https://bookdown.org/yihui/bookdown/markdown-syntax.html) |
| 9 | [YAML Headers - R Markdown Crash Course (zsmith27.github.io)](https://zsmith27.github.io/rmarkdown_crash-course/lesson-4-yaml-headers.html) |
***
2021 cloudedknowledge.net