---
title: "R Markdown Basics"
author: "Author Name"
date: "2020 May 10"
output: html_document
---

# Basics

This template illustrates the basics of an [R Markdown](https://rmarkdown.rstudio.com) document (aka. 'RMarkdown' or just 'Markdown'). 
R Markdown documents have the `.Rmd` file extension. 
The `.Rmd` source file of this document is available [here](http://Rpository.com/down/temp/Rmarkdown_basics.Rmd).

## Creating an R Markdown document

In order to use R Markdown, you need to have (or install) and load the **rmarkdown** and **knitr** packages in [**R**](https://www.r-project.org/):

```{r install-rmd-packages, echo = TRUE, eval = TRUE, message = FALSE, warning = FALSE}
# Install required packages (always):
# install.packages("tidyverse", "ds4psy")

# Load required packages (always):
library(tidyverse)
library(ds4psy)
```

Markdown documents are documents that combine text and code. 
They are saved as simple text documents (with the file extension `.md` or `.Rmd`) 
and can be edited by any text editor --- ideally by a program that interacts with R (like [**RStudio**](http://www.rstudio.com)). 

You can create a new RMarkdown document in [**RStudio**](http://www.rstudio.com) by clicking `File > New File > R Markdown`. 
At the top of a new file, you will see inputs for a page title, author, date, and the output format. 
Change the title, author, and date to suit your current document.

## Text vs. R code

Markdown separates regular text from R code. 
Unless you use a _code chunk_, Markdown will treat all your text as regular text. For example, when we write the following lines:

2 + 2
hist(ChickWeight$weight)

Markdown just thinks that we're writing text, not R code. (Actually, it even prints consecutive lines of text into the same line unless a line of text ends with _two_ spaces.)

<!-- Note that you can use html-commands in Markdown, e.g., for including comments. -->


# Formatting Text

## Italics, bold, and headers

To write text in _italics_ font, use a single underscore (or asterix) before and after the text.

To write text in **bold** font, use a double asterix (or underscores) before and after the text.


# 1st-Level Header

To make headers in Markdown, use the \# (i.e., pound symbol) at the beginning of a line.

Note that non-function words of 1st-level headings tend to be capitalized (in APA format). 

## 2nd-level header

Multiple pound symbols indicate lower-level headers.

### 3rd-level header

Note that, in an actual text, there should be _at least two_ headings on every level.


## Making Lists

To create a _numbered list_ of items, just use numbers before paragraphs: 

1. First element
2. Second element
3. Third element

To create a non-numbered _bullet list_, use a single dash or asterix before a list of paragraphs: 

- First element of bullet list.
- Second element of bullet list.
    - 1st sub-element
    - 2nd sub-element
- Third element of bullet list.

Note that you can create multiple levels of lists, using leading spaces to indicate the level.


# Including R Code Chunks

To evaluate R code in a Markdown document, you need to enclose the R code into a _code chunk_. 
Here's how a code chunk looks: 

```{r chunk_name, echo = TRUE, eval = TRUE}
# This is a code chunk. Everything included here will be interpreted as R code.
# (Specifying a unique chunk_name helps to keep track of your chunks later.) 

# R will evaluate the code in this chunk and print the result:
2 + 2
```

As you can see, code chunks in RStudio are highlighed with a gray background. Everything you put in this chunk will be evaluated by R Markdown as R code when you _knit_ the document.

You can insert a new code chunk in one of three ways: 

1. Use the `Command-Alt-I` shortcut on a Mac.

2. Click the "insert new code chunk" button on the top right hand of this panel. It looks like a green square with an arrow.

3. Copy and paste an existing chunk and change its content and properties.


## R Code Chunk options

You can add arguments at the start of code chunks to change how the code included in the chunk is evaluated and presented. Here are the most common options:

### Setting `echo = FALSE` 

By default, Markdown will repeat (aka 'echo') your R code in your final output. However, if you don't want this, you can add the `echo = FALSE` argument.

In the following code, I will write some comments and calculate the mean weight of chickens in the ChickWeight dataset. Because I include the `echo = FALSE` argument at the top of the chunk, the chunk will only print the result in the final output, not the original R code that generates the result:

```{r demo_echo_F, echo = FALSE}
# R will not repeat this code in the output because I wrote echo = FALSE.
# It will only print the result of the code

# What is the mean weight of chickens?
mean(ChickWeight$weight)
```

By contrast, if you do not include the `echo = FALSE` argument or set `echo = TRUE`, R will print the original code AND the result:

```{r demo_echo_T}
# Now R will copy this code (including comments) and print the result 
# because this chunk did not set the option echo = FALSE.

# What is the mean weight of chickens?
mean(ChickWeight$weight)
```

### Setting `eval = FALSE`

If you include the `eval = FALSE` argument, R will NOT evaluate code in a chunk: 

```{r demo_eval, eval = FALSE}
# Setting eval = FALSE at the beginning of this chunk, R will NOT evaluate the code. 
# However, because we did not include echo = FALSE, it will still print this code and comment: 
1 + 1
sd(ChickWeight$weight)
```

When setting _both_ `echo = FALSE`, and `eval = FALSE`, R will neither copy nor evaluate the code:

```{r demo_eval_echo_F, eval = FALSE, echo = FALSE}
# This chunk won't be evaluated and won't show up in the final document. 
3 + 58
```

### Specifying `fig.width` and `fig.height` 

If you generate a plot in a chunk, you can change its size with the `fig.width` and `fig.height` options:

The following chunk will print a small figure as I set `fig.width = 4` and `fig.height = 3` (in inches): 

```{r demo_figsize1, fig.width = 4, fig.height = 3}
hist(ChickWeight$weight)
```

The following chunk will print a tall and narrow figure as we set `fig.width = 4`, `fig.height = 7`:

```{r demo_figsize2, fig.width = 4, fig.height = 7}
hist(ChickWeight$weight)
```


## Minichunks

In addition to creating regular code chunks, you can create _minichunks_ that go directly into your text.

A minichunk looks like this: `r 2 + 2` and is evaluated in the output document (i.e., you'll only see the result of the minichunk).

For example, we can write: "The mean weight of chickens was `r round(mean(ChickWeight$weight), 0)`." When the document is created, R will evaluate the R code in the mini-chunk and replace it with the result of the corresponding R command in the output document.

Once an object has been defined, you can use it later in both regular chunks and in minichunks. For instance, let's create a chunk that defines several objects (specifically `diet.1.mean`, `diet.4.mean`, etc.) which calculate descriptive statistics of chickens on different diets from the `ChickWeight` dataframe:

```{r get_diet_stats}
diet.1.mean <- round(mean(ChickWeight$weight[ChickWeight$Diet == 1]), 2)
diet.4.mean <- round(mean(ChickWeight$weight[ChickWeight$Diet == 4]), 2)

diet.1.sd <- round(sd(ChickWeight$weight[ChickWeight$Diet == 1]), 2)
diet.4.sd <- round(sd(ChickWeight$weight[ChickWeight$Diet == 4]), 2)
```

Once the objects were defined and have been evaluated, we can use them in a minichunk:

* "We measured the weight of several chickens on different diets. The chickens in diet 1 had a mean weight of `r diet.1.mean` (SD = `r diet.1.sd`). By contrast, chickens on diet 4 had a mean weight of `r diet.4.mean` (SD = `r diet.4.sd`)." 


# Knitting a Document

To create an HTML (or Word or Latex) document from a Markdown (.Rmd) document, you need to _knit_ the document. 
Knitting a document simply means taking all the text and code and weaving (or _knitting_) it into a nicely formatted document. 
Fortunately, the R's **knitr** package takes care of the hard parts.

To knit a document (into html, LaTeX pdf, or -- if necessary -- MS&nbsp;Word) from your `.Rmd` file, do one of the following: 

1. on a Mac: Use the `Command-Shift-K` keyboard shortcut;

2. Click the "`Knit`" button at the top of this window. (Its icon typically shows a ball of yarn.) 


## Loading libraries

If you use a package in your code, you _must_ explicitly load the package in your Markdown document using `library()` before using the package. If you don't, Markdown may not know which packages you are using and the code won't work.

```{r load_packages}
# When requiring additional packages, you should ALWAYS load them explicitly 
# at the beginning of your markdown document: 
library("rmarkdown")
library("knitr")
```


## Warning: R code with _any_ errors will not knit!

If your R code (in any standard chunks or minichunks) contains R errors, the document will not knit.

For example, the following chunk has a syntax error. If we tried to knit this document with `eval = TRUE`, we would get an error message:

```{r, demo_syntax_error, eval = FALSE}
# This text is commented and NOT evaluated --- we can write whatever we want here: x <- 0/0!

This text is NOT commented, R thinks it is R code and will freak out if we try to knit the document.
Thankfully, we included the eval = FALSE argument for this chunk, so R will just ignore it.
```

If your document fails to knit, you need to go through your code chunk by chunk to find and fix the error.


# Credits

* The original version of this file was created by [Nathaniel Phillips](http://nathanieldphillips.com/).
* A simpler template for doing your course-related work is available [here](http://Rpository.com/down/temp/LastnameFirstname_WPA01_yymmdd.Rmd).

[Updated on `r Sys.Date()` by [hn](http://neth.de).]

<!-- End of file. -->
