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)

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
  1. What are the cases in this data set? How many cases are there in our sample?

Insert your answer here The dataset comprises 13,583 observations of high school children and their self reported health indicators. The key metrics are physical activity frequency(strength training and general exercise), media consumption habits(amount of time watching tv), sleep patterns, and risk taking behaviors(helmet usage and texting while driving).

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
  1. How many observations are we missing weights from?

Insert your answer here

na_count <- sum(is.na(yrbss$weight))
print(na_count)
## [1] 1004

1004

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"))
  1. Make a side-by-side boxplot of physical_3plus and weight. Is there a relationship between these two variables? What did you expect and why?

Insert your answer here

ggplot(yrbss, aes(x = physical_3plus, y = weight)) +
  geom_boxplot() +
  labs(x = "physically active 3+ days", y = "weight", title = "Weight by physical activity levels boxplots") +
  theme_minimal()

The chart showed what I’d except. Athletes gemerally weight more than the average person since they have so much muscle mass and the extreme outliers were in the catageory that didn’t regularly excerise

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))
## # A tibble: 3 × 2
##   physical_3plus mean_weight
##   <chr>                <dbl>
## 1 no                    66.7
## 2 yes                   68.4
## 3 <NA>                  69.9

There is an observed difference, but is this difference statistically significant? In order to answer this question we will conduct a hypothesis test.

Inference

  1. Are all conditions necessary for inference satisfied? Comment on each. You can compute the group sizes with the summarize command above by defining a new variable with the definition n().

Insert your answer here To evaluate the validity of the inference, I calculated the group sizes, average weights, and standard deviations using the summarize command. All conditions for inference are satisfied based on the following criteria

  • Randomization: The data is sourced from the Youth Risk Behavior Surveillance System (YRBSS). As a CDC administered dataset, it utilizes a rigorous scientific survey design with random sampling, ensuring the sample is representative of the population.

  • Independence: Within group independence is assumed via the random sampling design. Between group independence is also satisfied, as the groups are defined by mutually exclusive activity levels (those who engage in physical activity => 3 times a week vs. those who do not), with no individual overlap.

  • Normality: While the underlying distribution of weight can be skewed, both group sizes are well above the n > 30 threshold. According to what I’ve read about the Central Limit Theorem, these large samples ensure the sampling distribution of the mean is approximately normal.

  • Equal Variance: The standard deviation for the “no” group (17.6) and the “yes” group (16.5) are sufficiently similar. This means that the variances are approximately equal.

Conclusion: All conditions are meet and the dataset is appropriate for performing statistical inference

  1. 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.

Insert your answer here Null Hypothesis (H0): There’s no difference in the average weight between students who exercise at least three times a week and those who do not.

Alternative Hypothesis (Ha): The average weight of students who exercise at least three times a week is significantly different from those who do not.

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 %>%
  drop_na(physical_3plus) %>%
  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 %>%
  drop_na(physical_3plus) %>%
  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()

  1. How many of these null permutations have a difference of at least obs_stat?

Insert your answer here

null_dist %>%
  get_p_value(obs_stat = obs_diff, direction = "two_sided")
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
visualize(null_dist) +
  shade_p_value(obs_stat = obs_diff, direction = "two_sided")

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")
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0

Since the P value is less than 0.05 we reject the null hypothesis.

This the standard workflow for performing hypothesis tests.

  1. 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.
#Standard Deviation
yrbss %>% 
  group_by(physical_3plus) %>% 
  summarise(sd_weight = sd(weight, na.rm = TRUE))
## # A tibble: 3 × 2
##   physical_3plus sd_weight
##   <chr>              <dbl>
## 1 no                  17.6
## 2 yes                 16.5
## 3 <NA>                17.6
#Mean
yrbss %>% 
  group_by(physical_3plus) %>% 
  summarise(mean_weight = mean(weight, na.rm = TRUE))
## # A tibble: 3 × 2
##   physical_3plus mean_weight
##   <chr>                <dbl>
## 1 no                    66.7
## 2 yes                   68.4
## 3 <NA>                  69.9
#Sample Size N
yrbss %>% 
  group_by(physical_3plus) %>% 
  summarise(freq = table(weight)) %>%
  summarise(n = sum(freq))
## # A tibble: 3 × 2
##   physical_3plus     n
##   <chr>          <int>
## 1 no              4022
## 2 yes             8342
## 3 <NA>             215
not_active_mean <- 66.7
not_active_sd <- 17.6
not_active_n <- 4022

active_mean <- 68.4
active_sd <- 16.5
active_n <- 8342
  
z <- 1.96

# confidence interval for not active
upper_not_active <- not_active_mean + z * (not_active_sd / sqrt(not_active_n))
upper_not_active
## [1] 67.24394
lower_not_active <- not_active_mean - z * (not_active_sd / sqrt(not_active_n))
lower_not_active
## [1] 66.15606
upper_active <- active_mean + z * (active_sd / sqrt(active_n))
upper_active
## [1] 68.75408
lower_active <- active_mean - z * (active_sd / sqrt(active_n))
lower_active
## [1] 68.04592

More Practice

  1. Calculate a 95% confidence interval for the average height in meters (height) and interpret it in context.

Insert your answer here

valid_heights <- yrbss[complete.cases(yrbss$height), ]

height_t_test <- t.test(valid_heights$height)

mean_height <- mean(valid_heights$height)

conf_interval <- height_t_test$conf.int

print(paste("The mean height is ", round(mean_height, 2),
            " meters. The 95% confidence interval is [", 
            round(conf_interval[1], 2), ", ", round(conf_interval[2], 2), 
            "] meters.", sep = ""))
## [1] "The mean height is 1.69 meters. The 95% confidence interval is [1.69, 1.69] meters."
  1. 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.

Insert your answer here

height_t_test_90 <- t.test(valid_heights$height, conf.level = 0.90)

# The 90% confidence interval 
conf_interval_90 <- height_t_test_90$conf.int

# Print the 90% confidence interval
print(paste("The 90% confidence interval for the average height is [", 
            round(conf_interval_90[1], 2), ", ", round(conf_interval_90[2], 2), 
            "] meters.", sep = ""))
## [1] "The 90% confidence interval for the average height is [1.69, 1.69] meters."
  1. 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.

Insert your answer here

group1 <- yrbss$height[yrbss$physical_3plus == "yes"]
group2 <- yrbss$height[yrbss$physical_3plus == "no"]

# Conduct a two-sample t-test
test_result <- t.test(group1, group2)

# Print the results
print(test_result)
## 
##  Welch Two Sample t-test
## 
## data:  group1 and group2
## t = 19.029, df = 7973.3, p-value < 2.2e-16
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  0.03374994 0.04150183
## sample estimates:
## mean of x mean of y 
##  1.703213  1.665587
  1. Now, a non-inference task: Determine the number of different options there are in the dataset for the hours_tv_per_school_day there are.

Insert your answer here

unique_values <- unique(yrbss$hours_tv_per_school_day)

print(unique_values)
## [1] "5+"           "2"            "3"            "do not watch" "<1"          
## [6] "4"            "1"            NA
  1. 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.

Insert your answer here