---
title: "An Introduction to R Markdown"
author: "MSc Biostatistics & Health Data Science"
date: "`r Sys.setlocale('LC_TIME', 'C'); format(Sys.Date(), '%B %d, %Y')`"
output:
  html_document:            # Specifies HTML output format
    toc: true               # Enables table of contents
    toc_float: true         # Makes TOC floating/sticky
    toc_depth: 3            # Depth of headers in TOC
    theme: united           # Sets the United theme for styling
    highlight: tango        # Sets code highlighting style to Tango
    number_sections: true   # Auto-number sections
  bibliography: references.bib
---

```{r setup, include = FALSE}
# Load required packages
if (!require(pacman)) install.packages("pacman")
pacman::p_load(
  knitr,        # For R Markdown functionality
  rmarkdown,    # For advanced R Markdown features
  tidyverse,    # For data manipulation and visualization
  kableExtra    # For better table formatting
)

# This chunk sets global options for the entire document
knitr::opts_chunk$set(
  echo = TRUE,          # Show R code in output
  warning = FALSE,      # Don't show warnings
  message = FALSE,      # Don't show messages
  fig.width = 8,        # Default figure width
  fig.height = 6,       # Default figure height
  fig.align = 'center', # Center all figures
  dev = "png",          # Output device
  dpi = 300             # Resolution
)

# Set random seed for reproducibility
set.seed(123)
```


# Introduction to R Markdown

R Markdown is an essential tool for reproducible research in biostatistics. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. This document will guide you through:

* Creating professional statistical reports
* Combining narrative text with analysis
* Generating publication-ready tables and figures
* Documenting your statistical methods
* Ensuring reproducibility of your research

For more details, visit the [R Markdown website](http://rmarkdown.rstudio.com)


## Getting Started

To work with R Markdown, if necessary:

* Install [R](http://www.r-project.org/)
* Install the latest version of [RStudio](http://rstudio.org/download/)
* Install the latest version of the `knitr` package: `install.packages("knitr")`


## Document Structure
### YAML Header
The YAML header (at the top between `---`) configures your document. Key settings include:

* Output format (HTML, PDF, Word)
* Document styling
* Table of contents options
* Bibliography settings


### Text Formatting

R Markdown supports various text formatting options:

* *Italics*: Surround text with single asterisks `*italic*` or underscores `_italic_`
* **Bold**: Use double asterisks `**bold**` or underscores `__bold__`
* `Code`: Use backticks for `inline code`
* ~~Strikethrough~~: Use double tildes `~~strikethrough~~`
* Superscript^2^: `^2^`
* Subscript~2~: `~2~`

### Lists

Unordered lists use asterisks, plus, or minus signs:

* Item 1
* Item 2
  * Sub-item 2.1
  * Sub-item 2.2

Ordered lists use numbers:

1. First item
2. Second item
   1. Sub-item 2.1
   2. Sub-item 2.2

# Code Chunks and Options

The following document is mainly based on <https://bookdown.org/yihui/rmarkdown/r-code.html>.

## Basic Code Chunk Structure

You can insert R code chunks using:

- RStudio toolbar (the `Insert` button)
- Keyboard shortcut: `Ctrl + Alt + I` (`Cmd + Option + I` on macOS)


## Important Chunk Options

There are many chunk options in knitr documented at <https://yihui.name/knitr/options>. Here are some important ones:

* **`eval`**: Controls whether to execute the code chunk

* **`echo`**: Shows/hides source code (some may prefer to see only the results and not the source code)

* **`results`**: Controls output display:
  - Set to `'hide'` to hide text output.
  - Set to `'asis'` to write text output \"as-is\".
e.g., you can write raw Markdown text from R code (like `cat('*Markdown** is cool.\n')`). By default, text output will be wrapped in verbatim elements.

* **`collapse`**: Controls whether text output and source code are merged into a single code block in the output. This is mostly cosmetic: `collapse = TRUE` makes the output more compact by displaying R source code and its text output in a single block. The default `collapse = FALSE` separates R expressions and their text output into different blocks.

* **`warning`, `message`, and `error`**: Control display of warnings/messages/errors

* **`include`**: Controls chunk inclusion in output. When `include = FALSE`, the entire code chunk is excluded from the output, but will still be evaluated if `eval = TRUE`. When you want to set `echo = FALSE`, `results = 'hide'`, `warning = FALSE`, and `message = FALSE`, you might simply use the single option `include = FALSE`.

* **Figure dimensions**: Use `fig.width`, `fig.height`


When you click the **Knit** button, a document will be generated that includes both content and the output of any embedded R code chunks within the document.

You can produce various outputs in a code chunk: text output, tables, or graphics. You have fine control over all these outputs via chunk options, which can be provided inside the curly braces (between ````{r}` and `}`).

The value of a chunk option can be any valid R expression, which makes chunk options extremely flexible. For example, the `eval` option controls whether to evaluate (execute) a code chunk, and you can conditionally evaluate a chunk using a previously defined variable.

# Practical Examples

```{r, echo = TRUE}
# Execute code if the date is later than a specified day
do_it = Sys.Date() > '2018-02-14'
```

```{r, eval = do_it, echo = TRUE, results = 'markup'}
# Generate random normal data and create histogram
x = rnorm(10000)
x[1:5]  # Display first 5 values
hist(x, breaks = 55, main = "Distribution of Random Normal Data")
```

Besides code chunks, you can also insert values of R objects inline in text. For example:

```{r, echo = FALSE}
# Define circle radius
x = 15  # radius of a circle
```

For a circle with the radius `r x`, its area is `r round(pi * x^2, 2)`.

# Writing LaTeX

You can write LaTeX code easily. For example: $y_{i} = \mathbf{x}_{i}^{\top}\mathbf{\beta} + \epsilon_{i}$, $\epsilon_{i} \sim N(0, \sigma^{2})$.

$\left(\int_{a}^{b} f(x) \; dx\right)$, 
$\displaystyle\sum_{x = a}^{b} f(x)$,
$\displaystyle\prod_{x = a}^{b} f(x)$, 
$\log(x)$, 
$\exp(x)$

**Greek letters**: $\epsilon \varepsilon E$

To write an equation:

$$
\sum_{n = 1}^{10} n^2
$$

# Citations and References

## Adding Citations

To effectively cite references, start by creating a reference file named references.bib. Here's how to format your citations:

### Basic Citations
* Single inline citation: `@smith2020example` renders as @smith2020example
Parenthetical citation: `[@smith2020example]` renders as [@smith2020example]
* Multiple citations: `[@smith2020example; @brown2021manual]` renders as [@smith2020example; @brown2021manual]

### Advanced Citation Formats
* With page numbers: `[@smith2020example, pp. 33-35]`
* Author name in text: `@smith2020example argues that...`
* Multiple authors: `[-@smith2020example; @brown2021manual]`
* Year only: `[-@smith2020example]`

## Managing Citations

### Tools for Bibliography Management
Consider using the following tools to manage your bibliography:
* Zotero with Better BibTeX extension
* JabRef
* Mendeley
* EndNote

### Example Workflow with Zotero
1. Install Zotero and Better BibTeX extension
2. Save references to a Zotero collection
3. Export collection as `references.bib`
4. Place `references.bib` in your project directory
5. Keep `references.bib` updated by enabling automatic export in Zotero

```{r citation-example, eval=FALSE}
# R code can also generate citations
# Install and load RefManageR package
if (!require(RefManageR)) install.packages("RefManageR")
library(RefManageR)

# Read bibliography file
bib <- ReadBib("references.bib")

# Print all citations
print(bib)
```

## Citation Styles

### Common Citation Styles
* APA (American Psychological Association)
* MLA (Modern Language Association)
* Chicago
* IEEE
* Vancouver

### Using Citation Style Files
1. Download CSL files from [Zotero Style Repository](https://www.zotero.org/styles)
2. Add to YAML header:
```yaml
csl: "apa.csl"  # or another style file
```

## Bibliography Placement and Formatting

### Controlling Bibliography Location
To specify where the bibliography should appear, include this line in your document:
```markdown
# References
```

### Bibliography Formatting
You can customize the appearance of your bibliography using CSS:
```css
.references {
    font-size: 0.9em;
    line-height: 1.4;
    margin-top: 2em;
}
```

### Cross-References
Reference citations within your document by using:
```markdown
As discussed in Section \@ref(intro), @smith2020example provides...
```


## Bibliography

The bibliography will automatically be generated at the end of your document, ensuring that all cited works are properly listed.

# Further study
<https://bookdown.org/yihui/rmarkdown/>

<https://rmarkdown.rstudio.com/lesson-1.html>