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.
ANS:
## # 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
Remember that you can use filter to limit the dataset to
get just non-helmet wearers. Here, we will name the dataset
no_helmet.
There are 6,977 people who do not wear a 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.
The proportion of people who have texted while driving every day in the past 30 days and never wear helmets can be calculated by first calculating the total people who text every day while driving and do not wear a helmet.
## [1] 463
There are 463 people who texted while driving every day.
# calc percentage
pctnohelmet <- text30_no_helmet$n/nrow(yrbss)
print(paste("The proportion for people who have texted while driving every day in the past 30 days and never wear helmets is", sprintf("%.2f%%", pctnohelmet * 100)))## [1] "The proportion for people who have texted while driving every day in the past 30 days and never wear helmets is 3.41%"
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 <- no_helmet|>
mutate(text_ind = replace_na(ifelse(text_while_driving_30d == "30", "yes", "no"), "unknown"))
no_helmet |>
filter (text_ind != "unknown") |>
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.0650 0.0778
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 tha 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.
ANS: The margin of error is the square root of the sample proportion times one minus the sample proportion, divided by the number of people in the population - all of this times a value for z, which depends on the confidence level. For 0.95 confidence the z is 1.96.
#me = Margin of Error
me <- 1.96*sqrt((pctnohelmet*(1-pctnohelmet))/nrow(yrbss))
print(paste("The margin of error for those who have texted while driving every day in the past 30 days and never wear helmets is", sprintf("%.2f%%", me * 100)))## [1] "The margin of error for those who have texted while driving every day in the past 30 days and never wear helmets is 0.31%"
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.ANS: I’m going to look at: a) women who strength train 4 or more days per week b) men who sleep less than 8 hours a day
Women who strength train 4 or more days per week
set.seed(66861)
library(infer) # load again to ensure correct function use
# Step 1: identify women who strength train 4+ hours/day
gender_f <- yrbss |>
filter(gender == "female") |>
mutate(
train4day = case_when(
strength_training_7d >= 4 ~ "yes",
strength_training_7d < 4 ~ "no"
)
) |>
filter(!is.na(train4day))
ci_training <- gender_f |>
specify(response = train4day, success = "yes") |>
generate(reps = 1000, type = "bootstrap") |>
calculate(stat = "prop") |>
get_ci(level = 0.95)
ci_training## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.282 0.304
The lower ci_training is 0.282 and the upper ci_training is 0.304
# get Margin of error of ci_training
train4day_cnt <- gender_f |>
filter(train4day == "yes") |>
count()
gender_f_proportion <- train4day_cnt$n/nrow(yrbss)
MOE_training <- 1.96*sqrt((gender_f_proportion*(1-gender_f_proportion))/nrow(yrbss))
print(paste("The margin of error for women who train 4 days or more days per week is", sprintf("%.2f%%", MOE_training * 100)))## [1] "The margin of error for women who train 4 days or more days per week is 0.57%"
Now let’s do the same for men who sleep less than 7 hours per day
set.seed(66861)
# Step 1: identify men who sleep less than 7 hrs/day
gender_m <- yrbss |>
filter(gender == "male") |>
mutate(
sleepless7 = ifelse(school_night_hours_sleep <= 7, "yes", "no"),
sleepless7 = replace_na(sleepless7, "no")
)
ci_training <- gender_m |>
specify(response = sleepless7, success = "yes") |>
generate(reps = 1000, type = "bootstrap") |>
calculate(stat = "prop") |>
get_ci(level = 0.95)
ci_training## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 0.622 0.645
The lower_ci = 0.622 and the upper_ci = 0.645
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?ANS: The plot shows that the margin of error reaches its maximum when
p = .5o, or 50% of population proportion.
The “p * (1 - p)” in me calculation is maximized when p is 0.5, and a
larger value for this term results in a larger margin of error. As you
move away from p = 0.5 in either direction, the margin of error
decreases. For a given sample size n, the margin of error is largest
when p is around 0.5 (50%) because this is the point of maximum
uncertainty. When p is close to 0.5, you are least certain about the
true population proportion, and the margin of error is highest.
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.
ANS:
Shape: The shape of the sampling distribution of the proportions at \(n = 300\) resembles a normal distribution. The distribution is symmetric and bell-shaped like a standard normal distribution.
Center: The center of the sampling distribution of sample proportions is approx. 0.1, meaning that the mean of the sampling distribution of the proportions will be 0.1. On average, 10% of the samples will have a proportion that is expected to be equal to the true population proportion.
Spread: The spread of the distribution indicates how much variability is incurred by sampling only 300 at a time from the population.
Shape: When p is close to 0 or 1, the shape of the sampling distribution becomes increasingly skewed. If p is close to 0, the distribution will be right-skewed, with the majority of the data on the right side.If p is close to 1, the distribution will be left-skewed, with most of the data on the left side.
Center: The center of the sampling distribution is given by the mean, which is μ = n * p. As p changes, the center of the distribution shifts accordingly. When p is small, the center is closer to 0, and as p increases, the center moves toward n.
Spread: The spread of the sampling distribution is determined by the standard deviation, which is sd = sqrt(n * p * (1 - p)). When p is small or large, the spread is smaller because the values are clustered around the mean. This indicates less variability in the distribution.When p is around 0.5, the spread is at its maximum because there is more variability in the distribution.
Shape: As the n increases, the distribution of p-hat becomes approximately normal. The shape of the distribution becomes more bell-shaped and symmetric. This property is a result of the Central Limit Theorem, which states that the sampling distribution of p-hat becomes more normal as the sample size increases, regardless of the shape of the population distribution.
Precision and Variability: As n increases, p-hat becomes a more precise estimate of the population proportion of o.1. With larger n, the variability or spread of the distribution of p-hat decreases. This is because larger samples provide more information about the population, and thus, the estimates of p-hat are less likely to vary widely from one sample to another.The opposite is true when n is small.
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.
ANS:
The null hypothesis is that there IS NOT evidence that those who sleep 10+ hours per day are more likely to strength train every day of the week.
The alternative hypothesis is that there IS convincing evidence that those who sleep 10+ hours per day are more likely to strength train every day of the week.
yrbss2 <- yrbss |>
mutate(sleep10 = replace_na(ifelse(school_night_hours_sleep == "10+", "yes", "no"), "unknown"),
strength7 = replace_na(ifelse(strength_training_7d == "7", "yes", "no"), "unknown"))
ci2 <- yrbss2 |> filter(sleep10 != "unknown" & strength7 != "unknown") |>
specify(response = strength7, explanatory = sleep10, success = "yes") |>
generate(reps = 1000, type = "bootstrap") |>
calculate(stat = "diff in props", order = c("no", "yes")) |>
get_ci(level = 0.95)
ci2## # A tibble: 1 × 2
## lower_ci upper_ci
## <dbl> <dbl>
## 1 -0.153 -0.0562
ANS: The probability that you could detect a change simply by chance is 0.05 (or 5%). If there is truly no change occurring, the test will still produce a \(p\)-value less than or equal to 0.05 exactly 5% of the time, resulting in a false alarm. A Type 1 Error is defined as a false positive.
ANS:
# p estimated proportion of residents attending religious services
# moe is the desired margin of error, which is 1% or 0.01
p <- 0.5 # b/d 0.5 will yield the maximum required sample size
Z <- 1.96 # critical value corresponding to the a 95% confidence
ME <- 0.01
# For a 95% confidence interval, calculate sample size n
n <- Z^2*p*(1-p)/ME^2
print(paste("The requried sample size required to estimate the proportion of residents who attend a religious service on a weekly basis with a margin of error no greater than 1%
at a 95% confidence leve is", n))## [1] "The requried sample size required to estimate the proportion of residents who attend a religious service on a weekly basis with a margin of error no greater than 1%\nat a 95% confidence leve is 9604"