---
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
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

#install.packages("stargazer")
#install.packages("pander")
#install.packages("kableExtra")
#install.packages("tidyverse")

library(stargazer)
library(pander)
library(kableExtra)
library(tidyverse)

```



# 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.



# `RMarkdown`

- Save the following [Cheat Sheet](https://posit.co/wp-content/uploads/2022/10/rmarkdown-1.pdf) for `RMarkdown`.

- If any of you is looking for an general introduction for `RMarkdown`, I suggest you to check [Chapter 27](https://r4ds.had.co.nz/r-markdown.html) from Wickham and Grolemund ([2017](https://r4ds.had.co.nz/index.html)) - **R for Data Science**.

- If you want a more comprehensive guide, then check Xie et al. ([2021](https://bookdown.org/yihui/rmarkdown/)) - **R Markdown: The Definitive Guide**.

- Another, more applied, resource is Xie et al. ([2022](https://bookdown.org/yihui/rmarkdown-cookbook/)) - **R Markdown Cookbook**.




## 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. 

  - Short cut in Windows: \texttt{Ctrl + Alt + I}
  - Short cut in macOS: \texttt{Cmd + Option + I}

This will produce the following code chunk:

```{r}
    
```



The code chunk input and output is then displayed as follows:

```{r basicconsole, echo=FALSE}
set.seed(12345) # set the seed to generate the same numbers

x <- 1:10
y <- round(rnorm(10, x, 1), 3)
df <- data.frame(x, y)
df
```



In the prose/text area (outside the console area), you can call the console to report quantities using `r df$y[4]`. The in-text console also allows you to embed other R functions to customize the output, such as `r round(df$y[9], digits = 2)`. In the previous line, I used the function `round()` to round the ninth element or observation from the vector `y` to two digits.


- Frequently used chunk options

Option  |   Description
- | -----
include  |  If `FALSE`, knitr will run the chunk but **not** include the chunk in the final document
echo     |  If `FALSE`, knitr will **not** display the code in the code chunk above it’s results in the final document.
error    |  If `FALSE`, knitr will **not** display any error messages generated by the code.
message  |  If `FALSE`, knitr will **not** display any messages generated by the code.
warning  |  If `FALSE`, knitr will **not** display any warning messages generated by the code.


## Recommendation for homework


Option  |  HW setting
--- | --- 
include  | TRUE  | 
echo     | TRUE  | 
error    | FALSE  | 
message  | FALSE  | 
warning  | FALSE  | 


## 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}

Res1 <- lm(formula = y ~ x, data = df)

Res2 <- lm(formula = y ~ x + I(x^2), 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")

```


With `kableExtra`
```{r}

Table %>% kableExtra::kable()

```




# Intro to ggplot (with dplyr)


We are going to use the gapminder dataset to perform exploratory data analysis with dplyr and ggplot.

```{r}

# load data
df <- read.csv("data/gapminder.csv")

# check first observations
head(df)

# what is the average income (gdpPercap) per continent?
aggregate(df$gdpPercap, list(df$continent), mean)

```


In class, we have seen the function aggregate to aggregate quantities of interest, such as group means or variances. 

In the tydverse environment, dplyr has several functions that perform similar functions to aggregate and even more that will be very handy to explore your panel datasets.




## `group_by` for `summarize()` data.

- `group_by` sets up the data frame so that you can apply functions to each group separately using `dplyr` functions.

  - You shall call the function through **code chaining** using the pipe operator: `%>%`
  
  - Short cut in Windows: \texttt{Ctrl + Alt + M}
  - Short cut in macOS: \texttt{Cmd + Option + M}
  
  
- I recommend you to use data frames of class `tibble` instead of `data.frame`. See example below

In the example below, I show the difference between base R coding with `data.frame()` class and pipping or chaining coding `%>%` with `tibble()` class.

```{r}

# Looking at your data in the console with df
head(as.data.frame(df),2)

# Looking at your data in the console with tibble
df %>% 
  as_tibble() %>% 
  head(2)

```



- `group_by` is a function in the dplyr package that allows you to group a data frame by one or more variables.

- When you use `group_by`, dplyr creates a new object that is a **grouped** version of the original data frame.


```{r}
df %>% 
  as_tibble() %>% 
  group_by(country) %>% 
  head()
```



`summarize()` is a function in the dplyr package that allows you to apply functions to each group in a grouped data frame and return a summary result.


```{r}
df %>% 
  as_tibble() %>% 
  group_by(continent) %>% 
  summarize(gdp=mean(gdpPercap,na.rm=T),
            life=mean(lifeExp,na.rm=T))

# You can comment your code after pipping it!

df %>% 
  # transfomr the df as tibble
  as_tibble() %>% 
  # group the data by continents
  group_by(continent) %>% 
  # summarize group means
  summarize(gdp=mean(gdpPercap,na.rm=T),
            life=mean(lifeExp,na.rm=T)) %>% 
  # generate a table output
  kableExtra::kable()


```



## Grammar of graphics: `ggplot2`

- `ggplot2`: A *layered* grammer of graphics ([Wickham 2009](https://ggplot2-book.org/)).

  - Build a graphic from multiple layers; each consists of some geometric objects or transformation 
  
  - Use `+` to stack up layers

- *What* data do you want to visualize?
  - **`ggplot(data = ...)`**


- *How* are variables mapped to specific aesthetic attributes?
  - **`aes(... = ...)`**
    - positions (`x`, `y`), `shape`, `colour`, `size`, `fill`, `alpha`, `linetype`, `label`...
    - If the value of an attribute do not vary with regard to some variable, don't wrap it within `aes(...)`



- *Which* geometric shapes do you use to represent the data?
  - **`geom_{}`**:
    - `geom_point`, `geom_line`, `geom_ribbon`, `geom_polygon`, `geom_label`...


### Step 1: Define a basic ggplot object with x and y aesthetics

```{r}
ggplot(data=df,
       aes(x=gdpPercap,
           y=lifeExp))
```


### Step 2: Define a geometric shape

```{r}

df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp)) +
  # geometry
  geom_point()

```


**Note**: we are not limited to have a single geometric form


```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp)) +
  # geometry point
  geom_point() +
  # geometry loess fit
  geom_smooth()

```


### Step 3: modify coordinates or other arguments to customize the visual.


```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp)) +
  # geometry point
  geom_point() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log")

```


### Step 3: scale or transform coordinates or other arguments to customize the visual.


```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp)) +
  # geometry point
  geom_point() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000))

```


Now, I am going to include a new `aes`thetic: **color**.



```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp,
           # introduce color aesthetics
           color=continent)) +
  # geometry point
  geom_point() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000))

```


### Step 5: Add x and y axis labels and a title



```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp,
           # introduce color aesthetics
           color=continent)) +
  # geometry point
  geom_point() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000)) +
  # Tittle
  labs(x="GDP per capita (log)",
       y="Life Expectancy",
       title="Income and life expectancy in the continents")

```



*Note*: sometimes, a `geom` can be fitted but the visual is not appealing.



```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp,
           # introduce color aesthetics
           color=continent)) +
  # geometry point
  geom_point() +
  # geometry smooth
  geom_smooth() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000)) +
  # Tittle
  labs(x="GDP per capita (log)",
       y="Life Expectancy",
       title="Income and life expectancy in the continents")

```



### Step 6: create small multiples



```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp,
           # introduce color aesthetics
           color=continent)) +
  # geometry point
  geom_point() +
  # geometry smooth
  geom_smooth() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000)) +
  # Tittle
  labs(x="GDP per capita (log)",
       y="Life Expectancy",
       title="Income and life expectancy in the continents") +
  # Plot panels with small multiples
  facet_wrap(~continent)

```



You can use the argument `alpha` the set the degree of transparency of a specific `geom`.


```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp,
           # introduce color aesthetics
           color=continent)) +
  # geometry point
  geom_point(alpha=0.1) +
  # geometry smooth
  geom_smooth() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000)) +
  # Tittle
  labs(x="GDP per capita (log)",
       y="Life Expectancy",
       title="Income and life expectancy in the continents") +
  # Plot panels with small multiples
  facet_wrap(~continent)

```



### Step 6: modify the `theme_`.


```{r}
df %>% 
  ggplot(# aesthetics
       aes(x=gdpPercap,
           y=lifeExp,
           # introduce color aesthetics
           color=continent)) +
  # geometry point
  geom_point(alpha=0.1) +
  # geometry smooth
  geom_smooth() +
  # Transform the scale of X variable
  scale_x_continuous(trans = "log",
                     # introduce breaks
                     breaks = c(500,
                                1500,
                                20000,
                                60000)) +
  # Tittle
  labs(x="GDP per capita (log)",
       y="Life Expectancy",
       title="Income and life expectancy in the continents") +
  # Plot panels with small multiples
  facet_wrap(~continent) +
  # theme for the plot
theme_bw()

```




## Grammar of graphics in `ggplot2`

- `ggplot2` is a powerful tool for creating professional visualizations.

- Search on the internet for help with specific plot types using keywords based on geometries, such as **line plots**, **histograms**, **boxplots**, **coefficient plots**, etc.













