---
title: "Descriptive Analysis"
subtitle: "[R for Stata Users](https://github.com/worldbank)"
author: "Luiza Andrade, Marc-Andrea Fiorina, Rob Marty, Maria Reyes Retana, Rony Rodriguez Ramirez, Luis Eduardo San Martin, Leonardo Viotti"
date: "The World Bank | [WB Github](https://github.com/worldbank) <br> March 2024"
output:
  xaringan::moon_reader:
    css: ["libs/remark-css/default.css", 
          "libs/remark-css/metropolis.css", 
          "libs/remark-css/metropolis-fonts.css",
          "libs/remark-css/custom.css"] 
    lib_dir: libs
    nature:
      ratio: "16:9"
      highlightStyle: github
      highlightLines: true
      countIncrementalSlides: false
---

```{r setup, include = FALSE}
 
# Load packages
library(knitr)
library(tidyverse)
library(hrbrthemes)
library(fontawesome)
library(here)
library(xaringanExtra)
library(countdown)

here::i_am("Presentations/05-descriptive-analysis.Rmd")

options(htmltools.dir.version = FALSE)
opts_chunk$set(
  fig.align = "center",
  fig.height = 4,
  dpi = 300,
  cache = T
  )

xaringanExtra::use_panelset()
xaringanExtra::use_webcam()
xaringanExtra::use_clipboard()
xaringanExtra::use_editable(expires = 1)

htmltools::tagList(
  xaringanExtra::use_clipboard(
    success_text = "<i class=\"fa fa-check\" style=\"color: #90BE6D\"></i>",
    error_text = "<i class=\"fa fa-times-circle\" style=\"color: #F94144\"></i>"
  ),
  rmarkdown::html_dependency_font_awesome()
)

xaringanExtra::use_logo(
  image_url = here("Presentations",
                   "img",
                   "lightbulb.png"),
  exclude_class = c("inverse", 
                    "hide_logo"),
  width = "50px"
)

htmltools::tagList(
  xaringanExtra::use_clipboard(
    button_text = "<i class=\"fa fa-clipboard\"></i>",
    success_text = "<i class=\"fa fa-check\" style=\"color: #90BE6D\"></i>",
    error_text = "<i class=\"fa fa-times-circle\" style=\"color: #F94144\"></i>"
  ),
  rmarkdown::html_dependency_font_awesome()
)
```

# Introduction

### Initial Setup

.panelset[

.panel[.panel-name[If You Attended Session 2]
1. Go to the `dime-r-training-mar2024` folder that you created yesterday, and open the `dime-r-training-mar2024` R project that you created there.
]

.panel[.panel-name[If You Did Not Attend Session 2]

 1. Open RStudio.

 2. Type in the following lines, replacing “YOURFILEPATHHERE” with a file path where the file path where you will place this R project. 

```{r, eval=FALSE}
install.packages("usethis")
library(usethis)
usethis::use_course(
    "https://github.com/worldbank/dime-r-training/archive/main.zip",
    destdir = "YOURFILEPATHHERE"
)
```

 3\. In the console, type in the requisite number to delete the .zip file (we don't need it anymore)

 4\. A new RStudio environment will open. Use this for the session today. 
  
  
]

]

---
# Table of contents

.vlarge[
1. [Quick summary statistics](#exploring)
2. [Descriptive statistics tables](#desc_tables)
3. [Exporting descriptive statistics tables](#exporting)
3. [Formatting tables](#beautifying)
3. [Aggregating observations](#aggregating)
3. [Running regressions](#regressing)
3. [Exporting regression tables](#reg_tables)
]


???

I'm here to talk to you about creating tables in R. Although in terms of data analysis this is very similar to data visualization, in the sense that what we are doing is trying to display information about the data in the most concise and informative manner, the tools and packages required to implement the two are very different. Which is why we separated them into two sessions.

I will tell you exactly what are we going to do for the next hour and a half in a little bit, but first, let me ask you all something: what software do you usually export your tables to?

The objection of this session is to show you have to do 4 things:
- print quick statistics to explore your data
- export summary statistics tables in the most reproducible way possible
- run simple regressions
- export regression tables

I think most of you here know me already and have heard my spiel before, but since that's what I do, let's take a look at what I mean by reproducible

---

# Workflows for outputs

## .red[Not reproducible]

Anything that requires
`r fa("paste", fill = "#ac142a")` Copy-pasting
`r fa("paintbrush", fill = "#ac142a")` Manual formatting after exported

--

## .green[Reproducible]

`r fa("r-project", fill = "#046307")` R Markdown: dynamic document containing code and text that is exported directly from R into PDF, HTML, Word, Power Point and other formats 
`r fa("file-lines", fill= "#046307")` LaTeX: typesetting system used for scientific publications that automatically reloads tables and figures every time the document is rendered 

???

What is NOT reproducible? Anything that requires manual steps to update results in your final document after you update the data or the exact specification. This includes the terrible practice of printing results in the console and pasting them into Word, but also the much less terrible practice of exporting results to Excel and then manually formatting them and copying into Word.

Can someone tell me why these are not ideal practices?

The two best options to combine with R in terms of reproducibility are Markdown and LaTeX. Markdown is R's dyamic document framework and it's amazingly well developed. Most R advanced R users actually use Markdown to display their results instead of exporting tables and figures. I'm going to show you what that looks like, but this is a slightly more advanced topic that will not be covered on this course.

LaTeX, on the other hand, is widely used among non-R users, and there are plenty of packages to export tables to it in Stata as well.

But that's enough of me talking. Let's get you all to run some code

---

# Setting the stage


Load the packages that we will use today
```{r, eval = F}
# Install new packages
install.packages("modelsummary")
install.packages("fixest")
install.packages("janitor")
install.packages("huxtable")
install.packages("openxlsx")
```

```{r, warning = FALSE, message = FALSE}
# Load packages
library(here)
library(tidyverse)
library(modelsummary)
library(fixest)
library(janitor)
library(huxtable)
library(openxlsx)
```

---

# Setting the stage

Load the data that we will use today: Stata's `census` dataset

**Tip**: Use `here`, as we saw in the data wrangling session. 

`r countdown(minutes = 2, seconds = 0, left = 0, font_size = "2em")`

--

```{r}
  # Load data
   census <-
    read_rds(
      here(
        "DataWork",
        "DataSets", 
        "Final", 
        "census.rds"
      )
    )
```




???

So first thing, as usual, is make sure you are setting your folder paths so R knows where to find files and where to export them too.

If you have already downloaded the DataWork folder from OSF, all you need to do now is edit this line of code to match your computer. I'll do it on mine in case you don't remember the exact steps.

Then we will load the packages for today: tidyverse, as usual, and two new packages: modelsummary and huxtable, which we will learn about soon.

Finally, let's load some data. This dataset is probably already familiar to most of you: it's Stata's built-in 1980 census data at state level.

Double-check that you can see this dataset in your environment pane. Now, can someone tell me something about this dataset and how to get a little bit of information about it?

We discussed it in the data wrangling session. 

---

# Taking a peek at the data

```{r}
glimpse(census)
```

---

class: inverse, center, middle
name: exploring

# Quick summary statistics

<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Exploring a dataset

.command[
## `summary(x, digits)`
Equivalent to Stata's `codebook`. Its arguments are:
  
 * **x:** the object you want to summarize, usually a vector or data frame
 * *digits:* the number of decimal digits to be displayed
]

--

.exercise[

### Exercise 1 `r fa("keyboard")`
Use the `summary()` function to describe the `census` data frame.
]

`r countdown(minutes = 0, seconds = 45, left = 0, font_size = "2em")`

---

# Exploring a dataset

.small[
```{r}
summary(census)
```
]

---

# Exploring a dataset

 ```{r echo=FALSE}
 knitr::include_app("https://rrmaximiliano.shinyapps.io/learnr-app/")
 ```

---

# Summarizing continuous variables

.large[
- `summary()` can also be used with a single variable.
- When used with continuous variables, it works similarly to `summarize` in Stata.
- When used with categorical variables, it works similarly to `tabulate`.
]

---

# Summarizing continuous variables

.exercise[

### Exercise 2 `r fa("keyboard")`
Use the `summary()` function to display summary statistics for a continuous variable in the  `census` data frame.
]

`r countdown(minutes = 0, seconds = 45, left = 0, font_size = "2em")`

???

Note that we have already summarized continuous and categorical variables when summarizing the entire data frame. But this is a reminder of how to select a single column inside a data frame. So choose are continuous variables you can find and summarize only that variable.

---

# Summarizing continuous variables

.exercise[

### Exercise 2 `r fa("keyboard")`
Use the `summary()` function to display summary statistics for a continuous variable in the  `census` data frame.
]

```{r}
summary(census$pop)
```

---

# Summarizing continuous variables

 ```{r echo=FALSE}
 knitr::include_app("https://rrmaximiliano.shinyapps.io/learnr-app/")
 ```

---

# Summarizing categorical variables

.command[
## `tabyl(x, ...)`
Equivalent to `tabulate` in Stata, creates a frequency table. Its main arguments are vectors to be tabulated.

 * **x:** the object you want to summarize, usually a vector or data frame
 * *...* additional options as show_na, or show_missing_levels. 
]

--

.exercise[
### Exercise 3 `r fa("keyboard")`
Use the `tabyl()` function to display frequency tables for:

1. The variable `region` in the `census` data frame
2. The variables `region` and `state` in the `census` data frame, simultaneously
]

`r countdown(minutes = 1, seconds = 0, left = 0, font_size = "2em")`


---

# Summarizing categorical variables

## One way tabulation

```{r}
census %>% 
  tabyl(region)
```

???

Note that this and other tables that we will create during this session look more polished in the presentation than when you print them to the console. That's because the commands have a pre-defined printing option for RMArkdown, which was used to create this presentation

---

# Summarizing categorical variables

## Two way tabulation

```{r, eval = F}
census %>%
  tabyl(state, region)
```
```{r, echo = F}
census %>%
  filter(substring(state, 1, 1) %in% c("A", "C")) %>%
  tabyl(state, region)
```


???

Note that the output of `table` having a single variable as argument is the same as that of `summary`. However, `table` can also do two-way tabulations

---


class: inverse, center, middle
name: desc_tables

# Descriptives tables

<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Descriptives tables

## What if you want to...
- ...export the summary statistics to another software?
- ...customize which statistics to display?
- ...format the table?

--

## Well, then you will need a few more packages
- There are many packages that can be used both for displaying and exporting summary statistics
- Today we will show you a combination of two packages: `modelsummary` and `huxtable`
- We chose this combination because together, they can perform all the tasks we are interested in
- In fact, `modelsummary` can perform most of them by itself -- with the exception of exporting formatted tables to Excel

---

# Exploring datasets with *modelsummary*

.large[
The package *modelsummary* contains a family of functions called `datasummary` which can be used to create different types of summary statistics tables. These include:

- `datasummary_skim`, to create descriptive statistics tables
- `datasummary_balance`, to create balance tables
- `datasummary_correlation`, to create a correlation table
- `datasummary_crosstab`, to create a twoway tabulation
- `datasummary`, to create customized descriptive statistics tables
]

---

# Exploring datasets with *modelsummary*

.command[
## `datasummary_skim(data, output, ....)`

 * **data:** the data set to be summarized, the only required argument
 * **output:** the type of output desired
 * *...:* additional options allow for formatting customization, such as including notes and titles
]

```{r, eval = F}
datasummary_skim(
  data,
  type = "numeric",
  output = "default",
  histogram = TRUE,
  title = NULL,
  notes = NULL,
  ...
)
```

---


# Exploring datasets with *modelsummary*

.large[
.exercise[
### Exercise 4 `r fa("keyboard")`

Use `datasummary_skim()` to create a descriptive statistics table for the `census` data. 
]
]
`r countdown(minutes = 0, seconds = 45, left = 0, font_size = "2em")`

---

# Exploring datasets with *modelsummary*

```{r, eval = F}
datasummary_skim(census)
```


.small[
```{r, echo = F}
datasummary_skim(census)
```
]




---

# Exploring datasets with *modelsummary*

 ```{r echo=FALSE}
 knitr::include_app("https://rrmaximiliano.shinyapps.io/learnr-app/")
 ```

---

# Exploring datasets with *modelsummary*

.large[
- *modelsummary* summarizes only numeric variables by default.
- To summarize categorical variables, use the argument `type`

```{r, eval = FALSE}
datasummary_skim(census, type = "categorical")
```
]

```{r, echo = FALSE}
datasummary_skim(census$region, type = "categorical")
```

---

# Exploring datasets with *modelsummary*

You can also customize the variables and statistics to include using a **formula** with the `datasummary()` function.

.command[
## `datasummary(formula, data, output, ...)`

 * **formula:** a two-sided formula to describe the table: rows ~ columns
 * **data:** the data set to be summarized
 * *output:* the type of output desired
 * *...:* additional options allow for formatting customization

]

```{r, eval = F}
datasummary(
  var1 + var2 + var3 ~ stat1 + stat2 + stat3 + stat4,
  data = data
)
```

---

# Exploring datasets with *modelsummary*

.exercise[
### Exercise 5 `r fa("keyboard")`
Create a table showing the number of observations, mean, standard deviation, minimum, maximum and median value for all the population, number of deaths, number of marriage and number of divorces in the `census` data.
]

.can-edit[
```{r, eval = F}
datasummary(
  var1 + var2 + var3 ~ stat1 + stat2 + stat3 + stat4,
  data = data
)
```
]

> **Tip:** some of the allowed statistics are N, Mean, SD, Min, Max, Median, P0, P25, P50, P75, P100, Histogram


`r countdown(minutes = 1, seconds = 30, left = 0, font_size = "2em")`

---

# Exploring datasets with *modelsummary*

.large[
```{r, eval = F}
datasummary(
  pop + death + marriage + divorce ~ N + Mean + SD + Median + Min + Max,
  data = census
)
```
]

```{r, echo = F}
datasummary(
  pop + death + marriage + divorce ~ N + Mean + SD + Median + Min + Max,
  data = census
)
```

---

# Exploring datasets with *modelsummary*

.pull-left[
```{r, eval = F}
datasummary(
  All(census) ~ N + Mean + SD + Median + Min + Max,
  data = census
)
```
]

.pull-right[
.small[
```{r, echo = F}
datasummary(
  All(census) ~ N + Mean + SD + Median + Min + Max,
  data = census
)
```
]
]

---

# Balance tables with *modelsummary*

```{r, eval = FALSE}
census_rct <-
  census %>%
  mutate(
    treatment = as.numeric(runif(n()) > 0.5)
  ) %>%
  select(
    -starts_with("state")
  )

datasummary_balance(
  ~ treatment,
  data = census_rct
)
```

---

# Balance tables with *modelsummary*

.small[
```{r, echo = FALSE}
census_rct <-
  census %>%
  mutate(
    treatment = as.numeric(runif(n()) > 0.5)
  ) %>%
  select(
    -starts_with("state")
  )

datasummary_balance(
  ~ treatment,
  data = census_rct
)
```
]

---

class: inverse, center, middle
name: exporting

# Exporting tables

<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Exporting *modelsummary* table to LaTeX

To export the tables we created, we can simply use the option `output`:

```{r, message = FALSE, warning = FALSE}
descriptives <-
  All(census) ~ N + Mean + SD + Median + Min + Max

datasummary(
  descriptives,
  data = census,
  output = here( # file path to output file  #<<
    "DataWork", #<<
    "Output", #<<
    "Raw", #<<
    "summary-stats.tex" #<<
  ) #<<
)
```

---

# Exporting *modelsummary* table

.large[
Other valid output formats include: 

* `.docx`
* `.pptx`
* `.html`
* `.md`
]

---

# Exporting *modelsummary* table

.large[
Other valid output formats include: 

* `.docx`
* `.pptx`
* `.html`
* `.md`
* ... but not `.xls`
]

---

# Exporting *modelsummary* table to Excel

.pull-left[
.large[
- To export the table to Excel, we will first convert it into an object of type *huxtable*
- `huxtable` is another R package, one that allows not only for exporting tables, but also for extensive customization
- Before getting to the customization part, however, let's export this table:
]
]

.pull-right[
```{r}
# Create the huxtable object
summary_stats_table <-
  datasummary(
    descriptives,
    data = census,
    output = "huxtable"
  )

# Export it to Excel 
quick_xlsx(
  summary_stats_table, # object to be exported
  file = here( # file path to output file
    "DataWork",
    "Output",
    "Raw",
    "summary-stats.xlsx"
  )
)
```
]

---

# Exporting tables

A similar code can also export the same table to a self-standing LaTeX document

```{r}
# Export to LaTeX
quick_latex(
  summary_stats_table,
  file = here(
    "DataWork",
    "Output",
    "Raw",
    "summary-stats.tex"
  )
)
```

---

# Exporting tables to different Excel tabs

.small[
```{r}
# Start a new workbook
wb <- createWorkbook()

# Add one sheet to it
wb <-
  as_Workbook(
    summary_stats_table,
    Workbook = wb,
    sheet = "Summary stats"
  )

# Add another sheet to it
wb <-
  as_Workbook(
    hux("Mock", "table"),
    Workbook = wb,
    sheet = "Other sheet"
  )

# Save the workbook
saveWorkbook(
  wb, # object to be saved
   file = here( # file path to output file
    "DataWork",
    "Output",
    "Raw",
    "summary-stats.xlsx"
  ),
  overwrite = TRUE # replace existing file
)
```
]

---

# Exporting tables to LaTeX fragment

```{r}
summary_stats_table %>%
  print_latex() %>% # See LaTeX code
  # Save LaTeX code 
  capture.output(
    file = here(
      "DataWork",
      "Output",
      "Raw",
      "summary-stats.tex"
    )
  )

```

You will also need to load the required LaTeX packages. To copy the code that creates a preamble with all of them, use this code:

```{r, eval = FALSE}
report_latex_dependencies()
```

---
class: inverse, center, middle
name: beautifying

# Formatting tables

<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Beautifying tables

- `huxtable` also allows you to customize table formatting so it can be exported with the same layout to multiple software
- Before we do that, however, we will create a version of the data where the variable names are the Stata labels

```{r, message = FALSE, warning = FALSE}
# Extract variable labels from data frame
labels <- names(census)
names(labels) <- attributes(census)$var.labels

# Rename the variables
census_labelled <-
  census %>%
  rename(
    labels
  )

# Create a labelled summary table 
summary_stats_table <-
  datasummary(
    All(census_labelled) ~ N + Mean + SD + Median + Min + Max,
    data = census_labelled,
    output = "huxtable"
  )
```

---

# Beautifying tables

The code below shows the table `summary_stats_table` can be formatted

.pull-left[
```{r, eval = FALSE}
# Format table
summary_stats_table %>%  
 # Use first row as table header 
 set_header_rows(1, TRUE) %>% 
 # Use first column as row header 
 set_header_cols(1, TRUE)  %>%  
 # Don't round large numbers  
 set_number_format(everywhere, 2:ncol(.), "%9.0f") %>% 
 # Centralize cells in first row 
 set_align(1, everywhere, "center") %>% 
 # Set a theme for quick formatting 
 theme_basic()
```
]

.pull-right[
.small[
```{r, echo = F, message = F}
# Format table
 summary_stats_table %>%  
   set_header_rows(1, TRUE) %>% # Use first row as table header 
   set_header_cols(1, TRUE)  %>%  # Use first column as row header 
   set_number_format(everywhere, 2:ncol(.), "%9.0f") %>% # Don't round large numbers  
   set_align(1, everywhere, "center") %>% # Centralize cells in first row 
   theme_basic() # Set a theme for quick formatting 

```
]
]

---

# Export beautified tables

```{r, message = FALSE}
# Format table
summary_stats_table <-
  summary_stats_table %>%  
  set_header_rows(1, TRUE) %>% # Use first row as table header 
  set_header_cols(1, TRUE)  %>%  # Use first column as row header 
  set_number_format(everywhere, 2:ncol(.), "%9.0f") %>% # Don't round large numbers  
  set_align(1, everywhere, "center") %>% # Centralize cells in first row 
  theme_basic() # Set a theme for quick formatting 

quick_xlsx(
  summary_stats_table,
  file = here(
    "DataWork",
    "Output",
    "Raw",
    "summary-stats-basic.xlsx"
  )
)
```

---

# Export beautified tables

.pull-left[
## .red[Before]
![](img/summary-stats.png)
]


.pull-right[
## .green[After]
![](img/summary-stats-basic.png)
]

---

# Other themes to play with

![https://cran.r-project.org/web/packages/huxtable/vignettes/themes.html](img/themes.png){width=90%}

---

class: inverse, center, middle
name: regressing

# Ok, can we run some regressions now?!

<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Running regressions

The base R command for linear regressions is called `lm`

.command[
## lm(formula, data, subset, weights, ...)

- **formula:**	an object of class "formula" containing a symbolic description of the model
- **data:** a data frame containing the variables indicated in the formula
- *subset:* an optional vector specifying a subset of observations to be used in the regression
- *weights:* an optional vector of weights to be used in the regression
]

Formulas can take three specifications:
- `y ~ x1 + x2` regresses variable `y` on covariates `x1` and `x2`
- `y ~ x1:x2` regresses variable `y` on the interaction of covariates `x1` and `x2`
- `y ~ x1*x2` is equivalent to `y ~ x1 + x2 + x1:x2`

---

# Running regressions

.exercise[
### Exercise 6 `r fa("keyboard")`
Using the `census` data, run a regression of the number of divorces on population, urban population and number of marriages.
]

.can-edit[
```{r, eval = F}
  lm(y ~ x1 + x2,
     data)
```
]

`r countdown(minutes = 1, seconds = 0, left = 0, font_size = "2em")`


---

# Running regressions

.exercise[
### Exercise 6 `r fa("keyboard")`
Using the `census` data, run a regression of the number of divorces on population, urban population and number of marriages.
]


```{r}
reg1 <-
  lm(
    divorce ~ pop + popurban + marriage,
    census
  )
```


---

# Running regressions

.large[
- The output of regression commands is a list of relevant information.
- By default, it prints only a small portion of this information.
- The best way to visualize results is to store this list in an object and then access its contents using the function `summary`
]

---

# Running regressions

.small[
```{r}
reg1 <-
  lm(
    divorce ~ pop + popurban + marriage,
    census
  )

summary(reg1)
```
]

---

# Running regressions

The `feols` command from package `fixest` allows for more flexibility in model specification

.command[
## feols(formula, data, subset, weights, ...)

- **formula:**	an object of class "formula" containing a symbolic description of the model
- **data:** a data frame containing the variables indicated in the formula
- *vcov:* one of "iid", "hetero" (or "HC1"), "cluster", "twoway", "NW" (or "newey_west"), "DK" (or "driscoll_kraay"), or "conley"
- *subset:* an optional vector specifying a subset of observations to be used in the regression
- *weights:* an optional vector of weights to be used in the regression
- *cluster:* a list of vectors, a character vector of variable names, a formula or an integer vector specifying how to cluster standard errors
- ...
]

---

# Running regressions

Formulas for `feols` are more complex, and take the following format:
`y ~ x1 + x2 | fe1 + fe2 | x3 ~ iv3`
- `y ~ x1 + x2` takes all the same formulas as `lm`
- `fe1 + fe2` list the variables to be included as fixed effects
- `x3 ~ iv3` uses instrument `iv3` for variable `x3`

---

# Running regressions

.exercise[
### Exercise 7 `r fa("keyboard")`
Using the `census` data, run a regression of the number of divorces on population, urban population and number of marriages controlling for region fixed effects.
]

.can-edit[
```{r, eval = F}
feols(
  y ~ x1 + x2 | fe1 + fe2,
  data
)
```
]

`r countdown(minutes = 1, seconds = 0, left = 0, font_size = "2em")`


---

# Running regressions


.exercise[
### Exercise 7 `r fa("keyboard")`
Using the `census` data, run a regression of divorce on population, urban population and number of marriages controlling for region fixed effects.
]

```{r, eval = FALSE}
reg2 <-
  feols(
    divorce ~ pop + popurban + marriage | region,
    census,
    se = "iid"
  )

summary(reg2)
```

???

Note that feols uses clusters standard errors by default. To avoid this behavior, se `se = "iid"`

---

# Running regressions

.small[
```{r}
reg2 <-
  feols(
    divorce ~ pop + popurban + marriage | region,
    census,
    se = "iid"
  )

summary(reg2)
```
]

---

# Some notes on regressions

.large[
- Whenever a factor is included in the list of covariates, it is treated as a categorical variable, i.e., as if you had written `i.x` in Stata.
- Whenever a boolean is included in the list of covariates, it is treated as a dummy variable, where `TRUE` is `1` and `FALSE` is `0`.
]

---

class: inverse, center, middle
name: reg_tables

# Exporting regression tables

<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Exporting regression tables

`huxtable` also has a quick wrapper for regression tables

.command[
## huxreg(...)
- **...**: Models, or a single list of models. Names will be used as column headings.
- *number_format:* Format for numbering. See number_format() for details.
- *stars:* Levels for p value stars.
- *bold_signif:* Where p values are below this number, cells will be displayed in bold.
- *note:* Footnote for bottom cell, which spans all columns.
- *statistics:* A vector of summary statistics to display.
- *coefs:* A vector of coefficients to display. To change display names, name the coef vector: c("Displayed title" = "coefficient_name", ...)
]

---

# Exporting regression tables

.small[
```{r}
huxreg(reg1, reg2)
```
]

By now, you should know how to export this to Excel and LaTeX.

---

# Formatting regression tables

.pull-left[
```{r, eval = F}
huxreg(
  reg1, reg2,
  # Show variable labels instead of names
   coefs = c(
     "Population" = "pop", 
     "Urban population"  = "popurban",
     "Number of marriages" = "marriage"
   ),
   statistics = c("N. obs." = "nobs")) %>%
   add_rows(
     c("Region FE", "No", "Yes"),
     after = 7
   )
```
]

.pull-right[
```{r, echo = F}
huxreg(
  reg1, reg2,
   coefs = c(
     "Population" = "pop", # Show variable labels instead of names
     "Urban population"  = "popurban",
     "Number of marriages" = "marriage"
   ),
   statistics = c("N. obs." = "nobs")) %>%
   add_rows(
     c("Region FE", "No", "Yes"),
     after = 7
   )
```
]

---

# Exporting regression tables

.exercise[
### Exercise 8 `r fa("keyboard")`

Export a regression table with the results of your estimations using `lm` and `feols`:

- Use `huxreg` to combine `reg1` and `reg2`.
- Use `quick_xlsx` or `quick_latex` to export the output of `huxreg` to your preferred format.
]

`r countdown(minutes = 1, seconds = 0, left = 0, font_size = "2em")`

--

.pull-left[
```{r}
# Combine regression results with huxreg
reg_table <- huxreg(reg1, reg2)

# Export to Excel
quick_xlsx(reg_table,  file = here(
                               "DataWork",
                               "Output",
                               "Raw",
                               "regression_table.xlsx"))


```

]

.pull-right[
```{r}
# Or, export to LaTeX
quick_latex(reg_table, file = here(
                               "DataWork",
                               "Output",
                               "Raw",
                               "regression_table.tex"))
```
]

---



# References and recommendations


  * Econometrics with R
  https://www.econometrics-with-r.org/index.html
  
  * `modelsummary` documentation:
   https://vincentarelbundock.github.io/modelsummary/index.html

  * Introduction to `huxtable`:
  https://cran.r-project.org/web/packages/huxtable/vignettes/huxtable.html

  * Using `huxtable` for regression tables:
  https://cran.r-project.org/web/packages/huxtable/vignettes/huxreg.html
  
  * Sample code for tables in R:
  https://github.com/RRMaximiliano/r-latex-tables-sum-stats
  
  * More sample code for tables in R:
  https://evalsp20.classes.andrewheiss.com/reference/regtables/

  * Johns Hopkins Exploratory Data Analysis at Coursera:
  https://www.coursera.org/learn/exploratory-data-analysis

  * Udacity's Data Analysis with R:
  https://www.udacity.com/course/data-analysis-with-r--ud651


## Since we talked about LaTeX so much...

  * DIME LaTeX templates and trainings:
  https://github.com/worldbank/DIME-LaTeX-Templates

  * All you need to know about LaTeX:
  https://en.wikibooks.org/wiki/LaTeX

---

class: inverse, center, middle

# Thank you!

---

class: inverse, center, middle

# Appendix

---

class: inverse, center, middle
name: aggregating

# Aggregating observations


<html><div style='float:left'></div><hr color='#D38C28' size=1px width=1100px></html>

---

# Aggregating observations

.large[
- If you want to show aggregated statistics, the function `summarise` is a powerful tool.
- It is similar to `datasummary` in that it calculates a series of statistics for a data frame.
- However, it does not have pre-defined statistics, so it requires more manual input.
- On the other hand, its output is a regular data frame, so it is also useful to create constructed data sets.
- Its Stata equivalent would be `collapse`
]

---

# Aggregating observations

.command[
## `summarise(.data, ...,)`

- **data**: the data frame to be summarized
- **...**: Name-value pairs of summary functions. The name will be the name of the variable in the result.
]

--

The "name-value" pairs mentioned under `...` look like this: `new_variable = function(existing_variable)`, where possible functions include:

- Center: `mean()`, `median()`
- Spread: `sd()`, `IQR()`, `mad()`
- Range: `min()`, `max()`, `quantile()`
- Count: `n()`, `n_distinct()`

---

# Aggregating observations

.pull-left[
```{r}
region_stats <-
  census %>%
  group_by(region) %>%
  summarise(
    `Number of States` = n_distinct(state),
    `Total Population` = sum(pop)
  )
```
]

.pull-right[
```{r, echo = FALSE, message = FALSE, warning = F}
census %>%
  group_by(region) %>%
  summarise(`Number of States` = n_distinct(state),
            `Total Population` = sum(pop)) %>%
  kable
```
]

---

# Aggregating observations

.exercise[
### Exercise 9 `r fa("keyboard")`
Recreate the `region_stats` data set, now including the average and the standard deviation of the population.
]

`r countdown(minutes = 1, seconds = 30, left = 0, font_size = "2em")`

---

# Aggregating observations

```{r, message = F}
  region_stats <-
    census %>%
    group_by(region) %>%
    summarise(
      `Number of States` = n_distinct(state),
      `Total Population` = sum(pop),
      `Average Population` = mean(pop),
      `SD of Population` = sd(pop)
    )
```

```{r, echo = FALSE, message = F}
  region_stats %>%
  kable
```

---

# Aggregating observations

.exercise[
### Exercise 9 `r fa("keyboard")`
Use `huxtable` to format and export the object `region_stats`.
]

`r countdown(minutes = 2, seconds = 00, left = 0, font_size = "2em")`

---

# Aggregating observations

```{r}
  region_stats_table <-
    region_stats %>%
    rename(Region = region) %>%
    as_hux %>%
    set_header_cols("Region", TRUE)  %>%
    theme_bright()

  quick_xlsx(
    region_stats_table,
     file = here(
       "DataWork",
       "Output",
       "Raw",
       "region-stats.xlsx"
     )
  )
```

