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 cases in this dataset refers to the individual high schoolers and there are 13,583 cases within this dataset.

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

There are 1004 observations we are 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"))
  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

I expected the population that exercised more than 3 times a week would weigh less on average than those who don’t but it doesn’t.

boxplot( weight~physical_3plus , data = yrbss)

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

Conditions for inference to be satisfied is that all cases must be independent from each other and also that the data follows a normal distribution.

  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

H0: Students who are physically active 3 or more days per week have the same average weight as those who don’t exercise 3 times a week. HA: Students who are physically active 3 or more days per week have a different average weight than those who don’t exercise 3 times a 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 %>%
  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"))

null_dist
## Response: weight (numeric)
## Explanatory: physical_3plus (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.454
##  2         2 -0.321
##  3         3  0.526
##  4         4  0.171
##  5         5 -0.359
##  6         6 -0.198
##  7         7  0.313
##  8         8  0.128
##  9         9  0.176
## 10        10 -0.130
## # ℹ 990 more rows

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

There are none of these permutations

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

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.
## get sd for both values, 17.6 for no and 16.5 for yes
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
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
mean_no <- 66.67389
size_no <- 4022
sd_no <- 17.63805
mean_yes <- 68.44847
size_yes <- 8342
sd_yes <- 16.47832

z = 1.96

up_no <- mean_no + z*(sd_no/sqrt(size_no))
low_not <- mean_no - z*(sd_no/sqrt(size_no))
up_no
## [1] 67.219
low_not
## [1] 66.12878
u_ci <- mean_yes + z*(sd_yes/sqrt(size_yes))
l_ci <- mean_yes - z*(sd_yes/sqrt(size_yes))

u_ci
## [1] 68.80209
l_ci
## [1] 68.09485

More Practice

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

Insert your answer here

The confidence interval is 1.69

avg_height_95 <- yrbss %>%
  drop_na(height) %>% # Drop missing values
  specify(response = height) %>%
  generate(reps = 1000, type = "bootstrap") %>%
  calculate(stat = "mean") %>%
  get_ci(level = 0.95)
avg_height_95
## # A tibble: 1 × 2
##   lower_ci upper_ci
##      <dbl>    <dbl>
## 1     1.69     1.69
  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

avg_height_90 <- yrbss %>%
  drop_na(height) %>% # Drop missing values
  specify(response = height) %>%
  generate(reps = 1000, type = "bootstrap") %>%
  calculate(stat = "mean") %>%
  get_ci(level = 0.90)
avg_height_90
## # A tibble: 1 × 2
##   lower_ci upper_ci
##      <dbl>    <dbl>
## 1     1.69     1.69
  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

obs_diff_height <- yrbss %>%
  filter(!is.na(height) & !is.na(physical_3plus)) %>%
  specify(height ~ physical_3plus) %>%
  calculate(stat = "diff in means", order = c("yes", "no"))

obs_diff_height
## Response: height (numeric)
## Explanatory: physical_3plus (factor)
## # A tibble: 1 × 1
##     stat
##    <dbl>
## 1 0.0376
null_dist_height <- yrbss %>%
  drop_na(physical_3plus) %>%
  specify(height ~ physical_3plus) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "diff in means", order = c("yes", "no"))

null_dist_height 
## Response: height (numeric)
## Explanatory: physical_3plus (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate      stat
##        <int>     <dbl>
##  1         1  0.000484
##  2         2  0.00307 
##  3         3  0.00141 
##  4         4 -0.00336 
##  5         5 -0.00418 
##  6         6  0.00233 
##  7         7  0.00522 
##  8         8 -0.00218 
##  9         9 -0.000419
## 10        10  0.00141 
## # ℹ 990 more rows
null_dist_height %>% 
 get_p_value(obs_stat = obs_diff_height, direction = "two_sided")
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
  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

Excluding the NA from our observatons there are 7 different options within our dataset.

unique(yrbss$hours_tv_per_school_day)
## [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

H0 - There is no difference in average height for those who sleep more than 7+ hours than those who sleep less than 7 hours per day HA - There is a difference in average height for those who sleep more than 7+ hours than those who sleep less than 7 hours per day

yrbss <- yrbss %>% 
  mutate(sleep_7plus = ifelse(yrbss$school_night_hours_sleep > 7, "yes", "no"))
yrbss %>%
  group_by(sleep_7plus) %>%
  summarise(mean_height = mean(height, na.rm = TRUE))
## # A tibble: 3 × 2
##   sleep_7plus mean_height
##   <chr>             <dbl>
## 1 no                 1.69
## 2 yes                1.69
## 3 <NA>               1.70
obs_diff_height2 <- yrbss %>%
  drop_na(sleep_7plus) %>%
  specify(height ~ sleep_7plus) %>%
  calculate(stat = "diff in means", order = c("yes", "no"))

obs_diff_height
## Response: height (numeric)
## Explanatory: physical_3plus (factor)
## # A tibble: 1 × 1
##     stat
##    <dbl>
## 1 0.0376
null_dist_height2 <- yrbss %>%
  drop_na(sleep_7plus) %>%
  specify(height ~ sleep_7plus) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "diff in means", order = c("yes", "no"))

null_dist_height
## Response: height (numeric)
## Explanatory: physical_3plus (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate      stat
##        <int>     <dbl>
##  1         1  0.000484
##  2         2  0.00307 
##  3         3  0.00141 
##  4         4 -0.00336 
##  5         5 -0.00418 
##  6         6  0.00233 
##  7         7  0.00522 
##  8         8 -0.00218 
##  9         9 -0.000419
## 10        10  0.00141 
## # ℹ 990 more rows
ggplot(data = null_dist_height2, aes(x = stat)) +
  geom_histogram()

yrbss <- yrbss %>%
  mutate(sleep_less = ifelse(yrbss$school_night_hours_sleep < 6, "yes", "no"))
 
height_less <- yrbss %>% 
  select(height, sleep_less) %>% 
  filter(sleep_less == "no") %>%
  na.omit()

height_more <- yrbss %>% 
  select(height, sleep_less) %>% 
  filter(sleep_less == "yes") %>%
  na.omit()
mn <- mean(height_less$height)
sd <- sd(height_less$height)
max <- max(height_less$height)

mn1 <- mean(height_more$height)
sd2 <- sd(height_more$height)
max2 <- max(height_more$height)

meandiff <- mn1 - mn

sd <- sqrt(
  ((mn1^2) / nrow(height_more)) +
  ((mn^2) / nrow(height_less))
)

df <- 2492 - 1
t <- qt(0.05/2, df, lower.tail = FALSE)

u <- meandiff + t * sd
l <- meandiff - t * sd

pv <- 2 * pt(t, df, lower.tail = FALSE)

u
## [1] 0.06780798
l
## [1] -0.08195098
pv
## [1] 0.05

because we have a p value of 0.05 we can reject the null hypothesis * * *