---
title: "Lab 11: Inference for Proportion and Mean"
author: "Insert Name"
output:
  pdf_document
 
---

# Due: 12am night before lab

# Instructions
Work through the problems below, and submit this document as a knitted .pdf file with answers to the Problem Set 1 assignment on Gradescope. 


**For each problem, put your solution between the bars of red stars.**


```{r, include=FALSE}
# Do not edit this code block/chunk
knitr::opts_chunk$set(echo = TRUE, message=FALSE, warning = FALSE, fig.width = 5, fig.height = 3)
```

### Load packages

For this lab we will read be using the `tidyverse` for data wrangling and visualization and `oilabs` for the data set. `infer` is included as well, in case you decide to use it.

```{r, include=FALSE, message = FALSE, warning = FALSE}
library(tidyverse)
library(knitr)
library(oilabs)
library(infer)
library(openintro)
```

# Background 

In August of 2012, news outlets ranging from the [Washington Post](http://www.washingtonpost.com/national/on-faith/poll-shows-atheism-on-the-rise-in-the-us/2012/08/13/90020fd6-e57d-11e1-9739-eef99c5fb285_story.html) to the [Huffington Post](http://www.huffingtonpost.com/2012/08/14/atheism-rise-religiosity-decline-in-america_n_1777031.html) ran a story about the rise of atheism in America. The source for the story was a poll that asked people, “Irrespective of whether you attend a place of worship or not, would you say you are a religious person, not a religious person or a convinced atheist?” This type of question, which asks people to classify themselves in one way or another, is common in polling and generates categorical data. In this lab we take a look at the atheism survey and explore what's at play when making inference about population proportions using categorical data.

## The survey

The press release for the poll, conducted by WIN-Gallup International, can be accessed
[here](https://www.webpages.uidaho.edu/~stevel/251/Global_INDEX_of_Religiosity_and_Atheism_PR__6.pdf).

Take a moment to review the report then address the following questions.


### Exercise 1

In the first paragraph, several key findings are reported. Do these percentages appear to be *sample statistics* (derived from the data sample) or *population parameters*? Explain your reasoning.
    
**************************************************

**************************************************

### Exercise 2

The title of the report is “Global Index of Religiosity and Atheism”. To generalize the report's findings to the global human population, what must we assume about the sampling method? Does that seem like a reasonable assumption?
    
**************************************************

**************************************************

## The data

Turn your attention to Table 6 (pages 14 and 15), which reports the sample size and response percentages for all 57 countries. While this is a useful format to summarize the data, we will base our analysis on the original data set of individual responses to the survey. Load this data set into R with the following command.

```{r }
data(atheism)
```


### Exercise 3

What does each row of Table 6 correspond to? What does each row of `atheism` correspond to?

**************************************************

**************************************************

To investigate the link between these two ways of organizing this data, take a look at the estimated proportion of atheists in the United States. Towards the bottom of Table 6, we see that this is 5%. We should be able to come to the same number using the `atheism` data.

### Exercise 4

Using the code below, create a new dataframe called `us12` that contains only the rows in `atheism` associated with respondents to the 2012 survey from the United States. Next, calculate the proportion of atheist responses. Does it agree with the percentage in Table 6? If not, why?
    
```{r}
us12 <- atheism %>%
  filter(nationality == "United States", year == "2012")
```

**************************************************

**************************************************

 



## Inference on proportions

As was hinted earlier, Table 6 provides *statistics*, that is, calculations made from the sample of 51,927 people. What we'd like, though, is insight into the population *parameters*. You answer the question, “What proportion of people in your sample reported being atheists?” with a statistic; while the question “What proportion of people on earth would report being atheists” is answered with an estimate of the parameter.



Religion scholars thought that the proportion of atheists in the United States was 3\% of the population. You will perform a hypothesis test to determine if this assumption and your observation are consistent.

### Exercise 5
Write out the conditions for inference using the Normal approximation to perform a hypothesis test for the proportion of atheists in the United States in 2012. Are you confident all conditions are met?
    
**************************************************

**************************************************

Although formal confidence intervals and hypothesis tests don't show up in the report, suggestions of inference appear at the bottom of page 6: “In general, the error margin for surveys of this kind is \(\pm\) 3-5% at 95% confidence”.

### Exercise 6

Write out the null and alternative hypotheses.

**************************************************

**************************************************

### Exercise 7

Using the Normal approximation method, calculate a z-score and then a p-value.  What do you conclude about your hypotheses.

**************************************************

**************************************************

### Exercise 8

Perform the hypothesis test using `infer`.  How does this result compare with the Normal approximation
result.

**************************************************

**************************************************



## How does the proportion affect the margin of error?

Imagine you've set out to survey 1000 people on two questions: Do you have brown eyes? Are you left-handed? Since both of these sample proportions were calculated from the same sample size, they should have the same margin of error, right? Nope\! While the margin of error does change with sample size, it is also affected by the proportion.

Think back to the formula for the standard error:
$$SE = \sqrt{\frac{p(1-p)}{n}}$$
This is then used in the formula for the margin of error for a 95% confidence interval:
$$ME = 1.96\cdot SE = 1.96\cdot \sqrt{\frac{p(1-p)}{n}}$$
Since the population proportion $p$ is in this $ME$ formula, it should make sense that the margin of error is in some way dependent on the population proportion. We can visualize this relationship by creating a plot of $ME$ vs. $p$.

Since sample size is irrelevant to this discussion, let's just set it to some value ($n = 1000$) and use this value in the following calculations:

```{r}
n <- 1000
```

The first step is to make a variable `p` that is a sequence from 0 to 1 with each number incremented by 0.01. We can then create a vector of the margin of error (`me`) associated with each of these values of `p` using the familiar approximate formula ($ME = 2 \times SE$).

```{r}
p <- seq(0, 1, 0.01)
me <- 2 * sqrt(p * (1 - p)/n)
```

Lastly, we combine these vectors into a dataframe so that we can visualize it either using `geom_point()` or `geom_line()` (or both\!).

```{r}
dd <- data.frame(p = p, me = me)
```

### Exercise 9
Use ggplot to plot the relationship between `p` and `me` and describe it in words. For a given sample size, for which value of `p` is margin of error maximized?

**************************************************

**************************************************

## Success-failure condition

We emphasized that you must always check conditions before making inference. For inference on proportions, the sample proportion can be assumed to be nearly normal if it is based upon a random sample of independent observations and if both $np \geq 10$ and $n(1 - p) \geq 10$. This rule of thumb is easy enough to follow, but it makes one wonder: what's so special about the number 10?

The short answer is: nothing. You could argue that we would be fine with 9 or that we really should be using 11. What is the “best” value for such a rule of thumb is, at least to some degree, arbitrary. However, when $np$ and $n(1-p)$ reaches 10 the sampling distribution is sufficiently normal to use confidence intervals and hypothesis tests that are based on that approximation.

We can investigate the interplay between $n$ and $p$ and the shape of the sampling distribution by using simulations. Play around with the following app to investigate how the shape, center, and spread of the distribution of $\hat{p}$ changes as $n$ and $p$ changes.

Link to app:
<https://ismay.shinyapps.io/shinyDist/>

### Exercise 10

Describe the sampling distribution of sample proportions at $n = 300$ and $p = 0.1$. Be sure to note the center, spread, and shape.
    
**************************************************

**************************************************


### Exercise 11

Keep $n$ constant and change $p$. How does the shape, center, and spread of the sampling distribution vary as $p$ changes. You might want to adjust min and max for the x-axis for a better view of the distribution.

**************************************************

**************************************************

### Exercise 12

Now also change $n$.How does $n$ appear to affect the distribution of $\hat{p}$?

**************************************************

**************************************************


### Exercise 13

Find the sample proportion of atheists in Canada in 2012. Then perform a hypothesis test to determine whether the true proportion of atheists in Canada and in the United States differed in 2012. Use the Normal Approximation method.

*********************************************************************************

*********************************************************************************

## Inference with Single Mean

### The data

Every two years, the Centers for Disease Control and Prevention conduct the Youth Risk Behavior Surveillance System (YRBSS) survey, where it takes data from high schoolers (9th through 12th grade), to analyze health patterns. You will work with a selected group of variables from a random sample of observations during one of the years the YRBSS was conducted.

```{r}
data(yrbss)
```

There are observations on 13 different variables, some categorical and some numerical. The meaning of each variable can be found by bringing up the help file:

```{r}
?yrbss
```

Note that about 1000 observations in the `yrbss` dataset have an NA value for height. Run the following code to drop these observations.

```{r}
yrbss <- yrbss %>% drop_na(height)
```


Calculate a 95% confidence interval for the average height in meters (`height`) and interpret it in context.  

## Exercise 14

Using the Normal Approximation.

**********************************************************************

**********************************************************************
    

### Exercise 15   

Using `infer` and the bootstrapping method with `type = "se"`.  How does it compare with the confidence interval calculated using the normal approximation?  
    
**********************************************************************

**********************************************************************



