---
title: A Template
author: Andrew Pua
date: May 18, 2023
bibliography: references.bib
toc: true
format:
  html:
    code-fold: false
    embed-resources: true
---

## What is this template?

In your final report, you should remove this section, as the material here is only for you to understand how to do things in Quarto.

This template is a radically simplified version of @heiss-templates. What you see now is a **rendered** version of a qmd file. This rendered version is an HTML file similar to the HTML pages you see at the course website. A qmd file is a text file which contains how the report is going to be formatted, how the elements of the report are going to be "weaved" together to form a final readable form. In the case of this template, it is an HTML file. You have to submit as part of your project so that I can run it on my own computer and generate the same HTML file that you did. 

You have to install [RStudio](https://posit.co/download/rstudio-desktop/). You do not need to install R anymore if you have installed it before. Afterwards, you have to install [Quarto](https://quarto.org/docs/get-started/). Ater installing Quarto, you may want to look at a short tutorial [here](https://quarto.org/docs/get-started/hello/rstudio.html). If you want to follow that tutorial on your computer, you may have to install the specified packages. 

But you can also just open the file [`template-final-report.qmd`](template-final-report.qmd) in RStudio and click on Render. Of course, you have to have the file [`references.bib`](references.bib) for the rendering to work. 

### Reading more about Quarto

You might find the Quarto guide on the following topics to be of interest:

-   [Authoring](https://quarto.org/docs/authoring/markdown-basics.html): probably the highest priority
-   [Citations and footnotes](https://quarto.org/docs/authoring/footnotes-and-citations.html)
-   [Cross-references and hyperlinks](https://quarto.org/docs/authoring/cross-references.html)
-   [Showing and hiding code](https://quarto.org/docs/output-formats/html-code.html#folding-code)
-   [Wrapping code](https://quarto.org/docs/output-formats/html-code.html#code-overflow)
-   [Themes](https://quarto.org/docs/output-formats/html-themes.html): not really a priority, but this is quite a rabbit hole
-   [HTML reference](https://quarto.org/docs/reference/formats/html.html)

### How to incorporate R calculations into your document

You can weave R code into your document.

```{r}
n_lights <- 2 + 2
n_lights
```

You can also simply display the code without asking R to evaluate the code.

```{r}
#| eval: false
n_lights <- 2 + 2
n_lights
```

You can load data, calculate things, make plots.

```{r}
# Code used in class, modify accordingly for your situation
cookie <- read.csv("https://mathstat.neocities.org/data_cookie.csv")
# Shows the entire dataset
cookie
# Presents histogram of number of chocolate chip cookies
hist(cookie$numchoc)
# Store the histogram as an object
temp <- hist(cookie$numchoc)
# What is stored in temp?
temp 
# Confidence interval calculation in HW02
ybar <- mean(cookie$numchoc)
J <- length(cookie$numchoc)
c <- sqrt(20)
c(2*ybar + c^2/J - sqrt(4*ybar*c^2/J + c^4/J^2), 2*ybar + c^2/J + sqrt(4*ybar*c^2/J + c^4/J^2))/2
```

Here I repeatedly generate $10^4$ artificial datasets from $\mathsf{U}\left(0,\theta\right)$. Set $n\in \{5, 500\}$ and $\theta=1$. I used `apply()`, `min()`, `max()`, and `runif()` commands. I compute the estimators $\widehat{\theta}_1$, $\widehat{\theta}_2$, and $\widehat{\theta}_3$ to the artificial datasets, display histograms, and show the means and standard deviations in a table.

```{r}
set.seed(20230519) # for reproducibility, exact results even in a different computer
theta <- 1
nsim <- 10^4 # number of realizations to be obtained
# repeatedly obtain realizations
ymat <- replicate(nsim, runif(5, min = 0, max = theta))
# calculate estimates
theta1hat.5 <- 6*apply(ymat, 2, min)
theta2hat.5 <- 2*colMeans(ymat)
theta3hat.5 <- 6/5*apply(ymat, 2, max)
# put a 1x3 canvas for the case of n=5
par(mfrow=c(1,3))
hist(theta1hat.5, freq = FALSE)
hist(theta2hat.5, freq = FALSE)
hist(theta3hat.5, freq = FALSE)
# n=500
ymat <- replicate(nsim, runif(500, min = 0, max = theta))
# calculate estimates
theta1hat.500 <- 501*apply(ymat, 2, min)
theta2hat.500 <- 2*colMeans(ymat)
theta3hat.500 <- 501/500*apply(ymat, 2, max)
# put a 1x3 canvas for the case of n=500
par(mfrow=c(1,3))
hist(theta1hat.500, freq = FALSE)
hist(theta2hat.500, freq = FALSE)
hist(theta3hat.500, freq = FALSE)
```

|               |          $\widehat{\theta}_1$          |          $\widehat{\theta}_2$          |          $\widehat{\theta}_3$          |
|------------------|:------------------:|:----------------:|:----------------:|
| $n=5$         |                                        |                                        |                                        |
| Mean          |    `r round(mean(theta1hat.5), 2)`     |    `r round(mean(theta2hat.5), 2)`     |    `r round(mean(theta3hat.5), 2)`     |
| SD (times 10) |    `r round(10*sd(theta1hat.5), 2)`    |  `r round(10*sd(theta2hat.5), 2)`  |  `r round(10*sd(theta3hat.5), 2)`  |
| $n=500$       |                                        |                                        |                                        |
| Mean          |   `r round(mean(theta1hat.500), 2)`    |   `r round(mean(theta2hat.500), 2)`    |   `r round(mean(theta3hat.500), 2)`    |
| SD (times 10) | `r round(10*sd(theta1hat.500), 2)` | `r round(10*sd(theta2hat.500), 2)` | `r round(10*sd(theta3hat.500), 2)` |

So, all estimators of $\theta$ are unbiased. The variances of the estimators are:

$$\mathsf{Var}\left(\widehat{\theta}_1\right)=\frac{n}{n+2}\theta^2,\ \mathsf{Var}\left(\widehat{\theta}_2\right) =\frac{1}{3n}\theta^2,\ \mathsf{Var}\left(\widehat{\theta}_3\right)=\frac{1}{n\left(n+2\right)}\theta^2$$ Therefore, we expect the SD of the sampling distributions of the estimators to be $\displaystyle\sqrt{\frac{n}{n+2}}$, $\displaystyle\sqrt{\frac{1}{3n}}$, $\displaystyle\sqrt{\frac{1}{n\left(n+2\right)}}$. The results from the Monte Carlo simulation, which were multiplied by 10 for presentation purposes, match the theoretical results quite well. In particular, we should see results close to `r round(10*sqrt(5/7), 2)`, `r round(10*sqrt(1/15),2)`, and `r round(10*sqrt(1/35),2)` for $n=5$. We should also see results close to `r round(10*sqrt(500/502),2)`, `r round(10*sqrt(1/(3*500)),2)`, and `r round(10*sqrt(1/(500*502)),2)` for $n=500$. 


### How to add mathematics into the document

You can definitely mix text and mathematics. For example:

Let $Y_1,\ldots,Y_n$ be IID $\mathsf{U}\left(0,\theta\right)$, where $\theta>0$. The common pdf of these random variables is given by $$f\left(y\right)=\begin{cases}\dfrac{1}{\theta} & \ \ \ 0\leq y\leq \theta\\ 0 &  \ \ \ \mathrm{otherwise} \end{cases},$$ the common mean is $\theta/2$, and the common variance is $\theta^2/12$. The estimand for this exercise is $\theta$.

You can have single line displayed mathematical expressions:

$$\mathbb{E}\left[\left(\widehat{\theta}-\theta\right)^2\right]=\mathbb{E}\left[\left(\widehat{\theta}-\mathbb{E}\left(\widehat{\theta}\right)\right)^2\right]+\left(\mathbb{E}\left(\widehat{\theta}\right)-\theta\right)^2=\mathsf{Var}\left(\widehat{\theta}\right)+\left(\mathbb{E}\left(\widehat{\theta}\right)-\theta\right)^2.$$

You can have multi-line displayed mathematical expressions:

$$\begin{eqnarray}\mathbb{P}\left(\left|\overline{Y}-\mathbb{E}\left(\overline{Y}\right)\right|\geq \frac{c\sigma}{\sqrt{n}}\right) \leq \frac{\mathsf{Var}\left(\overline{Y}\right)}{c^2\sigma^2/n} &\Rightarrow & \mathbb{P}\left(\left|\frac{\overline{Y}-\mu}{\sigma/\sqrt{n}}\right|\geq c\right) \leq \frac{1}{c^2} \\ &\Rightarrow & \mathbb{P}\left(\left|\frac{\overline{Y}-\mu}{\sigma/\sqrt{n}}\right|\leq c\right) \geq 1-\frac{1}{c^2}.\end{eqnarray}$$

You can mix with lists too:

I collect the following integration results below to tidy up the calculations later.

-   For positive integers $k$, we have $$\int \left(1-\frac{s}{\theta}\right)^k \,\, ds = -\frac{\theta}{k+1}\left(1-\frac{s}{\theta}\right)^{k+1}$$ This result is obtained using integration by substitution.
-   For positive integers $m$ and $k$, we have $$\int s^m\left(1-\frac{s}{\theta}\right)^k \,\, ds = -\frac{\theta s^m}{k+1}\left(1-\frac{s}{\theta}\right)^{k+1}+\frac{m\theta}{k+1} \int s^{m-1}\left(1-\frac{s}{\theta}\right)^{k+1}\,\, ds$$

You can also have tables with mathematics:

| Source     | Sum of squares (SS)                                                                        | Degrees of freedom (df) | Mean sum of squares (MS) | Expected MS       |
|--------------|-----------------|--------------|--------------|--------------|
| Mean       | $V_1^2=n\overline{Y}^2$                                                                    | $1$                     | $n\overline{Y}^2$        | $\sigma^2+n\mu^2$ |
| Deviations | $\displaystyle\sum_{i=2}^n V_i^2=\displaystyle\sum_{i=1}^n\left(Y_i-\overline{Y}\right)^2$ | $n-1$                   | $S^2$                    | $\sigma^2$        |
| Total      | $\displaystyle\sum_{i=1}^n V_i^2=\displaystyle\sum_{i=1}^n Y_i^2$                          | $n$                     |                          |                   |

### How to add and cite references

Notice that in the qmd file there is a line `bibliography: references.bib`. What this means is that there is a separate file containing bibliographic information. Your job is to maintain this `bib` file and populate it with entries which you will be eventually citing in your report. The format of the entries is the BibTeX format.

Fortunately, almost every publisher of journal articles has citation tools that make things convenient. For example, when you look up the citation information of @HAMERMESH2005369 at [this website](https://www.sciencedirect.com/science/article/abs/pii/S0272775704001165?via%3Dihub), you will can click on Cite and find Export citation to BibTeX. Sometimes a file will open in your browser, but most of the time a very small file with a `.bib` or a `.txt` file extension will be downloaded. Open this file using a text editor and copy/paste the contents to `references.bib`. Sometimes it might be a good idea to clean up the contents to make it shorter, but still containing the most important pieces of information including the digital object identifier or DOI.[^1] For other publishers, your mileage may vary. I leave this for you to explore. But you got to admit that this gives everyone no excuse for not citing sources.

[^1]: There is a slight problem with some publisher when they export citations to BibTeX. The DOI entry has to modified so that you remove the first part `https://doi.org/`.

If you use R packages that were never used in class, please cite them. For example, if you want to cite the `multcomp` package, then you type `print(citation("sandwich"), bibtex=TRUE)` into the R console. It will generate a BibTeX entry. Put that entry into `references.bib`. Do not forget to put a key. Usually these keys are provided or automatically generated. These keys are markers or identifiers which enable you to tie your citation in the qmd file to the entry in `references.bib`. If this key is not provided or if you want to modify it, you can find it in the first line of every BibTeX entry. This first line typically starts with something like `@Manual{Rcite,` and for this example, `Rcite` is the key.

Open the qmd file which produced this HTML file so that you can see how to cite sources and how the keys play a role.

For reproducibility purposes, I would include something like "All analyses were performed using R Statistical Software v4.2.1 [@Rcite] and tables are displayed using `stargazer` v5.2.3 [@starcite].

Look at the bottom: Instant reference list!

### If you are using IPUMS

If you choose this project option, you may need to install and load the `ipumsr` package. The purpose of the package is to help you load an IPUMS dataset and to use its built-in commands to help you navigate the data. This may take some time to learn. 

The code chunk below is not evaluated in Quarto because of `eval: false`, but this can be removed. 

```{r}
#| eval: false
if (!require("ipumsr")) stop("Reading IPUMS data into R requires the ipumsr package. It can be installed using the following command: install.packages('ipumsr')")
```

Here I use some commands in `ipumsr` to load the data: 

```{r}
#| eval: false
# Download the XML file from IPUMS and use it to load the definitions of the variables
ddi <- read_ipums_ddi("usa_00008.xml")
# Load the data based on the previous command
data <- read_ipums_micro(ddi)
```

Here I create a variable `age.arrival` which may be interesting and I create a subset of the data that I have loaded previously. 

```{r}
#| eval: false
# Calculate age at arrival
data$age.arrival <- data$YRIMMIG - data$BIRTHYR
# born in Mexico, household head, living in California, married with spouse present, and white
filtered <- subset(data, BPL == 200 & RELATE == 1 & STATEFIP == 6 & MARST == 1 & RACE == 1)
# total number of observations used
nrow(filtered)
# show distribution of age at arrival
table(filtered$age.arrival)
# show distribution for males and females
table(filtered$age.arrival, filtered$SEX)
```

The previous code chunk were left unevaluated. To be able to evaluate these code chunks, you have to remove the line `#| eval: false` and you need access to the XML file `usa00008.xml` and the data file `usa00008.dat.gz`. 

## Preamble

Here you can organize the commands needed to load packages and do other formatting options (if needed).

```{r}
# To clean R's memory, leave this alone
rm(list=ls())
```

## Introduction and motivation

Here you explain why you have selected the chosen project option. Describe the problem(s) and research question(s) related to your chosen project option. Why do you think the problem(s) and the question(s) are important? What do you think is gained by addressing the problem(s) and/or answering the research question(s)? It is important to express into your own words, your own thoughts, and most preferably your own selected context.

### Plan 

Here you have to discuss what you plan to do for your report. Again, aim for something in between "a simple project done very well" and "a complicated project with flaws". 

### Progress

## Main body

Adjust the title to suit your situation. Your chosen project option will eventually determine what will be in this main body. Feel free to use subsections. 

## Summary

Summarize what you have done here and what you hope you could have done if you had more time. 