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
.
Insert your answer here
data("yrbss")
print(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
Insert your answer here
yrbss %>%
filter(helmet_12m=='never') %>%
mutate(text_drive=if_else(text_while_driving_30d=='30', 'yes', 'no'))%>%
drop_na(text_drive)%>%
count(text_drive)%>%
mutate(p=n/sum(n))
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.
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)
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.
Insert your answer here
#get the proportion for the "successes":
prop<- no_helmet %>%
drop_na(text_ind) %>%
count(text_ind) %>%
mutate(p = n/sum(n)) #p(yes) = 0.0712
print(prop)
## # A tibble: 2 × 3
## text_ind n p
## <chr> <int> <dbl>
## 1 no 6040 0.929
## 2 yes 463 0.0712
#For Margin of error:
p=0.0712
n=6040+463
1.96*sqrt(p*(1-p)/n) #ME=0.00625
## [1] 0.006250292
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.Insert your answer here
95% Ci:
m_texted<- yrbss %>%
drop_na() %>%
filter(gender=='male') %>%
mutate(male_texted = if_else(text_while_driving_30d=='30', 'yes', 'no'))
m_texted %>%
specify(response = male_texted, success = 'yes') %>%
generate(reps= 1000, type = 'bootstrap') %>%
calculate(stat= "prop") %>%
get_ci(level = 0.95) #0.0706~0.0866
We are 95% confident that 7.1% to 8.6% males texted while driving everyday in the past 30 days.
Margin of Error at 95% Ci:
p_m<- m_texted %>%
count(male_texted) %>%
mutate(p= n/sum(n)) %>%
filter(male_texted=='yes')%>%
pull(p)
n<-m_texted %>%
count(male_texted) %>%
summarise(n=sum(n))
print(1.96 * sqrt(p_m*(1-p_m)/n)) #ME=0.0081
## n
## 1 0.008077765
95% Ci: We are 95% confident that 16.4% to 18.3% female students are physically active for 7 days in the past 7 days.
work_out<- yrbss %>%
drop_na(physically_active_7d) %>%
filter(gender=='female') %>%
mutate(f_work_out=if_else(physically_active_7d=='7', 'yes', 'no'))
#calculate CI:
work_out%>%
specify(response = f_work_out, success = 'yes') %>%
generate(reps=1000, type = 'bootstrap') %>%
calculate(stat="prop") %>%
get_ci(level = 0.95) #0.164 ~ 0.183
Margin of Error:
p_f<- work_out %>%
count(f_work_out) %>%
mutate(p= n/sum(n)) %>%
filter(f_work_out=='yes')%>%
pull(p)
n_f<-work_out %>%
count(f_work_out) %>%
summarise(n=sum(n))
print(1.96 * sqrt(p_f*(1-p_f)/n_f)) #ME= 0.0092
## n
## 1 0.009186798
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?Insert your answer here
#Maximum ME:
max_point<- dd%>%
filter(me==max(dd$me))
ggplot(dd, aes(x = p, y = me)) +
geom_line() +
geom_point(data= max_point, aes(x=p, y= me), color='red', size=5)+
geom_text(data = max_point, aes(x=p, y= me, label = 'peak'),
vjust=-1)
labs( x='Population Proportion', y = 'Margin of Error') +
theme(legend.position = 'none')
## NULL
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.
Insert your answer here
Insert your answer here
Insert your answer here
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
.
Insert your answer here
H0 = The proportion (p1) of people who sleeping 10+ hours/day and strength train everyday of the week is the same as the proportion (p2) of those who sleep less than 10+hours/day and strength train everyday of the week. p1=p2
H1= p1 > p2.
Confidence interval difference at 95%:
yrbss_mod<- yrbss %>%
drop_na(school_night_hours_sleep, physically_active_7d) %>%
mutate(sleep_ind = if_else(school_night_hours_sleep == '10+', 'yes', 'no'),
work_out_ind = if_else(physically_active_7d=='7', 'yes','no'))
#to find people who sleep 10+ and train everyday:
yrbss_mod %>%
group_by(sleep_ind) %>%
count(work_out_ind)
p1<- yrbss_mod %>%
filter(work_out_ind=='yes') %>%
count(sleep_ind) %>%
mutate(p = n/sum(n)) %>%
filter(sleep_ind=='yes') %>%
pull(p)
p2<-yrbss_mod %>%
filter(work_out_ind=='no') %>%
count(sleep_ind) %>%
mutate(p = n/sum(n)) %>%
filter(sleep_ind=='yes') %>%
pull(p)
n1<- yrbss_mod %>%
filter(work_out_ind=='yes') %>%
count(sleep_ind) %>%
summarise(total=sum(n))%>%
pull(total)
n2<-yrbss_mod %>%
filter(work_out_ind=='no') %>%
count(sleep_ind) %>%
summarise(total=sum(n)) %>%
pull(total)
p_pool<- (115+198)/(n1+n2)
z<- (p1-p2)/(sqrt((p_pool*(1-p_pool)/n1)+(p_pool*(1-p_pool)/n2)))
#For a two-tailed p-value:
2*(1-pnorm(z))
## [1] 0.0001026157
#two tailed p-value = 0.0001 is much lesser alpha=0.05. Therefore, we reject the null hypothesis and accept the alternative hypothesis that there is a difference between people who sleep 10+ hours and working out daily.
Insert your answer here
Insert your answer here
p=0.5 for maximum margin of error
we need at least 9604 sample size.
n<- ((0.5*(1-0.5)/(0.01/1.96)^2))
print(n)
## [1] 9604