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)

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.

data('yrbss', package='openintro')
  1. What are the counts within each category for the amount of days these students have texted while driving within the past 30 days?

There were 4792 in the “0” category, 925 in “1-2”, 373 in “10-19”, 298 in “20-29”, 493 in “3-5”, 827 in “30”, 311 in “6-9”, 4646 in “did not drive”, and 918 in the “NA” category.

yrbss %>% 
  count(text_while_driving_30d)
## # A tibble: 9 × 2
##   text_while_driving_30d     n
##   <chr>                  <int>
## 1 0                       4792
## 2 1-2                      925
## 3 10-19                    373
## 4 20-29                    298
## 5 3-5                      493
## 6 30                       827
## 7 6-9                      311
## 8 did not drive           4646
## 9 <NA>                     918
  1. What is the proportion of people who have texted while driving every day in the past 30 days and never wear helmets?

The proportion of people who have texted while driving every day in the past 30 days and never wear helmets is 463/6503 or 7.1%.

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"))

table(no_helmet$text_ind)
## 
##   no  yes 
## 6040  463

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 %>%
  filter(!is.na(text_ind)) %>%
  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.0777

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 sample size of the amount of non of non-helmet wearers that have texted while driving each day for the past 30 days is 463 (n). The sample proportion is 7.1%. Using the formula: ME = 1.96 * sqrt(p*(1-p)/n), the margin of error is 2.3%.

n <- 463
p <- .071
me <- 1.96*(sqrt(p*(1-p)/n)) 
me * 100
## [1] 2.33939
  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.

    The two variables I will be looking at is physical active in the past 7 days (physically_active_7d) and strength training (strength_training_7d). Level of confidence will be set at 95%.

    For physically active, success will be if they are physically active for 7 days. I am 95% confident that the interval for the proportion of those who are physically active for 7 days is between .265 and .280.

table(yrbss$physically_active_7d)
## 
##    0    1    2    3    4    5    6    7 
## 2172  962 1270 1451 1265 1728  840 3622
active <- yrbss %>%
  filter(!is.na(physically_active_7d)) %>%
  mutate(healthy = ifelse(physically_active_7d == "7", "yes", "no")) 

table(active$healthy)
## 
##   no  yes 
## 9688 3622
set.seed(501)
active %>% 
  specify(response = healthy, 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.265    0.280

For strength training, success will be if they strength trained every day for the past 7 days. I am 95% confident that the interval for the proportion of those who strength trained every day for the past 7 days is between .162 and .174.

table(yrbss$strength_training_7d)
## 
##    0    1    2    3    4    5    6    7 
## 3632 1012 1305 1468 1059 1333  513 2085
gains <- yrbss %>%
  filter(!is.na(strength_training_7d)) %>%
  mutate(strong = ifelse(strength_training_7d == "7", "yes", "no")) 

table(gains$strong)
## 
##    no   yes 
## 10322  2085
set.seed(502)
gains %>% 
  specify(response = strong, 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.162    0.174

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?

    The margin of error is at its peak when the population proportion is at 0.50. As the population proportion moves further away from 0.50, towards 0 and 1, the margin of error decreases. The margin of error when the population proportion is at 0.25 and 0.75 is the same. For a given sample size, the margin of error is maximized when the value of p is at 0.50.

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.

The app did not open for me. I ended up changing the geom_histogram to geom_bar. This was the error I got initally with geom_histogram: Error: (converted from warning) Error in : (converted from warning) Error in geom_histogram: Problem while converting geom to grob. ℹ Error occurred in the 1st layer. Caused by error: ! (converted from warning) Removed 2 rows containing missing values (geom_bar()).

  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 center is at 0.1. It has a normal distribution. It has a spread from 0.04 to 0.17.

  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.

    As \(p\) increases or decreases, the center moves to where the \(p\) value is. It has a shape of a normal distribution with the peak at \(p\) regardless of the \(p\) changes. The spread gets wider as it approaches a \(p\) of 0.5. As \(p\) moves away from in both either direction, the spread becomes narrower.

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

    As the value of n increases, the spread of \(p\) decreases. In the standard error formula, n is in the denominator so as that increases the standard of error decreases and the spread becomes narrower.


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.

    Null hypothesis: There is no difference in strength training every day in those who sleep 10+ hours per day and those who do not sleep for 10+ hours per day. Alternative hypothesis: There is a difference in strength training every day in those who sleep 10+ hours per day and those who do not sleep for 10+ hours per day. Confidence Level: 95%

    Based on the data, I am 95% confident the proportion of individuals who sleep 10+ hours per day that strength train for 7 days is between 0.218 and 0.317. In comparison, I am 95% confident the proportion of individuals who do not sleep 10+ hours per day that strength train for 7 days is between .158 and .171. Thus, we can reject the null hypothesis and accept the alternative hypothesis. Those who sleep 10+ hours per day(confidence interval: 0.218 to 0.317) are more likely to strength train than those who sleep less than 10+ hours per day (confidence interval: 0.158 to 0.171)

table(yrbss$school_night_hours_sleep)
## 
##   <5  10+    5    6    7    8    9 
##  965  316 1480 2658 3461 2692  763
sloths <- yrbss %>% 
  filter(school_night_hours_sleep == "10+")
sloths <- sloths %>% 
  mutate(lifts = ifelse(strength_training_7d == "7", "yes", "no")) %>% 
  filter(!is.na(lifts))

table(sloths$lifts)
## 
##  no yes 
## 228  84
set.seed(199)
sloths %>% 
  specify(response = lifts, 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.218    0.317
no_sleep <- yrbss %>% 
  filter(school_night_hours_sleep != "10+")

no_sleep <- no_sleep %>% 
  mutate(lift_nosleep = ifelse(strength_training_7d == "7", "yes", "no")) %>% 
  filter(!is.na(lift_nosleep))

table(no_sleep$lift_nosleep)
## 
##   no  yes 
## 9949 1958
set.seed(198)
no_sleep %>% 
  specify(response = lift_nosleep, 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.158    0.171
  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.
At a significance level of 0.05, there is a 5% chance of detecting a type 1 error or a false positive. 
  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.
Assuming $p$ is 0.5 for a conservative estimate, 9604 people would be needed to be sampled to ensure that the estimate is within guidelines.
me <- 0.01
p <- 0.5
n <- (p*(1-p))/(me**2/1.96**2)
n
## [1] 9604