This function fits a linear mixed-effects model to assess the relationship between a predictor and an outcome over time, while controlling for covariates. It returns the model object, key statistics, and two plots for visualization.

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

Arguments

data

A data frame containing the data.

outcome_var

A character string specifying the name of the outcome variable.

predictor

A character string specifying the main predictor of interest (e.g., "yearsbl").

covariates

A character vector of covariate names.

random_effect

A character string for the name of the random grouping factor (e.g., "eid").

Value

A list containing:

model

The fitted lmerMod object.

cohen_d

The calculated Cohen's d for the main predictor.

t_value

The t-statistic for the main predictor.

df

The degrees of freedom for the t-statistic.

p_value

The p-value for the main predictor.

spaghetti_plot

A ggplot object showing individual trajectories.

population_plot

A ggplot object showing the model-predicted population trajectory.

Returns NULL if the model fails to converge or an error occurs.

Examples

if (FALSE) { # \dontrun{
# Assuming `ukbbdL` is your data frame
result <- analyze_longitudinal_change(
  data = ukbbdL,
  outcome_var = "t1PC1",
  predictor = "yearsbl",
  covariates = c("Age", "Sex", "T1Hier_resnetGrade"),
  random_effect = "eid"
)
if (!is.null(result)) {
  gridExtra::grid.arrange(result$spaghetti_plot, result$population_plot, ncol = 2)
}
} # }