PSYC 215: Homework Assignment 3

Exploratory Data Analysis & Visual Deconstruction of Repeated-Measures Data (Chapter 5)

Author

Nathalie Jimenez

Published

November 1, 2026

Assignment Overview & Instructions

Purpose

In this assignment, you will conduct an exploratory data analysis (EDA) on repeated-measures data from Chapter 5 (The Rat Brain Study) of Linear Mixed Models: A Practical Guide Using Statistical Software (3rd Ed.).

The primary objective is to visually deconstruct the data hierarchy, fixed effects, and random effects before fitting any inferential Linear Mixed Models (LMMs). By creating targeted visualizations and descriptive summary tables, you will gain an intuitive, geometric understanding of how population trends and individual-level variations manifest in repeated-measures research designs.

Important Rule: Do NOT run inferential LME models (e.g., lmer() or lme()) in this assignment. Focus entirely on descriptive statistics (tidyverse) and data visualizations (ggplot2).

The 4-Step AI Vibe Coding Workflow & Principles

When using AI co-pilots (ChatGPT, Claude, Gemini) to assist with R coding:

  1. Specify Data Structure & Tools: Provide the exact dataframe name (rat_brain_long), column names (animal, treatment, region, activate), and target R libraries (tidyverse, ggplot2, gridExtra).
  2. State Objective & Graph Specifications: Clearly specify the desired visual geometry or tabular structure (e.g., grouped boxplots, 2-factor interaction line plot, faceted individual trajectory plots, or a \(6 \times 6\) correlation matrix).
  3. Run & Debug Iteratively: Execute the code in your R code chunk. If R returns syntax errors or warnings, paste the exact console error message back into the AI to resolve it.
  4. Refine & Interpret: Polish visual aesthetics (clear axis labels, legends, titles) and answer the conceptual interpretation questions directly under each output chunk.

Global Setup & Data Ingestion

The chunk below creates and cleans the Rat Brain dataset (\(N = 30\) observations: 5 adult male rats measured across 2 treatment conditions and 3 brain regions).

# Load required libraries
library(tidyverse)
library(gridExtra)

# Set global publication-quality theme
theme_set(theme_minimal(base_size = 12) +
          theme(panel.grid.minor = element_blank(),
                plot.title = element_text(face = "bold", size = 13),
                plot.subtitle = element_text(color = "grey30", size = 11),
                strip.text = element_text(face = "bold", size = 11)))

# Construct Rat Brain dataset (Chapter 5) in wide format
rat_brain_wide <- data.frame(
  animal = c("R111097", "R111397", "R100797", "R100997", "R110597"),
  Basal_BST = c(366.19, 375.58, 458.16, 479.81, 462.79),
  Basal_LS  = c(199.31, 204.85, 245.04, 261.19, 278.33),
  Basal_VDB = c(187.11, 179.38, 237.42, 195.51, 262.05),
  Carb_BST  = c(371.71, 492.58, 664.72, 515.29, 589.25),
  Carb_LS   = c(302.02, 355.74, 587.10, 437.56, 493.93),
  Carb_VDB  = c(449.70, 459.58, 726.96, 604.29, 621.07)
)

# Reshape into long format for LMM & visualization
rat_brain_long <- rat_brain_wide %>%
  pivot_longer(
    cols = -animal,
    names_to = c("treatment", "region"),
    names_sep = "_",
    values_to = "activate"
  ) %>%
  mutate(
    animal = factor(animal),
    treatment = factor(treatment, levels = c("Basal", "Carb"), labels = c("Basal", "Carbachol")),
    region = factor(region, levels = c("VDB", "LS", "BST")) # VDB as baseline reference
  )

# Preview clean long dataframe
head(rat_brain_long, 12)
# A tibble: 12 × 4
   animal  treatment region activate
   <fct>   <fct>     <fct>     <dbl>
 1 R111097 Basal     BST        366.
 2 R111097 Basal     LS         199.
 3 R111097 Basal     VDB        187.
 4 R111097 Carbachol BST        372.
 5 R111097 Carbachol LS         302.
 6 R111097 Carbachol VDB        450.
 7 R111397 Basal     BST        376.
 8 R111397 Basal     LS         205.
 9 R111397 Basal     VDB        179.
10 R111397 Carbachol BST        493.
11 R111397 Carbachol LS         356.
12 R111397 Carbachol VDB        460.

Section 1: Data Hierarchy & Descriptive Summary

Theoretical Context

Repeated-measures data represent a two-level hierarchical structure where Level 2 represents the subjects (\(N = 5\) rats) and Level 1 represents the repeated measurements (\(n = 6\) observations per rat) collected under varying experimental conditions.

Required Analysis & Data Output

Compute a comprehensive descriptive summary table displaying the sample mean, standard deviation, minimum, and maximum of nucleotide activation (activate) grouped across all combinations of treatment (Basal vs. Carbachol) and region (VDB, LS, BST).

# Compute descriptive summary statistics for activation by treatment and region
summary_table <- rat_brain_long %>%
  group_by(treatment, region) %>%
  summarise(
    Mean = mean(activate, na.rm = TRUE),
    SD   = sd(activate, na.rm = TRUE),
    Min  = min(activate, na.rm = TRUE),
    Max  = max(activate, na.rm = TRUE),
    .groups = "drop"
  )

# Display the formatted table using knitr/kable for clean rendering in Quarto
knitr::kable(summary_table, digits = 2, caption = "Summary Statistics of Nucleotide Activation by Treatment and Brain Region")
Summary Statistics of Nucleotide Activation by Treatment and Brain Region
treatment region Mean SD Min Max
Basal VDB 212.29 35.73 179.38 262.05
Basal LS 237.74 34.67 199.31 278.33
Basal BST 428.51 53.32 366.19 479.81
Carbachol VDB 572.32 117.32 449.70 726.96
Carbachol LS 435.27 112.45 302.02 587.10
Carbachol BST 526.71 109.86 371.71 664.72

Written Response Questions (Section 1)

  • Question 1a (Data Hierarchy & Variables): Identify the Level-2 unit of analysis, the Level-1 within-subject fixed factors, and the dependent variable in the Rat Brain dataset. Explain why this design is considered a “crossed within-subject repeated-measures design.”

    While the level 1 units would be the individual measurements of nucleotide activation, the level-2 unit of analysis would be the five individual rats because they are measured repeatedly across conditions.Because measurements within the same subject are correlated, this makes the individual rat the level-2 unit. Level-1 within subjects factors are variables in which multiple measurements are taken at the same level-2 unit (here, the rat subject) across different conditions, time points, and or treatments. Within this data set, the level-1 within subject factors are treatment and brain region. Each of the five rates are measured under both experimental treatments (Basal and Carbachol) as well as measured across all three brain regions (VDB, LS, and BST). Since every rat undergoes every combination of treatment x brain region, they both operate as level-1 within-subjects factors nested within the individual animal. As previously stated, the individual animal acts as our Level-2 unit of analysis. The dependent variable is nucleotide activation, which is labeled as activation in our dataframe. Nucleotide activation is observed in the brain regions, and acts as our quantitative measure of how the different sections of the brain respond under the various treatments across VDB, LS, and BST. This design is considered a crossed-within subject repeated measures design for three reasons: every single rat is measured across all six conditions rather than being restricted to only one treatment, there are two factors- treatment and brain region- that are fully crossed, creating six experimental conditions, and because all six of these activation measurements are taken within the same rat.

  • Question 1b (Descriptive Trends & Dispersion): Based on your summary table above, compare the mean activation and standard deviations between the Basal and Carbachol treatment conditions. What happens to the variability (spread) of optical density measurements under Carbachol treatment?

    Across all three brain regions, Carbachol treatment produced a substantial increase in average nucleotide activation compared to Basal conditions. However, the magnitude of this effect varied by region. In VDB and LS, activation increases dramatically under Carbachol (VDB: \(212.29 \rightarrow 572.32\); LS: \(237.74 \rightarrow 435.27\)).In BST, baseline activation under Basal conditions is already markedly higher (\(\text{Mean} = 428.51\)) compared to VDB and LS. Consequently, while Carbachol increases activation further (\(\text{Mean} = 526.71\)), the relative difference is smaller, suggesting that the BST region maintains a naturally higher baseline level of metabolic reactivity. The Standard deviation within the Carbachol treatment for all three brain regions is significantly higher than the standard deviation for the brain regions in the Basal treatment. This dramatic increase in spread under Carbachol indicates heteroscedasticity (non-constant variance across treatment strata). It suggests that rats exhibit individual differences in their responsiveness to Carbachol stimulation. In linear mixed-effects modeling, this pattern justifies specifying a heteroscedastic error variance structure (e.g., varIdent(form = ~ 1 | treatment)) to model the treatment-specific dispersion accurately.


Section 2: Visualizing Fixed Effects (Treatment, Region, & Interaction)

Theoretical Context

In an LMM, fixed effects describe population-averaged relationships between predictors and the outcome. In the Rat Brain study, the fixed structure includes main effects for treatment (\(\beta_{\text{treat}}\)), region (\(\beta_{\text{region}}\)), and the treatment \times region interaction (\(\beta_{\text{treat} \times \text{region}}\)).

Required Analysis & Data Output

Construct a publication-quality 2-panel figure:

  • Panel A (Main Effects): Grouped boxplots of activate across region, color-coded by treatment (Basal vs. Carbachol), illustrating main effect differences.
  • Panel B (Interaction Plot): A 2-factor mean interaction line plot showing mean activate versus region with separate lines for Basal and Carbachol, illustrating whether the drug effect varies across brain regions.
library(ggplot2)
library(dplyr)
library(gridExtra)

# Set custom color palette for treatments
treatment_colors <- c("Basal" = "#2b5c8f", "Carbachol" = "#d95f02")

# -----------------------------------------------------------------------------
# Panel A: Main Effects (Grouped Boxplots)
# -----------------------------------------------------------------------------
panel_a <- ggplot(rat_brain_long, aes(x = region, y = activate, fill = treatment)) +
  geom_boxplot(alpha = 0.7, outlier.size = 2, position = position_dodge(width = 0.8)) +
  geom_jitter(aes(color = treatment), position = position_dodge(width = 0.8), size = 1.8, alpha = 0.6) +
  scale_fill_manual(values = treatment_colors) +
  scale_color_manual(values = treatment_colors) +
  labs(
    title = "Panel A: Nucleotide Activation by Region & Treatment",
    x = "Brain Region",
    y = "Nucleotide Activation (activate)",
    fill = "Treatment",
    color = "Treatment"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(face = "bold", size = 12),
    legend.position = "top",
    panel.grid.minor = element_blank()
  )

# -----------------------------------------------------------------------------
# Panel B: Interaction Plot (Mean Lines + Error Bars)
# -----------------------------------------------------------------------------
# Calculate means and standard errors for the interaction plot
interaction_summary <- rat_brain_long %>%
  group_by(treatment, region) %>%
  summarise(
    mean_act = mean(activate, na.rm = TRUE),
    se_act   = sd(activate, na.rm = TRUE) / sqrt(n()),
    .groups  = "drop"
  )

panel_b <- ggplot(interaction_summary, aes(x = region, y = mean_act, color = treatment, group = treatment)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3.5) +
  geom_errorbar(aes(ymin = mean_act - se_act, ymax = mean_act + se_act), width = 0.15, linewidth = 0.8) +
  scale_color_manual(values = treatment_colors) +
  labs(
    title = "Panel B: Mean Nucleotide Activation Profiles Across Treatment and Region",
    x = "Brain Region",
    y = "Mean Activation (± SE)",
    color = "Treatment"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(face = "bold", size = 12),
    legend.position = "top",
    panel.grid.minor = element_blank()
  )

# -----------------------------------------------------------------------------
# Combine Panels Side-by-Side
# -----------------------------------------------------------------------------
grid.arrange(panel_a, panel_b, ncol = 2)

Written Response Questions (Section 2)

  • Question 2a (Treatment & Region Main Effects): Based on your plots above, describe the overall main effect of drug treatment (Carbachol vs. Basal) and the main effect of brain region on nucleotide activation.

    Overall, Carbachol was shown to have a higher rate of nucleotide activation compared to Basal. The means for Basal in Panel A are shown visually to be significantly smaller than the means for Carbachol. However, the spread is much more evenly dispersed in the Basal grouping regarding nucleotide activation. Carbachol showed a much wider spread with higher variance in activation levels across subjects. The brain regions differs significantly in their overall activation levels regardless of treatment condition. The BST region was shown to exhibit the highest overall activation in under both treatments, whereas the VDB and LS regions displayed lower rates. Of the three brain regions, VDB displayed the lowest activation overall.

  • Question 2b (Interaction Pattern Mapping): Examine the slopes in Panel B. Does the effect of Carbachol drug stimulation operate identically across all three brain regions? Identify which brain region displays the largest activation boost under Carbachol versus Basal.

    In terms of brain region, it may be that the BST has a higher baseline of nucleotide activation, which is why the difference between treatment groups was significantly smaller there. While Carbachol still showed higher activation than Basal in the BST region, this smaller relative change may be because the higher baseline makes a larger incremental increase more difficult to reach. Conversely, the region with the largest activation boost was the VDB, given the substantial difference between the means of Carbachol and Basal in that region.


Section 3: Visualizing Random Effects (Between-Animal Variability)

Theoretical Context

Random effects capture subject-specific stochastic deviations from the population average. In Chapter 5, the model incorporates two random animal effects:

  1. Random Intercepts (\(u_{0i} \sim N(0, \sigma^2_{\text{int}})\)): Baseline differences in rat activation under control conditions.
  2. Random Treatment Slopes (\(u_{3i} \sim N(0, \sigma^2_{\text{treat}})\)): Differences among rats in their individual responsiveness to Carbachol.

Required Analysis & Data Output

Create individual animal trajectory plots (“spaghetti plots”) displaying activate values for each rat (animal) from Basal to Carbachol, faceted by brain region (region). Ensure individual rat lines are distinctly colored and labeled so you can track subject trajectories.

library(ggplot2)
library(dplyr)

# -----------------------------------------------------------------------------
# Individual Animal Trajectory Plots ("Spaghetti Plots")
# -----------------------------------------------------------------------------

ggplot(rat_brain_long, aes(x = treatment, y = activate, group = animal, color = animal)) +
  # Connect repeated measurements for each individual rat with trajectory lines
  geom_line(linewidth = 0.9, alpha = 0.85) +
  geom_point(size = 2.5) +
  # Add rat ID labels at the Carbachol end of each trajectory line for clear tracking
  geom_text(
    data = rat_brain_long %>% filter(treatment == "Carbachol"),
    aes(label = animal),
    hjust = -0.25,
    vjust = 0.5,
    size = 3.3,
    fontface = "bold",
    show.legend = FALSE
  ) +
  # Facet by brain region to examine regional heterogeneity
  facet_wrap(~ region, scales = "fixed") +
  # Adjust x-axis limits slightly to make room for animal text labels
  scale_x_discrete(expand = expansion(mult = c(0.15, 0.35))) +
  labs(
    title = "Individual Rat Activation Trajectories Across Treatments",
    subtitle = "Faceted by Brain Region (VDB, LS, BST)",
    x = "Treatment Condition",
    y = "Nucleotide Activation (activate)",
    color = "Rat ID (animal)"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(face = "bold", size = 11),
    plot.subtitle = element_text(color = "grey30", size = 11),
    strip.text = element_text(face = "bold", size = 11),
    legend.position = "right",
    panel.grid.minor = element_blank()
  )

Written Response Questions (Section 3)

  • Question 3a (Baseline Random Intercepts \(u_{0i}\)): Inspect the starting points of individual rat lines in the Basal condition (\(t=0\)). Do all rats begin at the same baseline activation level? How does this visual spread justify adding a Level-2 random intercept (\(u_{0i}\))?

    No, the rats do not begin at the same baseline activation level. Across all three brain regions under the Basal condition, there is a visible vertical spread among the individual lines, indicating that different subjects possess unique baseline levels of activation (rats R100797 and R110597 start higher, while R111097 and R111397 start lower).This subject variability thus justifies adding a Level-2 random intercept \(u_{0i}\). The random intercept allows the model to accommodate these individual baseline shifts around the overall population mean, accounting for the inherent correlation of repeated measures taken on the same animal..

  • Question 3b (Random Treatment Slopes \(u_{3i}\)): Compare the slopes of individual rat lines going from Basal to Carbachol. Are the individual trajectories strictly parallel, or do some rats show steeper increases than others? Identify which specific rat shows the most extreme positive reaction to Carbachol.

    The individual rat trajectories are not strictly parallel. Indeed, some rats exhibit much steeper increases from Basal to Carbachol than others. Specifically, R100797 (orange line) showed the most extreme positive reaction to Carbachol, which displayed the steepest overall slope—most dramatically in the VDB region, where it shot up from a baseline around 240 to over 700.Conversely, R111097 (blue line) consistently showed the smallest response across groups, most notably in the BST region where its trajectory was nearly flat, which indicated almost no change under drug stimulation. This visual variation in individual slopes (and baselines) directly justified incorporating a Level-2 random slope (\(u_{1i}\)) into your mixed-effects model to capture how individual animals uniquely respond to Carbachol treatment.


Section 4: Within-Subject Tracking & Marginal Correlation Structure

Theoretical Context

Because multiple measurements are taken from the same rat, repeated observations are correlated. The implied marginal covariance matrix (\(\mathbf{V}_i = \mathbf{Z}_i \mathbf{D} \mathbf{Z}_i^\top + \mathbf{R}_i\)) describes total variance and correlation among repeated measures.

Required Analysis & Data Output

Compute and visualize:

  1. An empirical \(6 \times 6\) correlation matrix (or heatmap) across all 6 repeated-measure conditions (Basal_BST, Basal_LS, Basal_VDB, Carb_BST, Carb_LS, Carb_VDB).
  2. A subject profile tracking plot displaying activation levels across all 6 condition combinations for each rat, demonstrating subject rank-order consistency.
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)

# -----------------------------------------------------------------------------
# 1. Prepare Wide Data & Compute 6x6 Correlation Matrix
# -----------------------------------------------------------------------------
# Create short labels (e.g., Basal_BST, Carb_VDB) and pivot to wide format
rat_brain_wide <- rat_brain_long %>%
  mutate(
    cond_label = paste(
      ifelse(treatment == "Carbachol", "Carb", as.character(treatment)),
      region,
      sep = "_"
    )
  ) %>%
  select(animal, cond_label, activate) %>%
  pivot_wider(names_from = cond_label, values_from = activate)

# Compute 6x6 correlation matrix across the 6 condition columns
cor_matrix <- cor(rat_brain_wide %>% select(-animal), use = "pairwise.complete.obs")

# Convert matrix to long format for ggplot heatmap visualization
cor_df <- as.data.frame(cor_matrix) %>%
  mutate(Var1 = rownames(.)) %>%
  pivot_longer(-Var1, names_to = "Var2", values_to = "Correlation")

# -----------------------------------------------------------------------------
# 2. Panel A: 6x6 Correlation Heatmap
# -----------------------------------------------------------------------------
panel_a_cor <- ggplot(cor_df, aes(x = Var1, y = Var2, fill = Correlation)) +
  geom_tile(color = "white", linewidth = 0.5) +
  geom_text(aes(label = sprintf("%.2f", Correlation)), color = "black", size = 3.5) +
  scale_fill_gradient2(low = "#4575b4", mid = "#ffffbf", high = "#d73027", midpoint = 0.5, limits = c(-1, 1)) +
  labs(
    title = "Empirical 6×6 Correlation Matrix",
    x = "", y = "",
    fill = "r"
  ) +
  theme_minimal(base_size = 11) +
  theme(
    plot.title = element_text(face = "bold", size = 12),
    axis.text.x = element_text(angle = 45, hjust = 1, face = "bold"),
    axis.text.y = element_text(face = "bold"),
    panel.grid = element_blank()
  )

# -----------------------------------------------------------------------------
# 3. Panel B: Subject Profile Tracking Plot Across All 6 Conditions
# -----------------------------------------------------------------------------
# Define explicit ordering for the 6 condition combinations
condition_order <- c("Basal_VDB", "Basal_LS", "Basal_BST", "Carb_VDB", "Carb_LS", "Carb_BST")

tracking_data <- rat_brain_long %>%
  mutate(
    cond_label = factor(
      paste(ifelse(treatment == "Carbachol", "Carb", as.character(treatment)), region, sep = "_"),
      levels = condition_order
    )
  )

panel_b_tracking <- ggplot(tracking_data, aes(x = cond_label, y = activate, group = animal, color = animal)) +
  geom_line(linewidth = 1, alpha = 0.85) +
  geom_point(size = 2.5) +
  labs(
    title = "Subject Profile Tracking Across 6 Conditions",
    subtitle = "Demonstrating Subject Rank-Order Consistency",
    x = "Condition (Treatment_Region)",
    y = "Nucleotide Activation",
    color = "Rat ID"
  ) +
  theme_minimal(base_size = 11) +
  theme(
    plot.title = element_text(face = "bold", size = 12),
    plot.subtitle = element_text(color = "grey30", size = 9.5),
    axis.text.x = element_text(angle = 45, hjust = 1),
    legend.position = "right",
    panel.grid.minor = element_blank()
  )

# -----------------------------------------------------------------------------
# Combine Plots Side-by-Side
# -----------------------------------------------------------------------------
grid.arrange(panel_a_cor, panel_b_tracking, ncol = 2, widths = c(1.1, 1.3))

Written Response Questions (Section 4)

  • Question 4a (Individual Subject Tracking): Do rats that display high activation in one brain region also tend to show high activation across other regions and treatments? What does this “tracking” phenomenon imply about the correlation among repeated measures within the same subject?

    Yes, rats that displayed high activation in one region tended to maintain high activation across other brain regions and treatment conditions (exhibiting strong rank-order consistency, as seen in the profile tracking plot where individual trajectories rarely cross). This tracking phenomenon implies, then, that repeated measurements taken on the same animal are strongly correlated. As a result, observations within a rat share unobserved subject-level characteristics, which formally justifies treating individual animals as Level-2 units in a hierarchical model.

  • Question 4b (Empirical Covariance & Variance Structure): Examine the calculated \(6 \times 6\) correlation matrix. Are the off-diagonal correlations positive or negative? Briefly explain why a simple single-level OLS model that ignores animal ID would violate independence assumptions.

    The off-diagonal correlations in the \(6 \times 6\) matrix were strongly positive (ranging roughly from \(0.64\) to \(0.98\)). A simple single-level model that ignores animal ID would violate the independence assumption because it would treat all 30 observations as completely independent data points. In reality, multiple measurements from the same rat share common subject-level random effects (such as unique baselines and response tendencies). Ignoring this clustering would cause standard errors to be underestimated, thus increasing the risk of false positives (Type I errors). Mixed-effects models resolve this by explicitly partitioning the variance into within-subject and between-subject components (\(\mathbf{V}_i = \mathbf{Z}_i \mathbf{D} \mathbf{Z}_i^\top + \mathbf{R}_i\)).


Section 5: AI Prompt Reflection

AI Prompt Reflection

Provide a brief 1-paragraph reflection addressing:

  1. Specific AI prompts used For Question one- To create the assigned summary table below, could you create me a code to enter into r? For Question 2- R code for the following: ### Required Analysis & Data Output Construct a publication-quality 2-panel figure: Panel A (Main Effects): Grouped boxplots of activate across region, color-coded by treatment (Basal vs. Carbachol), illustrating main effect differences. Panel B (Interaction Plot): A 2-factor mean interaction line plot showing mean activate versus region with separate lines for Basal and Carbachol, illustrating whether the drug effect varies across brain regions For Question 3- Please create a code for me to enter into R- Create individual animal trajectory plots (“spaghetti plots”) displaying activate values for each rat (animal) from Basal to Carbachol, faceted by brain region (region). Ensure individual rat lines are distinctly colored and labeled so you can track subject trajectories. For Question 4- Please review it and give me a code to be entered into r- Because multiple measurements are taken from the same rat, repeated observations are correlated. The implied marginal covariance matrix (\(\mathbf{V}_i = \mathbf{Z}_i \mathbf{D} \mathbf{Z}_i^\top + \mathbf{R}_i\)) describes total variance and correlation among repeated measures. An empirical \(6 \times 6\) correlation matrix (or heatmap) across all 6 repeated-measure conditions (Basal_BST, Basal_LS, Basal_VDB, Carb_BST, Carb_LS, Carb_VDB). A subject profile tracking plot displaying activation levels across all 6 condition combinations for each rat, demonstrating subject rank-order consistency.
  2. One code error/bug you encountered with ggplot2 or pivot_longer and how you resolved it. While building the subject profile tracking plot across all 6 conditions, I initially encountered an ordering issue with ggplot2 where the x-axis categories defaulted to alphabetical sorting rather than the intended experimental sequence (Basal conditions followed by Carbachol conditions). Rather than a syntax error crashing the code, the plot rendered with the conditions out of chronological order. I resolved this “visual bug” by explicitly wrapping the condition variable in a factor() function and manually defining the correct chronological vector using the levels = c(“Basal_VDB”, “Basal_LS”, “Basal_BST”, “Carb_VDB”, “Carb_LS”, “Carb_BST”) argument. This forced ggplot2 to respect the logical structure of the experimental design on the x-axis.
  3. How visual exploration helped you understand fixed and random effects before fitting formal LMMs.

Walking through Questions 2 and 3 provided a much more clear conceptual understanding of how fixed effects and subject-level random effects operate in tandem. Visualizing the data made it immediately apparent that the 30 observations are clustered within just 5 rats, with each animal acting as its own baseline and exhibiting unique responses to treatment. Seeing these subject-level variations—such as differences in starting baselines and their trajectory slopes—visually justified the need for Level-2 random intercepts and slopes before fitting formal linear mixed-effects models. Finally, the empirical correlation matrix and tracking plots in Question 4 helped fully synthesize how these individual trajectories translate into intra-subject correlation.