If you have access to data on an entire population, say the opinion of every adult in the United States on whether or not they think climate change is affecting their local community, it’s straightforward to answer questions like, “What percent of US adults think climate change is affecting their local community?”. Similarly, if you had demographic information on the population you could examine how, if at all, this opinion varies among young and old adults and adults with different leanings. If you have access to only a sample of the population, as is often the case, the task becomes more complicated. What is your best guess for this proportion if you only have data from a small sample of adults? This type of situation requires that you use your sample to make inference on what your population looks like.
Setting a seed: You will take random samples and build sampling distributions in this lab, which means you should set a seed on top of your lab. If this concept is new to you, review the lab on probability.
In this lab, we will explore and visualize the data using the tidyverse suite of packages, and perform statistical inference using infer.
Let’s load the packages.
A 2019 Pew Research report states the following:
To keep our computation simple, we will assume a total population size of 100,000 (even though that’s smaller than the population size of all US adults).
Roughly six-in-ten U.S. adults (62%) say climate change is currently affecting their local community either a great deal or some, according to a new Pew Research Center survey.
Source: Most Americans say climate change impacts their community, but effects vary by region
In this lab, you will assume this 62% is a true population proportion and learn about how sample proportions can vary from sample to sample by taking smaller samples from the population. We will first create our population assuming a population size of 100,000. This means 62,000 (62%) of the adult population think climate change impacts their community, and the remaining 38,000 does not think so.
The name of the data frame is us_adults
and the name of
the variable that contains responses to the question “Do you think
climate change is affecting your local community?” is
climate_change_affects
.
We can quickly visualize the distribution of these responses using a bar plot.
ggplot(us_adults, aes(x = climate_change_affects)) +
geom_bar() +
labs(
x = "", y = "",
title = "Do you think climate change is affecting your local community?"
) +
coord_flip()
We can also obtain summary statistics to confirm we constructed the data frame correctly.
## # A tibble: 2 × 3
## climate_change_affects n p
## <chr> <int> <dbl>
## 1 No 38000 0.38
## 2 Yes 62000 0.62
In this lab, you’ll start with a simple random sample of size 60 from the population.
Insert your answer here
## # A tibble: 2 × 3
## climate_change_affects n p
## <chr> <int> <dbl>
## 1 No 21 0.35
## 2 Yes 39 0.65
Insert your answer here
Return for a moment to the question that first motivated this lab:
based on this sample, what can you infer about the population? With just
one sample, the best estimate of the proportion of US adults who think
climate change affects their local community would be the sample
proportion, usually denoted as \(\hat{p}\) (here we are calling it
p_hat
). That serves as a good point
estimate, but it would be useful to also communicate how
uncertain you are of that estimate. This uncertainty can be quantified
using a confidence interval.
One way of calculating a confidence interval for a population proportion is based on the Central Limit Theorem, as \(\hat{p} \pm z^\star SE_{\hat{p}}\) is, or more precisely, as \[ \hat{p} \pm z^\star \sqrt{ \frac{\hat{p} (1-\hat{p})}{n} } \]
Another way is using simulation, or to be more specific, using bootstrapping. The term bootstrapping comes from the phrase “pulling oneself up by one’s bootstraps”, which is a metaphor for accomplishing an impossible task without any outside help. In this case the impossible task is estimating a population parameter (the unknown population proportion), and we’ll accomplish it using data from only the given sample. Note that this notion of saying something about a population parameter using only information from an observed sample is the crux of statistical inference, it is not limited to bootstrapping.
In essence, bootstrapping assumes that there are more of observations in the populations like the ones in the observed sample. So we “reconstruct” the population by resampling from our sample, with replacement. The bootstrapping scheme is as follows:
Instead of coding up each of these steps, we will construct confidence intervals using the infer package.
Below is an overview of the functions we will use to construct this confidence interval:
Function | Purpose |
---|---|
specify |
Identify your variable of interest |
generate |
The number of samples you want to generate |
calculate |
The sample statistic you want to do inference with, or you can also think of this as the population parameter you want to do inference for |
get_ci |
Find the confidence interval |
This code will find the 95 percent confidence interval for proportion of US adults who think climate change affects their local community.
samp %>%
specify(response = climate_change_affects, success = "Yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)
## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.517 0.767
specify
we specify the response
variable and the level of that variable we are calling a
success
.generate
we provide the number of resamples we want
from the population in the reps
argument (this should be a
reasonably large number) as well as the type of resampling we want to
do, which is "bootstrap"
in the case of constructing a
confidence interval.calculate
the sample statistic of interest for
each of these resamples, which is prop
ortion.Feel free to test out the rest of the arguments for these functions, since these commands will be used together to calculate confidence intervals and solve inference problems for the rest of the semester. But we will also walk you through more examples in future chapters.
To recap: even though we don’t know what the full population looks like, we’re 95% confident that the true proportion of US adults who think climate change affects their local community is between the two bounds reported as result of this pipeline.
Insert your answer here
In this case, you have the rare luxury of knowing the true population proportion (62%) since you have data on the entire population.
Insert your answer here
Insert your answer here
In the next part of the lab, you will collect many samples to learn more about how sample proportions and confidence intervals constructed based on those samples vary from one sample to another.
Doing this would require learning programming concepts like iteration so that you can automate repeating running the code you’ve developed so far many times to obtain many (50) confidence intervals. In order to keep the programming simpler, we are providing the interactive app below that basically does this for you and created a plot similar to Figure 5.6 on OpenIntro Statistics, 4th Edition (page 182).
Insert your answer here
# Sample
n <- 60
samp2 <- us_adults %>%
sample_n(size = n)
samp2 %>%
specify(response = climate_change_affects, success = "Yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)
## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.55 0.783
# Ranges from lower_ci to upper_ci include the true proportion 95% of time
ggplot(samp2, aes(x = climate_change_affects)) +
geom_bar() +
labs(
x = "", y = "",
title = "Do you think climate change is affecting your local community? (Sample 2)"
) +
coord_flip() +
geom_text(aes(label = after_stat(count)), stat = "count", hjust = 3, colour = "black")
* * * |
## More Practice |
7. Choose a different confidence level than 95%. Would you expect a confidence interval at this level to be wider or narrower than the confidence interval you calculated at the 95% confidence level? Explain your reasoning. |
Insert your answer here |
r samp2 %>% specify(response = climate_change_affects, success = "Yes") %>% generate(reps = 50, type = "bootstrap") %>% calculate(stat = "prop") %>% get_ci(level = 0.95) |
## # A tibble: 1 × 2 ## lower_ci upper_ci ## <dbl> <dbl> ## 1 0.587 0.833 |
```r # 0.554 to 0.783 |
samp2 %>% specify(response = climate_change_affects, success = “Yes”) %>% generate(reps = 50, type = “bootstrap”) %>% calculate(stat = “prop”) %>% get_ci(level = 0.5) ``` |
## # A tibble: 1 × 2 ## lower_ci upper_ci ## <dbl> <dbl> ## 1 0.633 0.717 |
```r # 0.633 to 0.712 |
samp2 %>% specify(response = climate_change_affects, success = “Yes”) %>% generate(reps = 50, type = “bootstrap”) %>% calculate(stat = “prop”) %>% get_ci(level = 0.1) ``` |
## # A tibble: 1 × 2 ## lower_ci upper_ci ## <dbl> <dbl> ## 1 0.65 0.667 |
r # 0.633 to 0.712 |
###### If I choose a lower confidence interval, then I would expect the range from the lower to upper ci’s to be narrower. As the range decreases, so does the likelihood of the true proportion to lie within the confines of those ranges. The lower our confidence interval, the closer we get to the true p_hat. Remember that we’re pulling 50 different intervals here, so lowering our confidence level means more of them will not contain p_hat, which we can see with the interactive shiny app above. |
samp
), find a confidence interval for
the proportion of US Adults who think climate change is affecting their
local community with a confidence level of your choosing (other than
95%) and interpret it.Insert your answer here
samp %>%
specify(response = climate_change_affects, success = "Yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.33)
## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.617 0.683
## # A tibble: 2 × 3
## climate_change_affects n p
## <chr> <int> <dbl>
## 1 No 21 0.35
## 2 Yes 39 0.65
Insert your answer here
# For a 95% ci, qnorm(0.95 / 2) = qnorm((1 - 0.95)/2) = qnorm(0.025) = -1.959964 because of symmetry.
# Remember we need to consider the two tails, 2.5% to the left, 2.5% to the right, Divide by 2 for left and right tail.
# For a 95% confidence interval, critical value = 1.96 (https://fall2023.data606.net/slides/05-Foundation_for_Inference.pdf)
true_prop <- 0.62
num_intervals <- 50
# Let's use ci = 0.33
my_ci <- 0.33
crit_value <- abs(qnorm((1 - my_ci)/2))
# Gives us critical value of 0.426148
# Create an empty frame for our plot
ci <- data.frame(mean = numeric(num_intervals), min = numeric(num_intervals), max = numeric(num_intervals))
for (i in seq_len(num_intervals)) {
samp_i <- sample(us_adults$climate_change_affects == "Yes", size = num_intervals, replace = TRUE)
se <- sd(samp_i) / sqrt(length(samp_i)) # standard error
# se = sqrt(p_hat * (1 - p_hat)/ n) is more accurate where p_hat = n /sum(n) but are basically the same
ci[i,] <- c(mean(samp_i), # Adding elements to the empty frame
mean(samp_i) - crit_value * se,
mean(samp_i) + crit_value * se)
}
ci$sample <- 1:nrow(ci)
ci$sig <- ci$min < true_prop & ci$max > true_prop #Adding the True False to see if the ci's contain the true proportion 0.62
# Plot all the confidence intervals using the dataframe we just made
ggplot(ci, aes(x=min, xend= max, y=sample, yend=sample, color= sig)) +
geom_vline(xintercept = true_prop) +
geom_segment() + xlab('CI') + ylab('') +
scale_color_manual(values = c('TRUE' = 'blue', 'FALSE' = 'red'))
samp
and
interpret it. Finally, use the app to generate many intervals and
calculate the proportion of intervals that capture the true population
proportion.Insert your answer here
true_prop <- 0.62
num_intervals <- 50
# Let's use ci = 0.85
my_ci2 <- 0.85
crit_value2 <- abs(qnorm((1 - my_ci2)/2))
# Create an empty frame for our plot
ci2 <- data.frame(mean = numeric(num_intervals), min = numeric(num_intervals), max = numeric(num_intervals))
for (i in seq_len(num_intervals)) {
samp_i2 <- sample(us_adults$climate_change_affects == "Yes", size = num_intervals, replace = TRUE)
se2 <- sd(samp_i2) / sqrt(length(samp_i2)) # standard error
# se = sqrt(p_hat * (1 - p_hat)/ n) is more accurate where p_hat = n /sum(n) but are basically the same
ci2[i,] <- c(mean(samp_i2), # Adding elements to the empty frame
mean(samp_i2) - crit_value2 * se2,
mean(samp_i2) + crit_value2 * se2)
}
ci2$sample <- 1:nrow(ci2)
ci2$sig <- ci2$min < true_prop & ci2$max > true_prop #Adding the True False to see if the ci's contain the true proportion 0.62
# Plot all the confidence intervals using the dataframe we just made
ggplot(ci2, aes(x=min, xend= max, y=sample, yend=sample, color= sig)) +
geom_vline(xintercept = true_prop) +
geom_segment() + xlab('CI') + ylab('') +
scale_color_manual(values = c('TRUE' = 'blue', 'FALSE' = 'red'))
11. Using the app, experiment with different sample sizes and comment on how the widths of intervals change as sample size changes (increases and decreases). |
Insert your answer here |
###### I started with a sample size of 50, at 1000 resamples and 95% confidence level. As the sample size increases, the width of the interval shrinks, meaning we’re having a smaller confidence interval cenetered around the true proportion . As the sample size decreases, the width of our interval is wider because the upper and lower values are more uncertain. |
Insert your answer here