This function fits a linear mixed-effects model to assess how an outcome variable changes over time (or another continuous predictor). It returns a list containing the model, key statistics, and two plots: a spaghetti plot showing individual trajectories and a population-level plot showing the overall model fit.

analyze_longitudinal_change(
  data,
  outcome_var,
  predictor,
  covariates = NULL,
  random_effect = "eid",
  verbose = FALSE
)

Arguments

data

A data frame containing all necessary variables.

outcome_var

The name of the dependent variable (character string).

predictor

The name of the main continuous predictor, typically a time variable like "yearsbl" (character string).

covariates

A character vector of other fixed-effect covariates to include in the model.

random_effect

The name of the random intercept grouping variable, typically a subject ID like "eid" (character string).

verbose

A logical. If TRUE, the function will print the exact model formula being used. Defaults to FALSE.

Value

A list containing the lmer model object, Cohen's d for the main predictor, t-value, p-value, and two ggplot objects (spaghetti_plot and population_plot). Returns NULL if the model fails.

Examples

if (FALSE) { # \dontrun{
# Assuming `my_long_data` exists and has the necessary columns
result <- analyze_longitudinal_change(
  data = my_long_data,
  outcome_var = "CognitiveScore",
  predictor = "YearsFromBaseline",
  covariates = c("AgeAtBaseline", "Sex", "Education"),
  random_effect = "SubjectID",
  verbose = TRUE
)

# Display the generated plots side-by-side
if (!is.null(result)) {
  library(gridExtra)
  grid.arrange(result$spaghetti_plot, result$population_plot, ncol = 2)
}
} # }