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)
set.seed(500)
data("yrbss")

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.

yrbss<-drop_na(yrbss)
yrbss
## # A tibble: 8,351 × 13
##      age gender grade hispanic race        height weight helme…¹ text_…² physi…³
##    <int> <chr>  <chr> <chr>    <chr>        <dbl>  <dbl> <chr>   <chr>     <int>
##  1    15 female 9     hispanic Native Haw…   1.73   84.4 never   30            7
##  2    15 female 9     not      Black or A…   1.6    55.8 never   0             0
##  3    15 female 9     not      Black or A…   1.5    46.7 did no… did no…       2
##  4    15 female 9     not      Black or A…   1.57   67.1 did no… did no…       1
##  5    15 female 9     not      Black or A…   1.68   69.8 did no… 0             0
##  6    15 female 9     not      Black or A…   1.65   66.7 did no… did no…       0
##  7    16 male   9     not      Black or A…   1.68   74.8 never   0             7
##  8    16 male   9     not      Black or A…   1.85   74.4 did no… did no…       7
##  9    15 male   9     not      Black or A…   1.78   70.3 did no… 0             7
## 10    14 male   9     not      Black or A…   1.73   73.5 never   did no…       4
## # … with 8,341 more rows, 3 more variables: hours_tv_per_school_day <chr>,
## #   strength_training_7d <int>, school_night_hours_sleep <chr>, and abbreviated
## #   variable names ¹​helmet_12m, ²​text_while_driving_30d, ³​physically_active_7d
  1. What are the counts within each category for the amount of days these students have texted while driving within the past 30 days?
countEachCategory <- yrbss %>% count(text_while_driving_30d)
countEachCategory
## # A tibble: 8 × 2
##   text_while_driving_30d     n
##   <chr>                  <int>
## 1 0                       3137
## 2 1-2                      658
## 3 10-19                    281
## 4 20-29                    224
## 5 3-5                      347
## 6 30                       583
## 7 6-9                      230
## 8 did not drive           2891
sum(countEachCategory$n)
## [1] 8351
  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 %>% count(text_ind)
## # A tibble: 2 × 2
##   text_ind     n
##   <chr>    <int>
## 1 no        4012
## 2 yes        332

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

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.

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.

According to the University of Southampton: "A 99% confidence interval will allow you to be more confident that the true value in the population is represented in the interval. However, it gives a wider interval than a 95% confidence interval. For most analyses, it is acceptable to use a 95% confidence interval to extend your results to the general population."

no_helmet %>%
  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.0686   0.0845

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?

     no_helmet %>%
     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.0684   0.0843

    Margin of error=z times sqrt(sigma^{2}/{n}) n = sample size; σ = population standard deviation; z = z-score

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

yrbss %>%
  count(physically_active_7d, sort=TRUE)
## # A tibble: 8 × 2
##   physically_active_7d     n
##                  <int> <int>
## 1                    7  2303
## 2                    0  1314
## 3                    5  1107
## 4                    3   927
## 5                    4   813
## 6                    2   771
## 7                    1   571
## 8                    6   545
yrbss %>%
  count(school_night_hours_sleep, sort=TRUE)
## # A tibble: 7 × 2
##   school_night_hours_sleep     n
##   <chr>                    <int>
## 1 7                         2417
## 2 6                         1845
## 3 8                         1799
## 4 5                         1023
## 5 <5                         597
## 6 9                          496
## 7 10+                        174
exercise_time<- yrbss %>%
  filter(!is.na(physically_active_7d)) %>%
  mutate(exercise_everyday = ifelse(physically_active_7d <"1", "yes", "no"))

exercise_time %>%
  count(exercise_everyday)
## # A tibble: 2 × 2
##   exercise_everyday     n
##   <chr>             <int>
## 1 no                 7037
## 2 yes                1314
exercise_time %>%
 specify(response = exercise_everyday, 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.150    0.165
n <- nrow(exercise_time)
z <- 1.96
p <- seq(from = 0, to = 1, by = 0.01)
se <- z*sqrt((p*(1-p))/n)

margin<- z * se
margin
##   [1] 0.000000000 0.004182736 0.005885332 0.007171160 0.008237748 0.009161988
##   [7] 0.009983492 0.010725891 0.011404646 0.012030533 0.012611425 0.013153285
##  [13] 0.013660760 0.014137552 0.014586670 0.015010598 0.015411416 0.015790883
##  [19] 0.016150504 0.016491578 0.016815233 0.017122457 0.017414120 0.017690992
##  [25] 0.017953756 0.018203024 0.018439343 0.018663204 0.018875052 0.019075287
##  [31] 0.019264270 0.019442329 0.019609763 0.019766841 0.019913809 0.020050888
##  [37] 0.020178280 0.020296167 0.020404716 0.020504072 0.020594371 0.020675729
##  [43] 0.020748253 0.020812035 0.020867156 0.020913682 0.020951672 0.020981173
##  [49] 0.021002219 0.021014837 0.021019041 0.021014837 0.021002219 0.020981173
##  [55] 0.020951672 0.020913682 0.020867156 0.020812035 0.020748253 0.020675729
##  [61] 0.020594371 0.020504072 0.020404716 0.020296167 0.020178280 0.020050888
##  [67] 0.019913809 0.019766841 0.019609763 0.019442329 0.019264270 0.019075287
##  [73] 0.018875052 0.018663204 0.018439343 0.018203024 0.017953756 0.017690992
##  [79] 0.017414120 0.017122457 0.016815233 0.016491578 0.016150504 0.015790883
##  [85] 0.015411416 0.015010598 0.014586670 0.014137552 0.013660760 0.013153285
##  [91] 0.012611425 0.012030533 0.011404646 0.010725891 0.009983492 0.009161988
##  [97] 0.008237748 0.007171160 0.005885332 0.004182736 0.000000000
sleep_time<- yrbss %>%
  filter(!is.na(school_night_hours_sleep)) %>%
  mutate(sleep_everyday = ifelse(school_night_hours_sleep == "<5", "yes", "no"))

sleep_time %>%
  count(sleep_everyday)
## # A tibble: 2 × 2
##   sleep_everyday     n
##   <chr>          <int>
## 1 no              7754
## 2 yes              597
sleep_time %>%
 specify(response = sleep_everyday, 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.0663   0.0777
n <- nrow(sleep_time)
z <- 1.96


se <- z*sqrt((p*(1-p))/n)

margin<- z * se
margin
##   [1] 0.000000000 0.004182736 0.005885332 0.007171160 0.008237748 0.009161988
##   [7] 0.009983492 0.010725891 0.011404646 0.012030533 0.012611425 0.013153285
##  [13] 0.013660760 0.014137552 0.014586670 0.015010598 0.015411416 0.015790883
##  [19] 0.016150504 0.016491578 0.016815233 0.017122457 0.017414120 0.017690992
##  [25] 0.017953756 0.018203024 0.018439343 0.018663204 0.018875052 0.019075287
##  [31] 0.019264270 0.019442329 0.019609763 0.019766841 0.019913809 0.020050888
##  [37] 0.020178280 0.020296167 0.020404716 0.020504072 0.020594371 0.020675729
##  [43] 0.020748253 0.020812035 0.020867156 0.020913682 0.020951672 0.020981173
##  [49] 0.021002219 0.021014837 0.021019041 0.021014837 0.021002219 0.020981173
##  [55] 0.020951672 0.020913682 0.020867156 0.020812035 0.020748253 0.020675729
##  [61] 0.020594371 0.020504072 0.020404716 0.020296167 0.020178280 0.020050888
##  [67] 0.019913809 0.019766841 0.019609763 0.019442329 0.019264270 0.019075287
##  [73] 0.018875052 0.018663204 0.018439343 0.018203024 0.017953756 0.017690992
##  [79] 0.017414120 0.017122457 0.016815233 0.016491578 0.016150504 0.015790883
##  [85] 0.015411416 0.015010598 0.014586670 0.014137552 0.013660760 0.013153285
##  [91] 0.012611425 0.012030533 0.011404646 0.010725891 0.009983492 0.009161988
##  [97] 0.008237748 0.007171160 0.005885332 0.004182736 0.000000000

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=√p(1−p)/n. This is then used in the formula for the margin of error for a 95% confidence interval:

                  ME=1.96×SE=1.96×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×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?
n <- 1000
p <- seq(from = 0, to = 1, by = 0.01)
margin <- 2 * sqrt(p * (1 - p)/n)
margin
##   [1] 0.000000000 0.006292853 0.008854377 0.010788883 0.012393547 0.013784049
##   [7] 0.015019987 0.016136914 0.017158088 0.018099724 0.018973666 0.019788886
##  [13] 0.020552372 0.021269697 0.021945387 0.022583180 0.023186203 0.023757104
##  [19] 0.024298148 0.024811288 0.025298221 0.025760435 0.026199237 0.026615785
##  [25] 0.027011109 0.027386128 0.027741665 0.028078461 0.028397183 0.028698432
##  [31] 0.028982753 0.029250641 0.029502542 0.029738863 0.029959973 0.030166206
##  [37] 0.030357866 0.030535226 0.030698534 0.030848015 0.030983867 0.031106269
##  [43] 0.031215381 0.031311340 0.031394267 0.031464265 0.031521421 0.031565804
##  [49] 0.031597468 0.031616451 0.031622777 0.031616451 0.031597468 0.031565804
##  [55] 0.031521421 0.031464265 0.031394267 0.031311340 0.031215381 0.031106269
##  [61] 0.030983867 0.030848015 0.030698534 0.030535226 0.030357866 0.030166206
##  [67] 0.029959973 0.029738863 0.029502542 0.029250641 0.028982753 0.028698432
##  [73] 0.028397183 0.028078461 0.027741665 0.027386128 0.027011109 0.026615785
##  [79] 0.026199237 0.025760435 0.025298221 0.024811288 0.024298148 0.023757104
##  [85] 0.023186203 0.022583180 0.021945387 0.021269697 0.020552372 0.019788886
##  [91] 0.018973666 0.018099724 0.017158088 0.016136914 0.015019987 0.013784049
##  [97] 0.012393547 0.010788883 0.008854377 0.006292853 0.000000000
graph <- data.frame(p = p, margin = margin)
ggplot(data = graph, aes(x = p, y = margin)) + 
  geom_line() +
  labs(x = "Population Proportion", y = "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 ≥10 and n(1−p)≥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 p hat 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 sampling distribution is normal ,unimodal, centered at 0.1, spread between 0.01 and 0.14.

  2. 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. To keep n constant, the shape is normal and spread increases as p goes up to 50%, then spread the decreases when p reaches 100%.

  3. Now also change n. How does n appear to affect the distribution of p hat? The sample distribution of population appears to be normal, unimodal with much less spread as well as standard error decreases.

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.
exercise_time<- yrbss %>%
  filter(!is.na(strength_training_7d)) %>%
  mutate(exercise_everyday = ifelse(strength_training_7d == "7", "yes", "no"))

exercise_time %>%
  count(exercise_everyday)
## # A tibble: 2 × 2
##   exercise_everyday     n
##   <chr>             <int>
## 1 no                 6939
## 2 yes                1412
exercise_time %>%
 specify(response = exercise_everyday, 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.161    0.177
n <- nrow(exercise_time)
z <- 1.96
se <- z*sqrt((p*(1-p))/n)

margin<- z * se
margin
##   [1] 0.000000000 0.004182736 0.005885332 0.007171160 0.008237748 0.009161988
##   [7] 0.009983492 0.010725891 0.011404646 0.012030533 0.012611425 0.013153285
##  [13] 0.013660760 0.014137552 0.014586670 0.015010598 0.015411416 0.015790883
##  [19] 0.016150504 0.016491578 0.016815233 0.017122457 0.017414120 0.017690992
##  [25] 0.017953756 0.018203024 0.018439343 0.018663204 0.018875052 0.019075287
##  [31] 0.019264270 0.019442329 0.019609763 0.019766841 0.019913809 0.020050888
##  [37] 0.020178280 0.020296167 0.020404716 0.020504072 0.020594371 0.020675729
##  [43] 0.020748253 0.020812035 0.020867156 0.020913682 0.020951672 0.020981173
##  [49] 0.021002219 0.021014837 0.021019041 0.021014837 0.021002219 0.020981173
##  [55] 0.020951672 0.020913682 0.020867156 0.020812035 0.020748253 0.020675729
##  [61] 0.020594371 0.020504072 0.020404716 0.020296167 0.020178280 0.020050888
##  [67] 0.019913809 0.019766841 0.019609763 0.019442329 0.019264270 0.019075287
##  [73] 0.018875052 0.018663204 0.018439343 0.018203024 0.017953756 0.017690992
##  [79] 0.017414120 0.017122457 0.016815233 0.016491578 0.016150504 0.015790883
##  [85] 0.015411416 0.015010598 0.014586670 0.014137552 0.013660760 0.013153285
##  [91] 0.012611425 0.012030533 0.011404646 0.010725891 0.009983492 0.009161988
##  [97] 0.008237748 0.007171160 0.005885332 0.004182736 0.000000000
sleep_time<- yrbss %>%
  filter(!is.na(school_night_hours_sleep)) %>%
  mutate(sleep_everyday = ifelse(school_night_hours_sleep == "10+", "yes", "no"))

sleep_time %>%
  count(sleep_everyday)
## # A tibble: 2 × 2
##   sleep_everyday     n
##   <chr>          <int>
## 1 no              8177
## 2 yes              174
sleep_time %>%
 specify(response = sleep_everyday, 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.0178   0.0239
n <- nrow(sleep_time)
z <- 1.96
se <- z*sqrt((p*(1-p))/n)

margin<- z * se
margin
##   [1] 0.000000000 0.004182736 0.005885332 0.007171160 0.008237748 0.009161988
##   [7] 0.009983492 0.010725891 0.011404646 0.012030533 0.012611425 0.013153285
##  [13] 0.013660760 0.014137552 0.014586670 0.015010598 0.015411416 0.015790883
##  [19] 0.016150504 0.016491578 0.016815233 0.017122457 0.017414120 0.017690992
##  [25] 0.017953756 0.018203024 0.018439343 0.018663204 0.018875052 0.019075287
##  [31] 0.019264270 0.019442329 0.019609763 0.019766841 0.019913809 0.020050888
##  [37] 0.020178280 0.020296167 0.020404716 0.020504072 0.020594371 0.020675729
##  [43] 0.020748253 0.020812035 0.020867156 0.020913682 0.020951672 0.020981173
##  [49] 0.021002219 0.021014837 0.021019041 0.021014837 0.021002219 0.020981173
##  [55] 0.020951672 0.020913682 0.020867156 0.020812035 0.020748253 0.020675729
##  [61] 0.020594371 0.020504072 0.020404716 0.020296167 0.020178280 0.020050888
##  [67] 0.019913809 0.019766841 0.019609763 0.019442329 0.019264270 0.019075287
##  [73] 0.018875052 0.018663204 0.018439343 0.018203024 0.017953756 0.017690992
##  [79] 0.017414120 0.017122457 0.016815233 0.016491578 0.016150504 0.015790883
##  [85] 0.015411416 0.015010598 0.014586670 0.014137552 0.013660760 0.013153285
##  [91] 0.012611425 0.012030533 0.011404646 0.010725891 0.009983492 0.009161988
##  [97] 0.008237748 0.007171160 0.005885332 0.004182736 0.000000000
  1. Let's say there has been no difference in likeliness to strength train everyday 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.

Type 1 Error is rejecting the null hypothesis when HNull is actually true. We do not want to reject HNull if the error is more than 0.5%. If the null hypothesis is true, the significance level indicates how often the data lead us to incorrectly reject H_null, meaning there is 5% margin we could be wrong. We could verify the change by checking success-failure and computing standard error for the hypothesis test

  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.
p <- 0.50
margin <- 0.01 
z <- 1.96
se <- sqrt((p*(1-p))/n)

n <- ((z^2)*(p*(1-p))) / (margin^2)
n
## [1] 9604

This lab was very challenging for me because I don't fully understand the formulas or when to apply which formula.