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)
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.
view(yrbss)
counts_category <- yrbss %>% count(text_while_driving_30d)
counts_category
## # 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
prop_text_no_helmet <- yrbss %>%
filter(helmet_12m == "never") %>%
summarise(prop_text_every_day = mean(text_while_driving_30d == "30", na.rm = TRUE))
prop_text_no_helmet
## # A tibble: 1 × 1
## prop_text_every_day
## <dbl>
## 1 0.0712
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"))
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(1234)
no_helmet %>% drop_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.0652 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.
set.seed(1234)
margin_of_error <- no_helmet %>%
drop_na(text_ind) %>% specify(response = text_ind, success = "yes") %>% generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95) %>%
summarise(margin_of_error = (upper_ci - lower_ci) / 2)
margin_of_error
## # A tibble: 1 × 1
## margin_of_error
## <dbl>
## 1 0.00623
The margin of error is about 0.62%
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.set.seed(1235)
glimpse(yrbss)
## Rows: 13,583
## Columns: 13
## $ age <int> 14, 14, 15, 15, 15, 15, 15, 14, 15, 15, 15, 1…
## $ gender <chr> "female", "female", "female", "female", "fema…
## $ grade <chr> "9", "9", "9", "9", "9", "9", "9", "9", "9", …
## $ hispanic <chr> "not", "not", "hispanic", "not", "not", "not"…
## $ race <chr> "Black or African American", "Black or Africa…
## $ height <dbl> NA, NA, 1.73, 1.60, 1.50, 1.57, 1.65, 1.88, 1…
## $ weight <dbl> NA, NA, 84.37, 55.79, 46.72, 67.13, 131.54, 7…
## $ helmet_12m <chr> "never", "never", "never", "never", "did not …
## $ text_while_driving_30d <chr> "0", NA, "30", "0", "did not drive", "did not…
## $ physically_active_7d <int> 4, 2, 7, 0, 2, 1, 4, 4, 5, 0, 0, 0, 4, 7, 7, …
## $ hours_tv_per_school_day <chr> "5+", "5+", "5+", "2", "3", "5+", "5+", "5+",…
## $ strength_training_7d <int> 0, 0, 0, 0, 1, 0, 2, 0, 3, 0, 3, 0, 0, 7, 7, …
## $ school_night_hours_sleep <chr> "8", "6", "<5", "6", "9", "8", "9", "6", "<5"…
physically_active_counts <- yrbss %>% count(physically_active_7d, sort = TRUE)
exercise_time <- yrbss %>%
filter(!is.na(physically_active_7d)) %>% mutate(exercise_everyday = ifelse(physically_active_7d < "1", "yes", "no"))
exercise_everyday_counts <- exercise_time %>% count(exercise_everyday)
exercise_everyday_counts
## # A tibble: 2 × 2
## exercise_everyday n
## <chr> <int>
## 1 no 11138
## 2 yes 2172
exercise_ci <- exercise_time %>%
specify(response = exercise_everyday, success = "yes") %>% generate(reps = 1000, type = "bootstrap") %>% calculate(stat = "prop") %>% get_ci(level = 0.95)
exercise_ci
## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.157 0.170
n <- nrow(exercise_time)
z <- 1.96
p <- mean(exercise_time$exercise_everyday == "yes")
se <- z * sqrt((p * (1 - p)) / n)
me <- z * se
me
## [1] 0.01230491
We are 95% confident that the amount of students that exercise at least once a week is between 15.7% and 17%. The margin of error is 12%.
set.seed(1236)
school_sleep_counts <- yrbss %>%
count(school_night_hours_sleep, sort = TRUE)
school_sleep_counts
## # A tibble: 8 × 2
## school_night_hours_sleep n
## <chr> <int>
## 1 7 3461
## 2 8 2692
## 3 6 2658
## 4 5 1480
## 5 <NA> 1248
## 6 <5 965
## 7 9 763
## 8 10+ 316
sleep_time <- yrbss %>%
filter(!is.na(school_night_hours_sleep)) %>% mutate(sleep_everyday = ifelse(school_night_hours_sleep == "<5", "yes", "no"))
sleep_everyday_counts <- sleep_time %>% count(sleep_everyday)
sleep_everyday_counts
## # A tibble: 2 × 2
## sleep_everyday n
## <chr> <int>
## 1 no 11370
## 2 yes 965
sleep_ci <- sleep_time %>%
specify(response = sleep_everyday, success = "yes") %>% generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)
sleep_ci
## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.0737 0.0830
n <- nrow(sleep_time)
z <- 1.96
p <- mean(sleep_time$sleep_everyday == "yes")
se <- z * sqrt((p * (1 - p)) / n)
me <- z * se
me
## [1] 0.009288537
We are 95% confident that the amount of students that sleep at least 5 hours per night is 73.7% and 83%. The margin of error is 9%.
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")
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 the population proportion increases, the margin of error also increases until it reaches a peak at 0.5%. At this point the margin of error starts to decrease as the population proportion passes 50%.
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.
I would say the sampling distribution is normal. It is centered at 0.10 and there isn’t much spread but I would say it is towards the mean.
Keeping N constant and changing P gives some interesting results. As P increases and approaches 50%, there is more spread around the center. As P surpasses 50% the spread begins to decrease and reverts to what it was in the beginning of the distribution.
As N continues to increase, the distribution continues to look more like a normal distribution. This tells me that the standard error decreases as N increases as well as the margin of error.
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.
H0:Those who sleep 10+ hours per day are not likely to strength train every day of the week. H1:Those who sleep 10+ hours per day are likely to strength train everyday.
A type 1 error is the probability of detecting a change simply by chance. It is equal to the significance level of the test which is 0.05%.
After inputting the values in order solve for the sample size, I determined that a sample size of 9,604 is needed in order to have an estimate with a margin of error within 1% and a 95% confidence level.
p <- 0.50
me <- 0.01
z <- 1.96
n <- ((z^2) * p * (1 - p)) / (me^2)
print(n)
## [1] 9604