---
title: "STAT 22000: Introduction to R Markdown"
output:
html_document:
highlight: pygments
theme: cerulean
pdf_document: default
---
```{r setup, echo = FALSE}
knitr::opts_chunk$set(
collapse =TRUE
)
```
R Markdown is a simple formatting syntax for producing PDF, MS Word, and HTML documents that incorporates R codes and R output in one single source document.
It can save you tons of time copying/pasting R text output or exporting/importing R plots into your homework.
## Demo 1. Hello! World
Please download the R markdown (RMD) file RMDdemo1.RMD
and open it in RStudio. It will be opened in the [Source Editor] as follows.
```{r, echo=FALSE, comment=""}
fileName = 'RMDdemo1.RMD'
a = readChar(fileName, file.info(fileName)$size)
cat(a)
```
In the file, the first few lines that
begin and end with 3 dashes (`---`)
are called the **header**.
which specifies the title, author, output format,
and the other meta setting of the R markdown file.
The remaining part is called the **body** of the R markdown.
The portion below is called an **R code chunk**.
```{r, echo=FALSE, comment=""}
cat(substr(a, nchar(a)-31,nchar(a)))
```
In general, R codes in an R markdown document
must be enclosed in **R code chunks**
that begin with `r cat(substr(a, nchar(a)-31,nchar(a)-26))` (three **back-ticks** (`) followed by an "r" enclosed in curly braces)
and ends with another three **back-ticks** `r cat(substr(a, nchar(a)-3,nchar(a)))`
```{r, echo=FALSE, comment="", collapse=TRUE}
b = paste(substr(a, nchar(a)-31,nchar(a)-26),
"first line of R codes",
"second line of R codes",
"... more lines of R codes",
substr(a, nchar(a)-3,nchar(a)), sep='\n')
cat(b)
```
Please note one can type **back-tick** (`) using
the key on the top right corner of an US keyboard.
{width=80%}
The code chunk contains only one line of R codes
`plot(sunspot.month)`,
where `sunspot.month` is a built-in dataset in R
that stores the monthly sunspot counts
data from 1749 to present.
To execute the command,
One can place the cursor on the line `plot(sunspot.month)`, and press
[Ctrl + Enter] (Windows) or [Cmd + Enter] (Mac).
The output appears directly below the code.
Outside of the R code chunk(s),
one can add text to an R Markdown document,
like `Hello! World` in the `RMDdemo1.Rmd` file.
One can add some description for the data,
the data analysis methods, and the conclusion of the analysis
to the R markdown file.
### 1.1 Knitting R Markdown to Word
Please click the [Knit] button in RStudio and choose “Knit to Word”.
A Word document should be generated like this.
### 1.2 Knitting R Markdown to PDF
Please click the [Knit] button in RStudio and choose “Knit to PDF”.
A PDF document should be generated like this.
If “Knit to PDF” doesn't work, please install `tinytex` package in R
by executing the two lines below in the [Console].
```
install.packages("tinytex")
tinytex::install_tinytex()
```
It might take 10+ minutes to download and install `tinytex`
depending the speed of your internet.
Once `tinytex` is installed, you can knit the RMD to PDF again
and it should work.
If you still have trouble knitting RMD to PDF, you can choose “Knit to Word”
and then convert the knitted Word document into PDF yourself.
## Demo 2. Plots
Please download the R markdown (RMD) file RMDdemo2.RMD, and open it up in RStudio.
### 2.1 How to Adjust the Sizes of Plots
You can resize your plots by adjusting values of `fig.width`
and `fig.height` inside `{r}` at the beginning of the code chunk.
```{r, echo=FALSE, comment="", collapse=TRUE}
b = paste("```{r fig.width=7.5, fig.height=2.5}",
"plot(sunspot.month)",
"```", sep='\n')
cat(b)
```
Note the unit of `fig.width` and `fig.height` are in inches.
Recall that letter size paper is 8.5 $\times$ 11 inches.
You can try change the values of `fig.width` and `fig.height`
in the first code chunk of `RMDdemo2.RMD.Rmd`
and [Knit] to PDF] and see how the plot is changed in the output PDF.
It's possible to view the output of a code chunk without Knitting the entire document.
To run a single line, place your cursor on the line you want to run and press
[Ctrl + Enter] (Windows) or [Cmd + Enter] (Mac).
The output appears directly below the code chunk.
Please **always adjust the sizes of plots appropriately**
in your homework submission.
### 2.2 Center, Right-justify, or Left-justify Plots
One can adjust the alignment of plots
by specifying `fig.align` to be `'center'`, `'right'` or `'left'`
The default alignment is left.
The code chunk below put the plot at the center of the page.
```{r, echo=FALSE, comment="", collapse=TRUE}
b = paste("```{r fig.width=4, fig.height=3, fig.align='center'}",
"plot(sunspot.month)",
"```", sep='\n')
cat(b)
```
Please change `fig.align` in one of the code chunks in `RMDdemo2.Rmd`,
[Knit] the file again
and see how the plot alignment is changed in the output PDF.
### 2.3 Two Plots Placed Side-by-Side
One can put more than one line of codes in a code chunk,
like the code chunk below,
the first line for a time plot
and the second line for a histogram of the monthly data of sunspot counts.
The histogram will be placed below the time plot in the output PDF,
rather than side-by-side.
```{r, echo=FALSE, comment="", collapse=TRUE}
b = paste("```{r fig.width=4, fig.height=3.5}",
"plot(sunspot.month)",
"hist(sunspot.month)",
"```", sep='\n')
cat(b)
```
To place the two plots side-by-side,
one can add `fig.show='hold'` in the code chunk,
and specify the relative widths of the two plots
by `out.width`.
The code chunk below let the two plots each
take 45% of the paper width (excluding the margins).
```{r, echo=FALSE, comment="", collapse=TRUE}
b = paste("```{r fig.width=4, fig.height=3.5, fig.show='hold', out.width=c('45%', '45%')}",
"plot(sunspot.month)",
"hist(sunspot.month)",
"```", sep='\n')
cat(b)
```
You can knit `RMDdemo2.RMD.Rmd` and see the output PDF
for the difference in output of the two code chunks above.
## Demo 3. Formatting Text
R markdown can combine your text explanation and comment
of your data and analysis with R codes and R outputs in one single file.
It includes most standard ways of formatted text.
Please download the R markdown (RMD) file RMDdemo3.RMD,
open it in RStudio.
You can play with and
try out the following text formatting methods using the file `RMDdemo3.RMD`
as you move along and [Knit] to see the output document.
### 3.1 Bold-face, Italic, Striking Through Text
**R Markdown:**
```
**This text is bold.**
*This text is in italics*.
You can even ~~strikethrough text~~.
```
**Knitted Output:**
**This text is bold.**
*This text is in italics*.
You can even ~~strikethrough text~~.
### 3.2 Itemized List
**R Markdown**
```
* item 1
* item 2
- sub-item 1
- sub-item 2
* item 3
- sub-item 1
```
**Knitted Output:**
* item 1
* item 2
- sub-item 1
- sub-item 2
* item 3
- sub-item 1
The list must be preceded by a **blank line**, and **4 spaces** should be used before sub-items.
### 3.3 Ordered List
**R Markdown:**
```
1. item 1
2. item 2
a. sub-item 1
b. sub-item 2
3. item 3
a. sub-item 1
```
**Knitted Output:**
1. item 1
2. item 2
a. sub-item 1
b. sub-item 2
3. item 3
a. sub-item 1
Again, the list must be preceded by a **blank line**,
and **4 spaces** should be used before sub-items.
### 3.4 Header
**R Markdown**
```
# Header 1
## Header 2
### Header 3
ordinary text
```
**Knitted Output:**
# Header 1
## Header 2
### Header 3
ordinary text
An header line must be preceded by a **blank line**,
and there must be a **space** between `#` and the header title.
### 3.5 Table
**R Markdown:**
```
Table Header | Second Header
------------- | -------------
Table Cell 1 | Cell 2
Cell 3 | Cell 4
```
**Knitted Output:**
Table Header | Second Header
------------- | -------------
Table Cell 1 | Cell 2
Cell 3 | Cell 4
You can center, right-, or left-justify text in your tables as you like.
**R Markdown:**
```
Centered | Right-Justified | Left-Justified
:-------:|----------------:|:----------------
A | 24 | My Friend's Name
B | 5 | My Name
CC | 167 | Firstname Lastname
DDD | 48 | Another Name
```
**Knitted Output:**
Centered | Right-Justified | Left-Justified
:-------:|----------------:|:----------------
A | 24 | My Friend's Name
B | 5 | My Name
CC | 167 | Firstname Lastname
DDD | 48 | Another Name