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)Load data:
data("yrbss", package = "openintro")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.
check the head of the data:
head(yrbss)## # A tibble: 6 x 13
## age gender grade hispanic race height weight helmet_12m text_while_driv~
## <int> <chr> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr>
## 1 14 female 9 not Black o~ NA NA never 0
## 2 14 female 9 not Black o~ NA NA never <NA>
## 3 15 female 9 hispanic Native ~ 1.73 84.4 never 30
## 4 15 female 9 not Black o~ 1.6 55.8 never 0
## 5 15 female 9 not Black o~ 1.5 46.7 did not r~ did not drive
## 6 15 female 9 not Black o~ 1.57 67.1 did not r~ did not drive
## # ... with 4 more variables: physically_active_7d <int>,
## # hours_tv_per_school_day <chr>, strength_training_7d <int>,
## # school_night_hours_sleep <chr>
Count within each category that have texted while driving
count_text_while_driving <- yrbss %>% count(text_while_driving_30d)
count_text_while_driving## # A tibble: 9 x 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
The tibble above shows the count for each category that texted while driving within the past 30 days.
no_helmet <- yrbss %>%
filter(helmet_12m == "never")no_helmet <- no_helmet %>%
mutate(text_ind = ifelse(text_while_driving_30d == "30", "yes", "no"))no_helmet_prop <- no_helmet %>% count(text_ind) %>% mutate(prop = n/sum(n))
no_helmet_prop## # A tibble: 3 x 3
## text_ind n prop
## <chr> <int> <dbl>
## 1 no 6040 0.866
## 2 yes 463 0.0664
## 3 <NA> 474 0.0679
It can be seen that about 6.64% reported texting while driving and never wear helmets.
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.
set.seed(100)
no_helmet %>%
specify(response = text_ind, success = "yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)## # A tibble: 1 x 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.0654 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.
The margin of error \(= \frac{upperlimit - lowerlimit}{2}\)
upperlimit <- 0.0778
lowerlimit <- 0.0654
margin_error <- (upperlimit - lowerlimit)/2
paste0("The margin of error is ", margin_error)## [1] "The margin of error is 0.0062"
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.Variable1: hours_tv_per_school_day
set.seed(101)
did_not_watch_tv <- yrbss %>%
mutate(did_not_watch_tv = ifelse(hours_tv_per_school_day =="do not watch", "yes", "no"))
did_not_watch_tv %>%
specify(response = did_not_watch_tv, success = "yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.99)## # A tibble: 1 x 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.131 0.146
This means that we are 99% confident that the proportion of students who did not watch tv is in the interval is in the interval (0.131, 146).
Variable2: school_night_hours_sleep
set.seed(110)
enough_sleep <- yrbss %>%
mutate(enough_sleep = ifelse(school_night_hours_sleep > 6, "yes", "no"))
enough_sleep %>%
specify(response = enough_sleep, success = "yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.99)## # A tibble: 1 x 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.548 0.571
This means that we are 99% confident that the proportion of students who had enough sleep (slept more than 6hours) is in the interval (0.548, 0.571).
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 <- 1000The 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")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 relationship is parabolic. The margin of error is maximum at p = 0.5; From the graph, we can see that margin of error increases as population proportion increases and peaks at p = 0.5 and then decreases to zero when p = 1.
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 sampling distribution for n = 300, p = 0.1 is unimodal, and centered around 0.1, and follows a nearly normal distribution. np = 30, and n(1-p) = 270 which are both well above 10. Therefore, a normal approximation can be made in this case.
With n constant and as p increases, the shape of the distribution gets more normal, the center moves towards the right and closer to 1 and the spread increases up until p = 0.5. Beyond p = 0.5, the center still moves to the right, but the spread becomes narrower. The graph completely vanishes at p = 1.0
As n increases, the distribution gets closer to a normal curve, the spread gets narrower, but the center appears to remain the same. As n approaches infinity, the spread approaches zero and \(\hat{p}\) converges to a single 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.
Null Hypothesis, \(H_{0}\) : There has been no difference in likeliness to strength train everyday of the week for those who sleep 10+ hours.
Alternative Hypothesis, \(H_{1}\) : There has been difference in likeliness to strength train everyday of the week for those who sleep 10+ hours.
set.seed(110)
sleep10more <- yrbss %>%
filter(school_night_hours_sleep == "10+") %>%
mutate(strength_train = ifelse(strength_training_7d == "7", "yes", "no"))
sleep10more %>%
specify(response = strength_train, success = "yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)## # A tibble: 1 x 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.221 0.317
Therefore, we are 95% confident that the proportion of people who sleep 10+ hours is between 22.1% and 31.7%
Type 1 error is the probability of rejecting a true null hypothesis. In this case, the probability is 0.05
Referring to the plot the relationship between margin of error and proportion, margin of error is minimum at p = 0 or 1 and maximum at p = 0.5;
Assuming we select p such that p = 0.5, \(me = 1.96\sqrt{\frac{p(1-p)}{n}}\)
p <- 0.5
me <- 0.01
n <- (p*(1-p)/(me/1.96)**2)
paste0("We would need to sample about ", n, " people to ensure we are within the guidelines")## [1] "We would need to sample about 9604 people to ensure we are within the guidelines"