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.
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
.
# Load the dataset if it's not already loaded
data(yrbss)
# View column names to identify the correct column
colnames(yrbss)
## [1] "age" "gender"
## [3] "grade" "hispanic"
## [5] "race" "height"
## [7] "weight" "helmet_12m"
## [9] "text_while_driving_30d" "physically_active_7d"
## [11] "hours_tv_per_school_day" "strength_training_7d"
## [13] "school_night_hours_sleep"
# Count the occurrences within each category for days texted while driving
table(yrbss$text_while_driving_30d)
##
## 0 1-2 10-19 20-29 3-5
## 4792 925 373 298 493
## 30 6-9 did not drive
## 827 311 4646
# Filter for students who texted while driving every day and never wear helmets
everyday_texters <- yrbss[yrbss$text_while_driving_30d == "30", ]
# Count how many never wear helmets
no_helmet <- nrow(everyday_texters[everyday_texters$helmet_12m == "Never", ])
# Count total number of students who text every day while driving
total_everyday_texters <- nrow(everyday_texters)
# Calculate proportion
proportion_no_helmet <- no_helmet / total_everyday_texters
# Display the result
proportion_no_helmet
## [1] 0.5335244
0.5335244
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
.
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.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.
# Confidence interval for the proportion of non-helmet wearers who texted every day
ci <- 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)
# Calculate margin of error
moe <- (ci$upper_ci - ci$lower_ci) / 2
# Display margin of error
moe
## [1] 0.005689682
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.## [1] "female" "male" NA
# Confidence interval for the proportion of female students
ci_gender <- yrbss %>%
drop_na(gender) %>%
specify(response = gender, success = "female") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)
# Calculate margin of error for gender
moe_gender <- (ci_gender$upper_ci - ci_gender$lower_ci) / 2
# Check the structure of the 'physically_active_7d' column
str(yrbss$physically_active_7d)
## int [1:13583] 4 2 7 0 2 1 4 4 5 0 ...
## [1] 4 2 7 0 1 5 3 NA 6
# Create a binary categorical variable for physically active or not
yrbss <- yrbss %>%
mutate(physically_active_binary = ifelse(physically_active_7d > 0, "Yes", "No"))
# Confidence interval for physically active students (at least one day active)
ci_active <- yrbss %>%
drop_na(physically_active_binary) %>%
specify(response = physically_active_binary, success = "Yes") %>%
generate(reps = 1000, type = "bootstrap") %>%
calculate(stat = "prop") %>%
get_ci(level = 0.95)
# Display the confidence interval
ci_active
## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.831 0.843
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:
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\)).
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?For a given sample size, the margin of error is maximized when the population proportion is 0.5. As the proportion moves closer to 0 or 1, the margin of error decreases because the population becomes more homogeneous.
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 is centered around the true population proportion 0.1, with a relatively small spread indicating low variability due to the large sample size n=300. The shape of the distribution is approximately normal, consistent with the central limit theorem, which states that for sufficiently large sample sizes, the distribution of sample proportions will approach a normal distribution.
As p changes, the distribution remains approximately normal but becomes slightly skewed when p is closer to 0 or 1 due to less variability room. The center of the distribution is always around the true population proportion (p). The spread decreases when p is near 0 or 1, making the distribution more concentrated. Conversely, the spread is maximized around p = 0.5, allowing for more variability.
Increasing the sample size (n) reduces the distribution spread. As n grows, the variability in sample proportions decreases, leading to a narrower, more concentrated distribution around the true population proportion (p). Larger sample sizes yield more accurate, less variable population proportion estimates.
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
.
The sleep categories range from <5 to 10+ hours per day. Each bar represents a sleep duration group, with the y-axis showing the proportion of students engaging in strength training (0 to 7 days). Colors indicate the number of training days, with pink for no training. Generally, no strength training (pink) dominates each bar. There’s little change in students training daily across sleep durations, though some variation exists in less frequent training. This suggests no strong link between 10+ hours of sleep and daily strength training, but a formal statistical test is needed to confirm it.
# Load necessary libraries
library(dplyr)
library(ggplot2)
library(infer)
# Filter and mutate the data for sleep category and remove missing values
yrbss_filtered <- yrbss %>%
filter(!is.na(strength_training_7d), !is.na(school_night_hours_sleep)) %>%
mutate(sleep_category = ifelse(school_night_hours_sleep >= 10, "10+ hours", "fewer than 10 hours"))
# Ensure strength_training_7d is a factor
yrbss_filtered$strength_training_7d <- as.factor(yrbss_filtered$strength_training_7d)
# Visualize the data: check if there's a difference in strength training based on sleep hours
ggplot(yrbss_filtered, aes(x = school_night_hours_sleep, fill = strength_training_7d)) +
geom_bar(position = "fill") +
labs(x = "Sleep Category", y = "Proportion", fill = "Strength Train") +
ggtitle("Proportion of Strength Training Based on Sleep Category")
A Type 1 error happens when we wrongly reject a true null hypothesis. With a significance level of 0.05, there is a 5% chance of detecting a difference and rejecting the null hypothesis purely by chance, even if no actual difference exists. Thus, there’s a 5% probability of detecting a change by chance.
To ensure a margin of error no greater than 1% for a 95% confidence interval without knowing the true population proportion (p), we assume the worst-case scenario (p = 0.5). Using the margin of error formula and the values Z* = 1.96 and ME = 0.01, we calculate the required sample size (n) as 9,604. This large sample size ensures the desired precision and confidence level. Meaning is needed to sample 9,604 people to ensure that your estimate of the proportion of residents attending religious services weekly is within 1% margin of error with 95% confidence