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)
library(psych)
library(statsr)The data
Every two years, the Centers for Disease Control and Prevention conduct the Youth Risk Behavior Surveillance System (YRBSS) survey, where it takes data from high schoolers (9th through 12th grade), to analyze health patterns. You will work with a selected group of variables from a random sample of observations during one of the years the YRBSS was conducted.
Load the yrbss data set into your workspace.
data('yrbss', package='openintro')There are observations on 13 different variables, some categorical and some numerical. The meaning of each variable can be found by bringing up the help file:
?yrbss- What are the cases in this data set? How many cases are there in our sample?
Remember that you can answer this question by viewing the data in the data viewer or by using the following command:
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"…
Exploratory data analysis
You will first start with analyzing the weight of the participants in kilograms: weight.
Using visualization and summary statistics, describe the distribution of weights. The summary function can be useful.
summary(yrbss$weight)## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 29.94 56.25 64.41 67.91 76.20 180.99 1004
- How many observations are we missing weights from?
Next, consider the possible relationship between a high schooler’s weight and their physical activity. Plotting the data is a useful first step because it helps us quickly visualize trends, identify strong associations, and develop research questions.
First, let’s create a new variable physical_3plus, which will be coded as either “yes” if they are physically active for at least 3 days a week, and “no” if not.
yrbss <- yrbss %>%
mutate(physical_3plus = ifelse(yrbss$physically_active_7d > 2, "yes", "no"))- Make a side-by-side boxplot of
physical_3plusandweight. Is there a relationship between these two variables? What did you expect and why?
yrbss %>%
ggplot() +
geom_boxplot(aes(x=weight, y=physical_3plus))ANSWER: From the above visual, we can see that the median weight of people that work out 3 days a week or more is actually higher than the median weight of those that don’t. This goes against my initial assumption, in which I assumed that as you work out more you lose more fat and therefore weight. Further research is required, as potentially I had not thought about the impact of muscle growth from more exercise.
The box plots show how the medians of the two distributions compare, but we can also compare the means of the distributions using the following to first group the data by the physical_3plus variable, and then calculate the mean weight in these groups using the mean function while ignoring missing values by setting the na.rm argument to TRUE.
yrbss %>%
group_by(physical_3plus) %>%
summarise(mean_weight = mean(weight, na.rm = TRUE))There is an observed difference, but is this difference statistically significant? In order to answer this question we will conduct a hypothesis test.
Inference
- Are all conditions necessary for inference satisfied? Comment on each. You can compute the group sizes with the
summarizecommand above by defining a new variable with the definitionn().
ANSWER: Conditions for inference: - normality - independence.
This dataset was randomly collected and all students are independent of each other. According to the box plots above, we can also see that the data appears to be normally distributed.
- Write the hypotheses for testing if the average weights are different for those who exercise at least times a week and those who don’t.
ANSWER: Null hypothesis: Students who are physically active 3 or more days per week have the same average weight as those who are not physically active 3 or more days per week.
Alternative hypothesis: Students who are physically active 3 or more days per week have a different average weight when compared to those who are not physically active 3 or more days per week.
Next, we will introduce a new function, hypothesize, that falls into the infer workflow. You will use this method for conducting hypothesis tests.
But first, we need to initialize the test, which we will save as obs_diff.
obs_diff <- yrbss %>%
specify(weight ~ physical_3plus) %>%
calculate(stat = "diff in means", order = c("yes", "no"))Notice how you can use the functions specify and calculate again like you did for calculating confidence intervals. Here, though, the statistic you are searching for is the difference in means, with the order being yes - no != 0.
After you have initialized the test, you need to simulate the test on the null distribution, which we will save as null.
null_dist <- yrbss %>%
specify(weight ~ physical_3plus) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "diff in means", order = c("yes", "no"))Here, hypothesize is used to set the null hypothesis as a test for independence. In one sample cases, the null argument can be set to “point” to test a hypothesis relative to a point estimate.
Also, note that the type argument within generate is set to permute, whichis the argument when generating a null distribution for a hypothesis test.
We can visualize this null distribution with the following code:
ggplot(data = null_dist, aes(x = stat)) +
geom_histogram()- How many of these
nullpermutations have a difference of at leastobs_stat?
obs_diff_val<-obs_diff$stat[1]
null_dist%>%
filter(stat>obs_diff_val)ANSWER:
There are no values greater than obs_stat
Now that the test is initialized and the null distribution formed, you can calculate the p-value for your hypothesis test using the function get_p_value.
null_dist %>%
get_p_value(obs_stat = obs_diff, direction = "two_sided")This the standard workflow for performing hypothesis tests.
- Construct and record a confidence interval for the difference between the weights of those who exercise at least three times a week and those who don’t, and interpret this interval in context of the data.
inference(data = yrbss, y = weight, x = physical_3plus,
statistic = "mean",
type = "ci",
null = NULL,
alternative = "twosided",
method = "theoretical")## Response variable: numerical, Explanatory variable: categorical (2 levels)
## n_no = 4022, y_bar_no = 66.6739, s_no = 17.6381
## n_yes = 8342, y_bar_yes = 68.4485, s_yes = 16.4783
## 95% CI (no - yes): (-2.4245 , -1.1246)
yrbss %>%
group_by(physical_3plus) %>%
summarise(sd_weight = sd(weight, na.rm = TRUE))yrbss %>%
group_by(physical_3plus) %>%
summarise(mean_weight = mean(weight, na.rm = TRUE))yrbss %>%
group_by(physical_3plus) %>%
summarise(freq = table(weight)) %>%
summarise(n = sum(freq))# a ~ not3plus
a_mean <- 66.67389
a_n <- 4022
a_sd <- 17.63805
# b ~ 3plus
b_mean <- 68.44847
b_n <- 8342
b_sd <- 16.47832
# 95% CI requires t ~ 1.96
t = 1.96
# a CI
upper_ci_a <- a_mean + t*(a_sd/sqrt(a_n))
lower_ci_a <- a_mean - t*(a_sd/sqrt(a_n))
# b_ci
upper_ci_b <- b_mean + t*(b_sd/sqrt(b_n))
lower_ci_b <- b_mean - t*(b_sd/sqrt(b_n))
print_list <- list(
c(lower_ci_a, upper_ci_a),
c(lower_ci_b, upper_ci_b)
)
print(print_list)## [[1]]
## [1] 66.12878 67.21900
##
## [[2]]
## [1] 68.09485 68.80209
ANSWER:
We are 95% confident that students who exercise 3+ times a week have an average weight between (68.095 – 68.802)
We are 95% confident that students who exercise 3+ times a week have an average weight between (66.129 – 67.219)
More Practice
- Calculate a 95% confidence interval for the average height in meters (
height) and interpret it in context.
mean_height <- mean(yrbss$height, na.rm = TRUE)
sd_height <- sd(yrbss$height, na.rm = TRUE)
sample_height <- yrbss %>%
summarise(freq = table(height)) %>%
summarise(n = sum(freq, na.rm = TRUE))
height_upper <- mean_height + 1.96*(sd_height/sqrt(sample_height))
height_lower <- mean_height - 1.96*(sd_height/sqrt(sample_height))
c(height_lower,height_upper, height_upper - height_lower)## $n
## [1] 1.689411
##
## $n
## [1] 1.693071
##
## $n
## [1] 0.003659302
ANSWER:
We are 95% confident that the average height of the students in this population is between 1.689 and 1.693
- Calculate a new confidence interval for the same parameter at the 90% confidence level. Comment on the width of this interval versus the one obtained in the previous exercise.
t <- 1.645
upper_90 <- mean_height + t*(sd_height/sqrt(sample_height))
lower_90 <- mean_height - t*(sd_height/sqrt(sample_height))
print(c(lower_90, upper_90, upper_90- lower_90))## $n
## [1] 1.689705
##
## $n
## [1] 1.692777
##
## $n
## [1] 0.0030712
ANSWER: The 95% CI has a larger range than the 90% CI
- Conduct a hypothesis test evaluating whether the average height is different for those who exercise at least three times a week and those who don’t.
Null Hypothesis:
There is no difference in the average height of those who are physically active at least 3 days per week and those who are not.
Alternative hypothesis:
There is a difference in the average height of those who are physically active at least 3 days per week and those who are not.
obs_diff_h <- yrbss %>%
specify(height ~ physical_3plus) %>%
calculate(stat = "diff in means", order = c("yes", "no"))
null_dist_h <- yrbss %>%
specify(height ~ physical_3plus) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "diff in means", order = c("yes", "no"))
null_dist_h %>%
get_p_value(obs_stat = obs_diff_h, direction = "two_sided")ANSWER:
with a p value of 0, we will reject the null hypothesis in favor of the alternate hypothesis. There is a statistically significant difference in the average height of those that are physically active and those who are not.
- Now, a non-inference task: Determine the number of different options there are in the dataset for the
hours_tv_per_school_daythere are.
length(unique(yrbss$hours_tv_per_school_day))## [1] 8
- Come up with a research question evaluating the relationship between height or weight and sleep. Formulate the question in a way that it can be answered using a hypothesis test and/or a confidence interval. Report the statistical results, and also provide an explanation in plain language. Be sure to check all assumptions, state your \(\alpha\) level, and conclude in context.
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" "physical_3plus"
unique(yrbss$helmet_12m)
Null Hypothesis:
The average height of students has no affect on the average number of hours of sleep students receive on school nights.
Alternative hypothesis:
The average height of students has an affect on the average number of hours of sleep students receive on school nights.
aov.out <- aov(data=yrbss, height ~ school_night_hours_sleep )
summary(aov.out)## Df Sum Sq Mean Sq F value Pr(>F)
## school_night_hours_sleep 6 0.17 0.02776 2.538 0.0186 *
## Residuals 11474 125.49 0.01094
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 2102 observations deleted due to missingness
Conclusion:
With a p-value below 0.05, we will reject the P-value and accept the alternate hypothesis that height affects hours of sleep.