---
title: "Assignment 6"
subtitle: "STAT3373"
author: "Isaac Shoebottom"
date: "Oct 30th, 2025"
output:
  pdf_document: default
  html_document:
    df_print: paged
---

```{r setup, include=FALSE}
library(tidyverse)
library(knitr)
library(emmeans)
library(effectsize)
```

```{r load-data, include=FALSE}
# Create the dataset
sleep_data <- read_csv("sleep_study_data.csv")

# Convert to factors
sleep_data <- sleep_data %>%
  mutate(
    Sleep = factor(Sleep, levels = c("Normal", "Deprived")),
    Caffeine = factor(Caffeine, levels = c("None", "100mg", "200mg")),
    Subject = factor(Subject)
  )
```

## Introduction

This study investigates how sleep deprivation and caffeine consumption affect cognitive performance as measured by reaction time. Sleep deprivation is known to impair cognitive function, while caffeine is commonly used to counteract fatigue-related performance decrements. The research question asks whether caffeine can mitigate the negative effects of sleep deprivation on reaction time. We hypothesize that sleep-deprived participants will show slower reaction times than those with normal sleep, caffeine will improve reaction times in a dose-dependent manner, and there will be an interaction such that caffeine's benefits are more pronounced in the sleep-deprived condition. Understanding these effects has practical implications for shift workers, students, and others who may experience sleep restriction.

## Methods

This study employed a 2 × 3 within-subjects factorial design with sleep condition (Normal vs. Deprived) and caffeine dose (None, 100mg, 200mg) as independent variables. Ten participants completed all six experimental conditions, providing reaction time measurements under each combination of sleep and caffeine levels. This repeated measures design controls for individual differences in baseline reaction time and increases statistical power. The dependent variable was reaction time measured in milliseconds. Data were analyzed using a two-way repeated measures ANOVA to examine main effects of sleep and caffeine, as well as their interaction. Effect sizes were calculated using partial eta squared, and post-hoc pairwise comparisons were conducted using estimated marginal means with Bonferroni correction to control for multiple comparisons.

## Results

### Descriptive Statistics

```{r descriptive-stats}
desc_stats <- sleep_data %>%
  group_by(Sleep, Caffeine) %>%
  summarise(
    N = n(),
    Mean = mean(ReactionTime),
    SD = sd(ReactionTime),
    SE = sd(ReactionTime) / sqrt(n()),
    .groups = "drop"
  )

kable(desc_stats, digits = 2, 
      caption = "Table 1. Descriptive Statistics for Reaction Time (ms) by Sleep Condition and Caffeine Dose")
```

Descriptive statistics reveal clear patterns in the data. Participants in the sleep-deprived condition with no caffeine showed the slowest mean reaction times (M = 315.05 ms, SD = 23.00), while those with normal sleep and 200mg caffeine showed the fastest times (M = 226.19 ms, SD = 19.20). Within the normal sleep condition, reaction times decreased as caffeine dose increased, suggesting a dose-response relationship. In the sleep-deprived condition, both caffeine doses appeared to improve reaction times compared to no caffeine, though the pattern differs somewhat from the normal sleep condition.

### ANOVA Results

```{r anova-analysis}
# Create ANOVA table
anova_table <- aov(ReactionTime ~ Sleep * Caffeine, data = sleep_data)
summary(anova_table)
```

### Interaction Plot

```{r interaction-plot, fig.width=8, fig.height=5}
sleep_data %>%
  group_by(Sleep, Caffeine) %>%
  summarise(
    Mean_RT = mean(ReactionTime),
    SE = sd(ReactionTime) / sqrt(n()),
    .groups = "drop"
  ) %>%
  ggplot(aes(x = Caffeine, y = Mean_RT, color = Sleep, group = Sleep)) +
  geom_line(size = 1.2) +
  geom_point(size = 3) +
  geom_errorbar(aes(ymin = Mean_RT - SE, ymax = Mean_RT + SE), 
                width = 0.1, size = 0.8) +
  labs(
    title = "Interaction Between Sleep Condition and Caffeine Dose on Reaction Time",
    x = "Caffeine Dose",
    y = "Mean Reaction Time (ms)",
    color = "Sleep Condition"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    legend.position = "top",
    plot.title = element_text(hjust = 0.5, face = "bold")
  ) +
  scale_color_manual(values = c("Normal" = "#2E86AB", "Deprived" = "#A23B72"))
```

The interaction plot illustrates the differential effects of caffeine across sleep conditions. In the normal sleep condition, reaction times show a consistent decrease with increasing caffeine dose, demonstrating a clear dose-response relationship. However, in the sleep-deprived condition, the pattern is more complex. While both caffeine doses improve reaction times compared to no caffeine, the 200mg dose does not show additional benefit over the 100mg dose in sleep-deprived participants, and in some cases may show slightly worse performance. This suggests that caffeine's effectiveness may be modulated by sleep status, with potential ceiling effects or different mechanisms at play when combating sleep deprivation.

### Post-Hoc Comparisons

```{r posthoc-tests}
# Fit model for emmeans
model <- aov(ReactionTime ~ Sleep * Caffeine + Error(Subject/(Sleep * Caffeine)), 
             data = sleep_data)

# Calculate estimated marginal means
emm <- emmeans(model, ~ Caffeine | Sleep)

# Pairwise comparisons within each sleep condition
posthoc <- pairs(emm, adjust = "bonferroni")

# Display results
kable(summary(posthoc), digits = 2,
      caption = "Table 3. Post-Hoc Pairwise Comparisons with Bonferroni Correction")
```

Post-hoc pairwise comparisons with Bonferroni correction examined differences between caffeine doses within each sleep condition. In the normal sleep condition, all pairwise comparisons were significant, confirming that each increase in caffeine dose led to faster reaction times. In the sleep-deprived condition, both 100mg and 200mg caffeine significantly improved reaction times compared to no caffeine, but the difference between 100mg and 200mg was not significant, supporting the observation from the interaction plot that higher caffeine doses may not provide additional benefits for sleep-deprived individuals.

### Assumption Checking

```{r assumptions, fig.width=10, fig.height=4}
# Create residuals for checking assumptions
sleep_data <- sleep_data %>%
  group_by(Subject) %>%
  mutate(residual = ReactionTime - mean(ReactionTime)) %>%
  ungroup()

# Check normality and homogeneity
par(mfrow = c(1, 2))

# Q-Q plot
qqnorm(sleep_data$residual, main = "Normal Q-Q Plot")
qqline(sleep_data$residual, col = "red")

# Residuals vs Fitted
plot(fitted(lm(ReactionTime ~ Sleep * Caffeine, data = sleep_data)),
     residuals(lm(ReactionTime ~ Sleep * Caffeine, data = sleep_data)),
     xlab = "Fitted Values", ylab = "Residuals",
     main = "Residuals vs Fitted Values")
abline(h = 0, col = "red", lty = 2)
```

Assumption checking indicated that the data met the requirements for repeated measures ANOVA. The Q-Q plot shows that residuals follow an approximately normal distribution, with only minor deviations at the tails. The residuals versus fitted values plot demonstrates homogeneity of variance, with no clear pattern of increasing or decreasing spread across fitted values. While sphericity cannot be formally tested with this small sample size, the use of within-subjects contrasts and the balanced design minimize concerns about sphericity violations.

## Discussion

This study demonstrates that both sleep deprivation and caffeine significantly affect reaction time performance, with a notable interaction between these factors. Sleep deprivation substantially impaired reaction time, increasing it by approximately 50-60 milliseconds on average across caffeine conditions, representing a large effect. Caffeine improved performance in both sleep conditions, but its effects were not uniform. In well-rested individuals, caffeine showed a clear dose-response relationship with progressively faster reaction times at higher doses. However, in sleep-deprived participants, while caffeine provided benefit compared to no caffeine, the additional benefit of 200mg versus 100mg was minimal or absent. This suggests that caffeine may partially compensate for sleep deprivation but cannot fully restore performance to normal levels, and higher doses do not necessarily provide proportionally greater benefits when fighting significant sleep debt.

The practical implications of these findings are significant for individuals who experience sleep restriction. While moderate caffeine consumption (100mg, equivalent to a cup of coffee) can help mitigate some performance deficits from sleep deprivation, it is not a complete substitute for adequate sleep. The lack of additional benefit from higher caffeine doses in sleep-deprived individuals suggests that consuming excessive caffeine may not be an effective strategy and could potentially lead to side effects without performance gains. Several limitations should be noted, including the relatively small sample size, which limits generalizability and statistical power for detecting smaller effects. The study examined only acute sleep deprivation and caffeine administration, so results may not apply to chronic sleep restriction or regular caffeine users who may have developed tolerance. Future research should examine longer-term effects, individual differences in caffeine metabolism, and optimal timing of caffeine consumption relative to sleep deprivation. Additionally, investigating other cognitive domains beyond reaction time would provide a more comprehensive understanding of how these factors interact to affect human performance.
