---
title: "R Markdown Sample"
author: "Your Name"
date: \today
fontfamily: accanthis
linkcolor: blue
output:
# html_document:
pdf_document: default
editor_options:
chunk_output_type: console
fontsize: 12pt
# the below header is to call LaTeX packages
header-includes:
\usepackage{float}
---
## Prepare for analyses
I typically use the first chunk, right after the YAML header, to establish general chunk options and load necessary libraries and packages for the analysis. Since these procedures are not particularly interesting to report, I always configure this initial chunk with `include=FALSE`.
```{r setup, include=FALSE}
knitr::opts_chunk$set(include = TRUE,echo = TRUE,message = FALSE,warning = FALSE,error = FALSE)
rm(list = ls()) # clear the environment
set.seed(1234)
#install.packages("lattice")
#install.packages("stargazer")
#install.packages("pander")
library(tidyverse)
library(lattice)
library(stargazer)
library(pander)
```
## Getting started
To produce PDF file, you need \TeX files.
- Easy way: Install the `tinytex` package: `install.packages("tinytex")`. Then run `tinytex::install_tinytex()`.
- *Warning*: Installing `tinytext`` will likely take few minutes.
### Install guide for Chris's packages and TinyTeX
Un-comment the code below to install the packages. You can call \LaTeX commands as I am doing here with `\scriptsize` and `\normalsize`
\scriptsize
```{r}
# Install tile
# install.packages("https://faculty.washington.edu/cadolph/software/tile_0.4.17.tar.gz",
# repos = NULL,
# type="source")
# Install simcf
# install.packages("https://faculty.washington.edu/cadolph/software/simcf_0.2.20.tar.gz",
# repos = NULL,
# type="source")
```
\normalsize
## Basic console output
To insert an R code chunk, you can type it manually or just press `Chunks - Insert chunks` or use the shortcut key.
- Windows: *Ctrl + Alt + I*
- macOS: *Cmd + Option + I*
This will produce the following code chunk:
```{r}
```
Pressing tab when inside the braces will bring up code chunk options.
The following R code chunk labelled `basicconsole` is as follows:
```{r }
x <- 1:10
y <- round(rnorm(10, x, 1), 2)
df <- data.frame(x, y)
df
```
The code chunk input and output is then displayed as follows:
```{r basicconsole}
x <- 1:10
y <- round(rnorm(10, x, 1), 2)
df <- data.frame(x, y)
df
```
### Echo and Results
The following code hides the command input (i.e., `echo=FALSE`), and outputs the content directly as code (i.e., `results=asis`).
```{r dotpointprint, results='asis', echo=FALSE}
cat("Here are some dot points\n\n")
cat(paste("* The value of y[", 1:3, "] is ", y[1:3], sep="", collapse="\n"))
```
This code includes the command input (i.e., `echo=TRUE`) with markup output (i.e., results -> default )
```{r dotpointprint2, echo=T}
cat(paste("* The value of y[", 1:3, "] is ", y[1:3], sep="", collapse="\n"))
```
### Message and Warning
While the chunk without specification of options show all warnings and messages....
```{r, warning=TRUE}
df %>%
summarize_at(vars(y), funs(mean))
```
this code does not output warnings
```{r, warning=FALSE}
df %>%
summarize_at(vars(y), funs(mean))
```
## Functions and loops
- For a more comprehensive introduction, please consult Wickham and Grolemund ([2017](https://r4ds.had.co.nz/index.html))
- Functions: [chapter 19](https://r4ds.had.co.nz/functions.html).
- Iteration: [chapter 21](https://r4ds.had.co.nz/iteration.html).
- For advanced users with some knowledge on programming:
- Wickham ([2019](https://adv-r.hadley.nz/)) - Advanced R (2nd Edition).
- Reduce duplication in your code by creating functions (or loops) instead of copying-and-pasting.
- **Golden rule**: whenever you find yourselves copying-and-pasting certain code more than three times, consider writing a function or a loop!
## Functions: steps
1. **Function name**: select a descriptive name for your function that accurately conveys its purpose.
2. **Argument input**: define the input arguments for customizing output inside `function()`. Open brackets `{}` after your function to include 3 and 4.
3. **Performing the operation**: write the code to perform the desired operation or computation within the function, incorporating the input arguments to manipulate or process the data.
4. **Output**: the `return()` statement to return the intended output from the function.
## Functions: example
```{r}
# Function to calculate the area of a rectangle
calculate_rectangle_area <- function(length, width) {
# Perform the operation
area <- length * width
# Return the output
return(area)
}
# Call the function with specific arguments
calculate_rectangle_area(length = 5, width = 3)
```
## Loops: steps
1. **Loop structure**: specify the loop *control variable* `i` and its initial value.
2. **Loop body**: write the loop body code and ensure to update the loop control variable accordingly within the loop.
3. **Loop termination**: make sure the termination condition is eventually met to avoid infinite loops.
## Loops: example
```{r}
n <- 5 # Set the value of n
# Loop structure from 1 to n
for (i in 1:n) {
# Loop body
result <- 1 + i
# Loop termination, in this case when n=5
print(result)
}
```
# Functions and loops: example
```{r}
# Loop to calculate the sum of numbers from 1 to n
calculate_sum <- function(n) {
# Initialize the sum variable
sum_result <- 0
# Loop through the numbers from 1 to n
for (i in 1:n) {
# Add the current number to the sum
sum_result <- sum_result + i
}
# Return the final sum
return(sum_result)
}
# Call the function with a specific value of n
calculate_sum(n = 10)
```
### Cache analysis
Caching analyses is straightforward.
Here's example code.
On the first run on my computer, this took about 10 seconds.
On subsequent runs, this code was not run.
If you want to rerun cached code chunks, just [delete the contents of the `cache` folder](http://stackoverflow.com/a/10629121/180892)
```{r , cache=TRUE}
for (i in 1:5000) {
lm((i+1)~i)
}
```
## Basic markdown functionality
For those not familiar with standard [Markdown](http://daringfireball.net/projects/markdown/), the following may be useful.
See the source code for how to produce such points. However, RStudio does include a Markdown quick reference button that adequatly covers this material.
### Dot Points
Simple dot points:
* Point 1
* Point 2
* Point 3
and numeric dot points:
1. Number 1
2. Number 2
3. Number 3
and nested dot points:
* A
* A.1
* A.2
* B
* B.1
* B.2
### Equations
Equations are included by using LaTeX notation and including them either between single dollar signs (inline equations) or double dollar signs (displayed equations).
If you hang around the Q&A site [CrossValidated](http://stats.stackexchange.com) you'll be familiar with this idea.
There are inline equations such as $y_i = \alpha + \beta x_i + e_i$.
And displayed formulas:
$$\frac{1}{1+\exp(-x)}$$
$$
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$
$$
\begin{split}
X & = (x+a)(x-b) \\
& = x(x-b) + a(x-b) \\
& = x^2 + x(a-b) - ab
\end{split}
$$
More info:
[LaTeX wiki](https://en.wikibooks.org/wiki/LaTeX/Mathematics)
### Tables
Tables can be included using the following notation
A | B | C
--- | --- | ---
1 | Male | Blue
2 | Female | Pink
Or you want to show nice regression tables
```{r}
Mod1 <- y ~ x
Res1 <-
lm(formula = Mod1,
data = df)
Mod2 <- y ~ x^2
Res2 <-
lm(formula = Mod2,
data = df)
```
```{r, results='asis'}
# notice option: results='asis'
stargazer(Res1, Res2)
#For html
#stargazer(Res1, Res2, type = "html")
```
More info:
[Cheat Sheet](https://www.jakeruss.com/cheatsheets/stargazer/)
If you want to create a fancy table from data.frame, you can use "pander"
```{r}
Table <-
df %>%
mutate(z = if_else(y>5, 1, 0)) %>%
t()
Table
```
With `pander`
```{r}
Table %>%
pander(caption ="Fancy Table")
```