Getting Started

Load packages

In this lab, we will explore and visualize the data using the tidyverse suite of packages, and perform statistical inference using infer. The data can be found in the companion package for OpenIntro resources, openintro.

Let’s load the packages.

library(tidyverse)
library(openintro)
library(infer)
library(kableExtra)
library(dplyr)

The Data

You will be analyzing the same dataset as in the previous lab, where you delved into a sample from the Youth Risk Behavior Surveillance System (YRBSS) survey, which uses data from high schoolers to help discover health patterns. The dataset is called yrbss.

  1. What are the counts within each category for the amount of days these students have texted while driving within the past 30 days?
kable(table(yrbss$text_while_driving_30d))
Var1 Freq
0 4792
1-2 925
10-19 373
20-29 298
3-5 493
30 827
6-9 311
did not drive 4646

The results are provided above in the table.

  1. What is the proportion of people who have texted while driving every day in the past 30 days and never wear helmets?
no_helmet <- yrbss |> filter(helmet_12m == "never")
no_helmet <- no_helmet |> mutate(text_ind = ifelse(text_while_driving_30d == "30", "yes", "no"))

no_helmet %>%
  group_by(text_ind) %>%
  summarize(count = n()) %>%
  mutate(proportion = count / sum(count))
## # A tibble: 3 × 3
##   text_ind count proportion
##   <chr>    <int>      <dbl>
## 1 no        6040     0.866 
## 2 yes        463     0.0664
## 3 <NA>       474     0.0679

The proportion is provided in the results above. Of the people reporting that they do not wear helmets, 6.64% also report they have texted while driving every day in the past 30 days.

Remember that you can use filter to limit the dataset to just non-helmet wearers. Here, we will name the dataset no_helmet.

data('yrbss', package='openintro')
no_helmet <- yrbss %>%
  filter(helmet_12m == "never")

Also, it may be easier to calculate the proportion if you create a new variable that specifies whether the individual has texted every day while driving over the past 30 days or not. We will call this variable text_ind.

no_helmet <- no_helmet %>%
  mutate(text_ind = ifelse(text_while_driving_30d == "30", "yes", "no"))

Inference on proportions

When summarizing the YRBSS, the Centers for Disease Control and Prevention seeks insight into the population parameters. To do this, you can answer the question, “What proportion of people in your sample reported that they have texted while driving each day for the past 30 days?” with a statistic; while the question “What proportion of people on earth have texted while driving each day for the past 30 days?” is answered with an estimate of the parameter.

The inferential tools for estimating population proportion are analogous to those used for means in the last chapter: the confidence interval and the hypothesis test.

no_helmet %>%
  drop_na(text_ind) %>% # Drop missing values
  specify(response = text_ind, 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.0649   0.0775

Note that since the goal is to construct an interval estimate for a proportion, it’s necessary to both include the success argument within specify, which accounts for the proportion of non-helmet wearers than have consistently texted while driving the past 30 days, in this example, and that stat within calculate is here “prop”, signaling that you are trying to do some sort of inference on a proportion.

  1. What is the margin of error for the estimate of the proportion of non-helmet wearers that have texted while driving each day for the past 30 days based on this survey?

The margin of error is typically reported as a percentage of the sample proportion or mean, but we can also report it has numerical numbers. So, in this case, the MOE is the width of the CI/2, or 0.0061. This gives us a sample mean of 0.0716 +/- 0.0061 or 8.5%

  1. Using the infer package, calculate confidence intervals for two other categorical variables (you’ll need to decide which level to call “success”, and report the associated margins of error. Interpet the interval in context of the data. It may be helpful to create new data sets for each of the two countries first, and then use these data sets to construct the confidence intervals.
gender_sleep_female <- yrbss |> filter(gender=="female") |> mutate(text_ind2 = ifelse( school_night_hours_sleep == "8", "yes", "no"))
gender_sleep_female %>%
  drop_na(text_ind2) %>% # Drop missing values
  specify(response = text_ind2, 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.192    0.213
gender_tv_male <- yrbss |> filter(gender=="male") |> mutate(text_ind3 = ifelse(hours_tv_per_school_day == "5+", "yes", "no"))
gender_tv_male %>%
  drop_na(text_ind3) %>% # Drop missing values
  specify(response = text_ind3, 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.111    0.126

For this question, we chose to look at the proportion of all females getting 8 hours a sleep, and the proportion of all males watching 5+ hours of television. We are 95% confident that the population proportion of females getting 8 hours per night of sleep is within the interval of 0.202 +/- .01 or +/- 4.95%. We are also 95% confident that the population proportion of males watching 5+ hours of television per day is within the interval of 0.1185 +/- .0075 or +/- 6.32%

How does the proportion affect the margin of error?

Imagine you’ve set out to survey 1000 people on two questions: are you at least 6-feet tall? and 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? Wrong! 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{p(1-p)/n}\). This is then used in the formula for the margin of error for a 95% confidence interval:

\[ ME = 1.96\times SE = 1.96\times\sqrt{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:

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. You can then create a variable of the margin of error (me) associated with each of these values of p using the familiar approximate formula (\(ME = 2 \times SE\)).

p <- seq(from = 0, to = 1, by = 0.01)
me <- 2 * sqrt(p * (1 - p)/n)

Lastly, you can plot the two variables against each other to reveal their relationship. To do so, we need to first put these variables in a data frame that you can call in the ggplot function.

dd <- data.frame(p = p, me = me)
ggplot(data = dd, aes(x = p, y = me)) + 
  geom_line() +
  labs(x = "Population Proportion", y = "Margin of Error")

  1. Describe the relationship between p and me. Include the margin of error vs. population proportion plot you constructed in your answer. For a given sample size, for which value of p is margin of error maximized?

As population proportion increases or decreases from 50%, the MOE will also decrease. The function has a maximum at a population of 50% or 0.5. It then decreases from that maximum either going up or down, and so does th margin of error.

Success-failure condition

We have 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 you wonder: what’s so special about the number 10?

The short answer is: nothing. You could argue that you would be fine with 9 or that you 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.

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

  1. Describe the sampling distribution of sample proportions at \(n = 300\) and \(p = 0.1\). Be sure to note the center, spread, and shape.

The plot appears mostly normal, with a large peak near 0.1. However there does also appear to have some slight right hand skewing. The spread appears to be from about 0.06 to about 0.17. This sampling curve is very steep and narrow.

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

As we get to 0.5, the plot appears much more normal than for the 0.1 p, but now wider and less high. The spread now expands from about 0.375 to 0.625. As we then move toward a population proportion of 1, the curve then starts to narrow again and the spread gets smaller.

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

As long as n is relatively large, say > 300, there seems to be very little change to the shape and width of the plot. That is because when we start getting n’s that large in the denominator, each factor increase in n does not have much effect on the overall denominator and effectively p(1-p) trends toward the smallest value.


More Practice

For some of the exercises below, you will conduct inference comparing two proportions. In such cases, you have a response variable that is categorical, and an explanatory variable that is also categorical, and you are comparing the proportions of success of the response variable across the levels of the explanatory variable. This means that when using infer, you need to include both variables within specify.

  1. Is there convincing evidence that those who sleep 10+ hours per day are more likely to strength train every day of the week? As always, write out the hypotheses for any tests you conduct and outline the status of the conditions for inference. If you find a significant difference, also quantify this difference with a confidence interval.
Sleep_ten_hours <- yrbss |> filter(school_night_hours_sleep=="10+") |> mutate(text_ind3 = ifelse(strength_training_7d=="7", "yes", "no"))

Sleep_ten_hours %>%
  drop_na(text_ind3) %>% # Drop missing values
  specify(response = text_ind3, 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.221    0.317

H0: People sleeping 10+ hours a day are not more likely to strength train every day of the week (7 days). HA: People sleeping 10+ hours a day are more likely to strength train every day of the week. for the purposes of this question, we need to determine whether the sample proportion of those strength training 7 days a week would be greater than 50% of the population, and the confidence interval of 95% would not include the population of 0.5. For this result we have a population estimate of 0.273 +/- .052. Since this results is much less than 0.5, and the confidence interval does not include 0.5, we can conclude that with 95% confidence that the population proportion is within the CI(0.221,0.324) and that we must accept the null hypothesis that People sleeping 10+ hours a day are not more likely to strength train every day of the week (7 days).

  1. Let’s say there has been no difference in likeliness to strength train every day of the week for those who sleep 10+ hours. What is the probablity that you could detect a change (at a significance level of 0.05) simply by chance? Hint: Review the definition of the Type 1 error.

A type 1 error is when we see something that is in reality not there, or a false positive. That is we reject the null hypothesis when it is actually true. When we select an alpha=0.05, that is the probability of a Type I error. This means there is a a 0.5 or 5% chance of incorrectly concluding there is a difference in the likeliness to strength train every day of the week for those who sleep 10+ hours per day.

  1. Suppose you’re hired by the local government to estimate the proportion of residents that attend a religious service on a weekly basis. According to the guidelines, the estimate must have a margin of error no greater than 1% with 95% confidence. You have no idea what to expect for \(p\). How many people would you have to sample to ensure that you are within the guidelines?
    Hint: Refer to your plot of the relationship between \(p\) and margin of error. This question does not require using a dataset.

For an unknown population, the maximum margin of error would occur at 50/50. So, we should assume that would be the worst case scenario for the population proportion. Therefore, we can work backwards using the MOE formula, but in this case we use: \[ ME =0.01 = 1.96\times SE = 1.96\times\sqrt{p(1-p)/n} \,. \] \[ 0.01/1.96 = \sqrt{p(1-p)/n} \,. \] \[ 0.0001/3.842 = 0.5(0.5)/n = 0.25/n \] \[ n = (0.25)(3.842)/0.0001 = 0.9605/0.0001 = 9605 \] So we would need to sample at least 9605 residents to stay within the 1% margin of error with 95% confidence. * * *