# Longitudinal Analysis > Longitudinal methods, made clear > Generated by All in One SEO Pro v5.0.5.1, this is an llms-full.txt file, used by LLMs to index the site. ## Posts ### [Guides](https://longitudinalanalysis.com/blog/) **Published:** February 2, 2024 **Author:** alexcernat **Content:** ## Longitudinal Analysis Guides - [![AI Agent for Data Analysis and Why You Need Taste](https://longitudinalanalysis.com/wp-content/uploads/2026/07/ChatGPT-Image-Jul-10-2026-11_40_31-AM.webp)](https://longitudinalanalysis.com/ai-agent-for-data-analysis-and-why-you-need-taste/) ## [AI Agent for Data Analysis and Why You Need Taste](https://longitudinalanalysis.com/ai-agent-for-data-analysis-and-why-you-need-taste/) An AI agent for data analysis can write code quickly, but researchers still have to build expertise and understand what decisions are made - [![Causal Mediation in R: A Practical Guide](https://longitudinalanalysis.com/wp-content/uploads/2026/06/example-5-diagram-1-4.webp)](https://longitudinalanalysis.com/causal-mediation-in-r/) ## [Causal Mediation in R: A Practical Guide](https://longitudinalanalysis.com/causal-mediation-in-r/) Learn how to do causal mediation in R using real-world panel data. Learn how to interpret ACME, ADE and how to use binary mediators - [![How to run a multiple mediation model in R](https://longitudinalanalysis.com/wp-content/uploads/2026/06/a-multiple-mediation-model-example-4-6.webp)](https://longitudinalanalysis.com/a-multiple-mediation-model-r/) ## [How to run a multiple mediation model in R](https://longitudinalanalysis.com/a-multiple-mediation-model-r/) Fit a multiple mediation model in R with lavaan using parallel, serial, and longitudinal examples with code and path diagrams. - [![Data cleaning tips for making the most of longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2026/05/Design.webp)](https://longitudinalanalysis.com/data-cleaning-tips-for-making-the-most-of-longitudinal-data/) ## [Data cleaning tips for making the most of longitudinal data](https://longitudinalanalysis.com/data-cleaning-tips-for-making-the-most-of-longitudinal-data/) Before visualising and analysing longitudinal data, it is essential to prepare it correctly. In this guide, we cover data cleaning tips before visualisation - [![Merge Data in R: Complete Guide to Joining Datasets](https://longitudinalanalysis.com/wp-content/uploads/2026/03/image-3.webp)](https://longitudinalanalysis.com/merge-data-in-r-complete-guide-to-joining-datasets/) ## [Merge Data in R: Complete Guide to Joining Datasets](https://longitudinalanalysis.com/merge-data-in-r-complete-guide-to-joining-datasets/) Learn how to merge data when you have information in different files, at different levels and at multiple time points. Explore four real-world scenarios - [![Attrition bias: what is it and how to measure it](https://longitudinalanalysis.com/wp-content/uploads/2026/02/image.webp)](https://longitudinalanalysis.com/attrition-bias-what-is-it-and-how-to-measure-it/) ## [Attrition bias: what is it and how to measure it](https://longitudinalanalysis.com/attrition-bias-what-is-it-and-how-to-measure-it/) Attrition bias explained: how participant dropout occurs, how to measure it, and why it matters for valid longitudinal research. - [![Mediating vs Moderating Variable: How to Choose the Right One](https://longitudinalanalysis.com/wp-content/uploads/2026/01/mediating-vs-moderating-variable.webp)](https://longitudinalanalysis.com/mediating-vs-moderating-variable-how-to-choose-the-right-one/) ## [Mediating vs Moderating Variable: How to Choose the Right One](https://longitudinalanalysis.com/mediating-vs-moderating-variable-how-to-choose-the-right-one/) Mediating vs moderating variable with examples. Learn how to distinguish between mediation and moderation, choose the right model, and avoid common mistakes. - [![A Guide to Moderated Mediation and Mediated Moderation](https://longitudinalanalysis.com/wp-content/uploads/2025/12/image-2.webp)](https://longitudinalanalysis.com/a-guide-to-moderated-mediation-and-mediated-moderation/) ## [A Guide to Moderated Mediation and Mediated Moderation](https://longitudinalanalysis.com/a-guide-to-moderated-mediation-and-mediated-moderation/) A practical guide to moderated mediation, explaining how indirect effects vary across contexts, with clear examples and applied modeling strategies. - [![Hands-On Introduction to Moderation Analysis](https://longitudinalanalysis.com/wp-content/uploads/2025/11/image.webp)](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/) ## [Hands-On Introduction to Moderation Analysis](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/) Learn how moderation analysis reveals when and for whom effects change in longitudinal data, with clear examples and practical modelling guidance. - [![Longitudinal Mediation in R: A Hands-On Guide](https://longitudinalanalysis.com/wp-content/uploads/2025/10/image-2.webp)](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/) ## [Longitudinal Mediation in R: A Hands-On Guide](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/) Learn how to run longitudinal mediation analysis in R using lavaan. Step-by-step guide to model indirect effects and causal pathways over time. - [![Introduction to Path and Mediation Analysis with R](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image.webp)](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/) ## [Introduction to Path and Mediation Analysis with R](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/) Introduction to path analysis and mediation analysis in R. Estimate direct, indirect, and total effects with diagrams, examples, and code. - [![How to present results from longitudinal analysis](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-7.png)](https://longitudinalanalysis.com/how-to-present-results-from-longitudinal-analysis/) ## [How to present results from longitudinal analysis](https://longitudinalanalysis.com/how-to-present-results-from-longitudinal-analysis/) Learn how to present results from longitudinal data analysis using R Markdown, stargazer, texreg, and visualization tools like tidySEM and semPlot. - [![Dynamic documents: a smarter way to share results](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-4.png)](https://longitudinalanalysis.com/using-dynamic-documents-to-present-results-in-r/) ## [Dynamic documents: a smarter way to share results](https://longitudinalanalysis.com/using-dynamic-documents-to-present-results-in-r/) Learn how to use R Markdown to create a dynamic document for reproducible reports, automate updates, and seamlessly integrate code, text, and results in R. - [![How to create reproducible workflows for longitudinal data analysis](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-2.png)](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/) ## [How to create reproducible workflows for longitudinal data analysis](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/) Learn best practices for longitudinal data analysis, including Git, renv, and reproducible workflows to improve efficiency, accuracy, and collaboration. - [![How to include control variables in a cross-lagged panel model](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-1.png)](https://longitudinalanalysis.com/how-to-include-control-variables-in-a-cross-lagged-panel-model/) ## [How to include control variables in a cross-lagged panel model](https://longitudinalanalysis.com/how-to-include-control-variables-in-a-cross-lagged-panel-model/) Learn how to include control variables in a Cross-Lagged Panel Model (CLPM) in R, using time-constant and time-varying predictors to refine causal analysis. - [![Mixture Latent Growth Models R: A Step-by-Step Guide](https://longitudinalanalysis.com/wp-content/uploads/2025/02/image.png)](https://longitudinalanalysis.com/mixture-latent-growth-models-r-a-step-by-step-guide/) ## [Mixture Latent Growth Models R: A Step-by-Step Guide](https://longitudinalanalysis.com/mixture-latent-growth-models-r-a-step-by-step-guide/) The blog post discusses Mixture Latent Growth Models (MLGM) that enhance traditional longitudinal models by identifying latent subgroups with distinct trajectories over time. It details the implementation of MLGM in R using the tidySEM package and compares results from using R and Mplus for improved understanding of individual and aggregate changes. - [![How to estimate and interpret parallel Latent Growth Models (LGM) in R: a step-by-step guide](https://longitudinalanalysis.com/wp-content/uploads/2024/11/image-3.png)](https://longitudinalanalysis.com/how-to-estimate-and-interpret-parallel-latent-growth-models-lgm-in-r-a-step-by-step-guide/) ## [How to estimate and interpret parallel Latent Growth Models (LGM) in R: a step-by-step guide](https://longitudinalanalysis.com/how-to-estimate-and-interpret-parallel-latent-growth-models-lgm-in-r-a-step-by-step-guide/) Learn how to estimate and interpret Parallel Latent Growth Models (LGM) in R and lavaan. This step-by-step guide explores modeling multiple trajectories, analyzing relationships over time, and visualizing results. Perfect for researchers in psychology, sociology, and public health using longitudinal data. - [![How to include time-varying predictors in Latent Growth Models (LGM) in R](https://longitudinalanalysis.com/wp-content/uploads/2024/11/Untitled.png)](https://longitudinalanalysis.com/how-to-include-time-varying-predictors-in-latent-growth-models-lgm-in-r/) ## [How to include time-varying predictors in Latent Growth Models (LGM) in R](https://longitudinalanalysis.com/how-to-include-time-varying-predictors-in-latent-growth-models-lgm-in-r/) This post explores how to incorporate time-varying predictors into Latent Growth Models (LGM) to analyse changes in variables over time. It discusses data preparation, using R code for modeling, and differentiating between concurrent and lagged effects. - [![Including time constant controls in Latent Growth Models](https://longitudinalanalysis.com/wp-content/uploads/2024/10/Untitled.png)](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/) ## [Including time constant controls in Latent Growth Models](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/) This post discusses incorporating time-constant predictors in Latent Growth Models (LGM) using R to better understand changes over time. It details coding in R using real data. It compares strategies for including these predictors and interpreting their effects on intercept and slope in LGMs. - [![Understanding time-varying predictors in multilevel models for longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2024/07/image-1.png)](https://longitudinalanalysis.com/understanding-time-varying-predictors-in-multilevel-models-for-longitudinal-data/) ## [Understanding time-varying predictors in multilevel models for longitudinal data](https://longitudinalanalysis.com/understanding-time-varying-predictors-in-multilevel-models-for-longitudinal-data/) This post explains how to include time-varying predictors in multilevel models for analyzing dynamic processes over time. By incorporating variables that change over time, such as income or educational support, researchers can gain a nuanced understanding of factors influencing outcomes like mental health. - [![Understanding the longitudinal data workflow: a comprehensive guide](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process.png)](https://longitudinalanalysis.com/understanding-the-longitudinal-data-workflow-a-comprehensive-guide/) ## [Understanding the longitudinal data workflow: a comprehensive guide](https://longitudinalanalysis.com/understanding-the-longitudinal-data-workflow-a-comprehensive-guide/) Unlock insights from longitudinal data with our step-by-step guide, from import to analysis. Master the workflow to elevate your research. - [![Complete guide to visualizing longitudinal data in R](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_visualize_crop.png)](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/) ## [Complete guide to visualizing longitudinal data in R](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/) Unlock the secrets of longitudinal data in R with this complete guide. Master the art of insightful visualizations for impactful analysis. - [![Exploring longitudinal data in R: tables and summaries](https://longitudinalanalysis.com/wp-content/uploads/2024/03/long_process_describe.png)](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) ## [Exploring longitudinal data in R: tables and summaries](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) Unlock the power of R for longitudinal data analysis! Learn to navigate tables and summaries with ease in our latest guide. - [![Cleaning longitudinal data in R: a step-by-step guide](https://longitudinalanalysis.com/wp-content/uploads/2024/03/long_process_cleaning-e1711530629641.png)](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) ## [Cleaning longitudinal data in R: a step-by-step guide](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) Explore key R commands for cleaning longitudinal data, including recoding variables and handling missing data effectively. - [![Preparing longitudinal data for analysis in R: a step-by-step guide](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image.png)](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) ## [Preparing longitudinal data for analysis in R: a step-by-step guide](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) Explore the crucial steps of data preparation for longitudinal analysis in R, from importing to reshaping data, in this step-by-step guide. - [![Estimating and visualizing multilevel models for change in R](https://longitudinalanalysis.com/wp-content/uploads/2024/02/multilevel-model-change-predictions.png)](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) ## [Estimating and visualizing multilevel models for change in R](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) Learn how to analyse longitudinal data using the multilevel model for change with R. Hands on example using real world data and syntax. - [![Estimating non-linear change with Latent Growth Models in R](https://longitudinalanalysis.com/wp-content/uploads/2024/02/latent-growth-model-predicted-trends.png)](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/) ## [Estimating non-linear change with Latent Growth Models in R](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/) Learn how to estimate and visualize nonlinear Latent Growth Models (LGM) using R. Hands on example using real world longitudinal data and code - [![Comparing the multilevel model with the Latent Growth Model](https://longitudinalanalysis.com/wp-content/uploads/2024/02/mlm_trajectories.png)](https://longitudinalanalysis.com/comparing-the-multilevel-model-with-the-latent-growth-model/) ## [Comparing the multilevel model with the Latent Growth Model](https://longitudinalanalysis.com/comparing-the-multilevel-model-with-the-latent-growth-model/) Learn how the multilevel model for change and the latent growth models are different and when to use each one. Hands on example using real data and R - [![Understanding causal direction using the cross-lagged model](https://longitudinalanalysis.com/wp-content/uploads/2024/02/cross-lagged-model.png)](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) ## [Understanding causal direction using the cross-lagged model](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) Learn how to investigate the causal direction of two variables using the cross-lagged model and longitudinal data. Hands on example using R and real data - [![Estimating non-linear change in time using the multilevel model for change](https://longitudinalanalysis.com/wp-content/uploads/2024/02/nonlinear_change_multilevel_modeling.png)](https://longitudinalanalysis.com/estimating-non-linear-change-in-time-using-the-multilevel-model-for-change/) ## [Estimating non-linear change in time using the multilevel model for change](https://longitudinalanalysis.com/estimating-non-linear-change-in-time-using-the-multilevel-model-for-change/) Learn how to model non-linear change in time using the multilevel model for change in R. Hands on tutorial with real data. - [![Explaining change using multilevel and time constant predictors](https://longitudinalanalysis.com/wp-content/uploads/2024/02/mlm_change_prediction.png)](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/) ## [Explaining change using multilevel and time constant predictors](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/) Learn how to explain change in time using time constant predictors using the multilevel model. Examples with real data and R code - [![Visualizing transitions in time using R and alluvial graphs](https://longitudinalanalysis.com/wp-content/uploads/2024/02/alluvial_graph_r.png)](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) ## [Visualizing transitions in time using R and alluvial graphs](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) Learn how to visualize transitions in time for categorical data using Sankey plot/river/alluvial graphs and R. Easy hands one example using real data - [![Estimating and visualizing Latent Growth Models with R](https://longitudinalanalysis.com/wp-content/uploads/2024/02/lgm.png)](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) ## [Estimating and visualizing Latent Growth Models with R](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) Tutorial showing you how to visualize change in time and how to estimate it using Latent Growth Modelling with R. Hands on longitudinal data analysis. - [![Data structures for longitudinal analysis: wide versus long](https://longitudinalanalysis.com/wp-content/uploads/2024/02/futuristictrends-e1711120364697.png)](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) ## [Data structures for longitudinal analysis: wide versus long](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) Learn how to create, store and reshape longitudinal data. Reshaping data from wide to long data format and back using R. Hands on examples --- ### [Understanding time-varying predictors in multilevel models for longitudinal data](https://longitudinalanalysis.com/understanding-time-varying-predictors-in-multilevel-models-for-longitudinal-data/) **Published:** July 26, 2024 **Author:** Alex Cernat **Excerpt:** This post explains how to include time-varying predictors in multilevel models for analyzing dynamic processes over time. By incorporating variables that change over time, such as income or educational support, researchers can gain a nuanced understanding of factors influencing outcomes like mental health. **Content:** Multilevel models for change are among the most popular approaches used to understand how people, groups and societies change over time. In previous posts, [we introduced the model](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) and [showed how to include time-constant predictors to explain change in time](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/). Here, we will discuss how to add time-varying predictors in such models to analyze dynamic processes. This technique allows researchers to account for variables that change over time, providing a nuanced understanding of how these predictors influence outcomes. For instance, in studying educational progress, time-varying predictors like student engagement or teacher support can be critical in explaining individual differences in achievement growth. Understanding how to include time-varying predictors in multilevel models is essential for accurately capturing the complexity of longitudinal data and enhancing the precision of statistical analyses. ## Preparing the data You can follow this guide by running the code in R on your computer. Our examples will use synthetic (simulated) data modelled after [Understanding Society](https://www.understandingsociety.ac.uk/), a comprehensive panel study from the UK. The real data can be accessed for free from the [UK Data Archive](https://beta.ukdataservice.ac.uk/datacatalogue/series/series?id=2000053). [In a previous blog](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/), we cleaned the data and we have it both in [the long format and the wide one](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! Before we start, make sure you have the `tidyverse` and `lme4` packages installed and loaded by running the following code: ``` install.packages("lme4") install.packages("tidyverse") library(lme4) library(tidyverse) ``` We will mainly use the `lme4` package to run multilevel models but will also use `tidyverse` for some light data cleaning. Next, we will load the data prepared in the previous post. This contains both the long and the wide format data in an “RData” file. We will load the long-format data and have a quick look at it: ``` load("./data/us_clean_syn.RData") glimpse(usl) ``` ``` ## Rows: 204,028 ## Columns: 32 ## $ pidp 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 10, 10, 10, 10, 11, 11… ## $ wave 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4… ## $ age 28, 28, 28, 28, 80, 80, 80, 80, 60, 60, 60, 60, 42, 42… ## $ hiqual 1, 1, 1, 1, 9, 9, 9, 9, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, … ## $ single 1, 1, 1, 0, 0, 0, 0, 0, 1, NA, NA, NA, 0, NA… ## $ fimngrs 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ sclfsato -9, 6, 2, 1, 6, 6, -8, 3, 2, NA, NA, NA, -9, NA… ## $ sf12pcs 54.51, 62.98, 56.97, 56.15, 53.93, 46.39, NA, 46.16, 33.18… ## $ sf12mcs 55.73, 36.22, 60.02, 59.04, 46.48, 45.39, NA, 37.02, 46.80… ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, … ## $ sf1 2, 2, 1, 3, 4, 3, 3, 3, 5, NA, NA, NA, 2, NA… ## $ present TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, … ## $ gndr.fct Male, Male, Male, Male, Male, Male, Male, Male, Male, Male… ## $ single.fct Single, Single, Single, In relationship, In relationship, … ## $ urban.fct Urban, Urban, Urban, Urban, Urban, Urban, Urban, Urban, Ur… ## $ degree.fct Degree, Degree, Degree, Degree, No degree, No degree, No d… ## $ vote6.fct Not very, Not at all, Not at all, Not at all, Not at all, … ## $ sati NA, 6, 2, 1, 6, 6, NA, 3, 2, NA, NA, NA, NA, NA, 5, NA, NA… ## $ sati.fct NA, Mostly satisfied, Mostly dissatisfied, Completely diss… ## $ fimngrs.cap 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ logincome 8.099818, 8.297170, 8.196070, 6.757514, 6.809039, 6.577861… ## $ year 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, NA, … ## $ sati.ind 3.000000, 3.000000, 3.000000, 3.000000, 5.000000, 5.000000… ## $ sati.dev NA, 3.000000, -1.000000, -2.000000, 1.000000, 1.000000, NA… ## $ sf12pcs.ind 57.65250, 57.65250, 57.65250, 57.65250, 48.82667, 48.82667… ## $ sf12pcs.dev -3.1425000, 5.3275000, -0.6825000, -1.5025000, 5.1033333, … ## $ sf12mcs.ind 52.75250, 52.75250, 52.75250, 52.75250, 42.96333, 42.96333… ## $ sf12mcs.dev 2.977500, -16.532500, 7.267500, 6.287500, 3.516667, 2.4266… ## $ waves 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4… ## $ sati.lag NA, NA, 6, 2, NA, 6, 6, NA, NA, 2, NA, NA, NA, NA, NA, 5, … ## $ sf12pcs.lag NA, 54.51, 62.98, 56.97, NA, 53.93, 46.39, NA, NA, 33.18, … ## $ sf12mcs.lag NA, 55.73, 36.22, 60.02, NA, 46.48, 45.39, NA, NA, 46.80, … ``` ## Including Time Varying Predictors We discussed the basic multilevel model of change and included time-constant predictors in previous posts ([here ](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/)and [here](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/)). Now we will build on that knowledge to include time-varying predictors in the model. Before we run the model, it’s good practice to fix the time variable to start from 0 to make the intercept easier to interpret: ``` usl <- mutate(usl, wave0 = wave - 1) ``` Including time-varying predictors in a multilevel model for change works in the same way as time-constant ones, but their interpretation is more complex as their values can change over time. Let’s look at a simple example where we include log income as a predictor of mental health: ``` m1 <- lmer(data = usl, sf12mcs ~ 1 + wave0 + logincome + (1 + wave0 | pidp)) summary(m1) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: sf12mcs ~ 1 + wave0 + logincome + (1 + wave0 | pidp) ## Data: usl ## ## REML criterion at convergence: 934469.1 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.3666 -0.4289 0.1551 0.5582 3.1007 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 39.740 6.304 ## wave0 3.053 1.747 -0.38 ## Residual 59.077 7.686 ## Number of obs: 127863, groups: pidp, 48615 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 48.77459 0.15088 323.28 ## wave0 -0.44797 0.02191 -20.45 ## logincome 0.22631 0.02166 10.45 ``` Based on the model, the rate of change in mental health is -0.448. This indicates that with the passing of each wave, mental health decreases by 0.448, on average. Here, we see that an increase of log income by 1 leads to an increase in mental health by 0.226. This shift can happen multiple times because individuals can increase and decrease their income over time. To help better understand how to interpret the results we can build three case studies. We will create a new small data with three individuals: one that always has logincome = 2, one that always has 9 and one that has 4 in the first wave and then switches to 5, 3 and 3. ``` pred_data <- tibble(pidp = rep(1:3, each = 4) |> as.factor(), wave0 = rep(0:3, 3), logincome = c(rep(c(2, 9), each = 4), c(4, 5, 3, 3))) pred_data ``` ``` ## # A tibble: 12 × 3 ## pidp wave0 logincome ## ## 1 1 0 2 ## 2 1 1 2 ## 3 1 2 2 ## 4 1 3 2 ## 5 2 0 9 ## 6 2 1 9 ## 7 2 2 9 ## 8 2 3 9 ## 9 3 0 4 ## 10 3 1 5 ## 11 3 2 3 ## 12 3 3 3 ``` We can then predict the expected mental health for these individuals based on our model: ``` pred_data <- mutate(pred_data, pred_m1 = predict(m1, newdata = pred_data, allow.new.levels = TRUE)) pred_data ``` ``` ## # A tibble: 12 × 4 ## pidp wave0 logincome pred_m1 ## ## 1 1 0 2 49.2 ## 2 1 1 2 48.8 ## 3 1 2 2 48.3 ## 4 1 3 2 47.9 ## 5 2 0 9 50.8 ## 6 2 1 9 50.4 ## 7 2 2 9 49.9 ## 8 2 3 9 49.5 ## 9 3 0 4 49.7 ## 10 3 1 5 49.5 ## 11 3 2 3 48.6 ## 12 3 3 3 48.1 ``` Finally, we can visualize how their mental health would change over time. ``` pred_data |> ggplot(aes(wave0, pred_m1, color = pidp, group = pidp)) + geom_line() ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/07/image-4.png) This way, we can easily see that the trends for the individuals are the same and how the shift in log income impacts the trajectory of mental health. This approach also helps communicate the findings of these complex models. Let’s examine in more detail how these predicted scores were created using a slightly nice version of the graph. ![Graph showing the impact of time-varying predictors on mental health in a multilevel model. It compares predicted mental health for individuals with different log income levels over time.](https://longitudinalanalysis.com/wp-content/uploads/2024/07/image-1-1024x832.png) The first individual, line green, always has a log income of 9. Based on our model, this leads to better mental health. The 0.226 coefficient causes the shift in the line of this individual. On the other hand, we have an individual who always has a log income of 2 (red line). Their mental health is lower. We also note that the two lines are parallel. This is because, in the absence of an interaction with time, we assume that the rate of change is the same regardless of the log income value. Based on this model, log income leads to a shift in the trend line but not a change in the trajectory itself. The last individual (blue line) starts with an initial log income of 4. In the second wave, their income increases to 5, shifting the trend line by 0.226. In the next wave, their income decreases by two, leading to another shift in their trend line of 2 \* 0.226. In this way, we can see how the change in log income “shifts” individuals to different hypothetical trends. In some situations, we might have a hypothesis that a variable not only increases or decreases the values of the outcomes but also impacts their trajectory. Alternatively, we can think that the effect of a variable might not be the same over time. Maybe we expect the effect of income to be lower as people get older. In such situations, we can expand the model to include an interaction between the predictor and time (similar to what we have done before). ``` m2 <- lmer(data = usl, sf12mcs ~ 1 + wave0 + logincome + logincome:wave0 + (1 + wave0 | pidp)) summary(m2) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: sf12mcs ~ 1 + wave0 + logincome + logincome:wave0 + (1 + wave0 | ## pidp) ## Data: usl ## ## REML criterion at convergence: 934472.2 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.3668 -0.4293 0.1552 0.5581 3.1014 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 39.756 6.305 ## wave0 3.053 1.747 -0.38 ## Residual 59.077 7.686 ## Number of obs: 127863, groups: pidp, 48615 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 48.96708 0.18545 264.047 ## wave0 -0.65471 0.11779 -5.558 ## logincome 0.19769 0.02695 7.335 ## wave0:logincome 0.02987 0.01672 1.787 ``` Based on these results, log income not only has a positive effect on mental health, but its effect increases over time. In each wave, the effect is larger by 0.03 Let’s look again at three hypothetical trends to better understand the model’s implications. ![Graph showing the effect of time-varying predictors on mental health in a multilevel model, highlighting the impact of log income changes and interaction over time.](https://longitudinalanalysis.com/wp-content/uploads/2024/07/image-2-1024x832.png) For an individual who always has a log income of 9 (green line), we see that they start with higher mental health in the first wave. This is caused by the main effect of log income (0.198). We observe that their mental health decreases over time, but it does so at a lower rate compared to the other two individuals. The interaction effect causes this difference in the trend. On the other hand, we see that the individual who always has a log income of 2 (red line) not only starts with lower mental health but also decreases at a faster rate. The third individual (blue line) starts with a log income of 4 and shifts to a value of 5 in the second wave. This increase in log income initially leads to a change in mental health of 0.198. But because of the interaction effect, as time passes they get an additional improvement in mental health. By wave 4, they get an additional 2 \* 0.03 in the mental health score. While we can interpret the coefficients like in a standard regression, the substantive interpretation can be more complex. The main reason for this is that time-varying variables also include two sources of variation. ([see an interactive explanation of within and between variation](https://longitudinalanalysis.com/interactive/within-between/)) The effect of log income could be due to **between variation**, for example, because the respondent is more or less wealthy, which is a stable trait. The effect could be due to **within variation**, if the respondent had a significant increase or decrease in income, which could be important in relative terms (feeling more or less financially secure than usual) and less critical in absolute terms. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions In conclusion, incorporating time-varying predictors into multilevel models offers a way to analyze dynamic processes in longitudinal data. By accounting for variables that change over time, such as income or educational support, researchers can gain deeper insights into the factors influencing outcomes like mental health or academic achievement. As demonstrated here, the interpretation of such models can be complex, especially when considering interactions. Building case studies of different individuals using predicted scores from the model can help better understand the implications of the findings. This model can be easily extended to include multiple time constant and time-varying predictors. It can also include non-linear change in time, which we discuss [here](https://longitudinalanalysis.com/estimating-non-linear-change-in-time-using-the-multilevel-model-for-change/). To interpret time-varying predictors easier it is also possible to recode or decompose time-varying predictors using lagged effects or separating between and within variation. We will discuss how to do this in future posts. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, multilevel modeling, r --- ### [Understanding the longitudinal data workflow: a comprehensive guide](https://longitudinalanalysis.com/understanding-the-longitudinal-data-workflow-a-comprehensive-guide/) **Published:** April 4, 2024 **Author:** Alex Cernat **Excerpt:** Unlock insights from longitudinal data with our step-by-step guide, from import to analysis. Master the workflow to elevate your research. **Content:** Longitudinal data analysis provides a unique window into the evolution of phenomena over time, capturing the dynamism of real-world processes in ways that cross-sectional studies simply cannot. It also helps shed light on causal relationships. From understanding how economic policies impact growth year after year to tracking the progress of students throughout their education, longitudinal analysis provides novel insights. However, the richness of longitudinal data also brings its own set of challenges. These include managing multiple datasets at various levels, handling different types of missing data, and navigating diverse variables. Also, longitudinal data can be diverse, including everything from panel studies to log data from phones. To analyse such data, it is useful to step back and understand the workflow needed to get insights from such sources. In this comprehensive guide, you’ll learn the essential steps to transform raw longitudinal data into insightful analyses that are ready for communication. From importing data to communicating results, we’ll guide you through each stage with practical tips, paving your way to mastering longitudinal data analysis. One way to visualize this entire process is with the following diagram, which includes the main steps and the associated commands in R. We will next discuss each of these stages to explore the key aspects you need to consider in your work. ![Illustration showing the workflow of longitudinal data analysis, including data import, transformation, cleaning, exploration, analysis, and communication.](http://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process-1024x557.png) ## 1.      Importing data The first step in the journey to data analysis is to import the data. Longitudinal data is stored in different ways. Traditional social science data typically stores data separately for each wave and each level. For example, [Understanding Society](http://understandingsociety.ac.uk), a large UK panel study, has a separate dataset for wave 1 individual-level information and wave 1 household-level information. Other datasets include details about relationships between household members or biological attributes. The following waves would follow a similar structure. On the other hand, a study like the [Health and Retirement Study](https://hrs.isr.umich.edu/), an ageing study in the US, has a separate file for each survey section at each point in time. Given this complexity and diversity, your first step should be understanding how your data is stored and identifying which datasets are essential for your analysis. Once we have decided on that, we can download the data. Typically, this is stored either as CSV (comma-separated values) or in a more specialised format, like “.sav”, “.dta”, “.sas”. Most statistical software can open the “.csv” format, but it tends to occupy more space and lack labels or other metadata. Because of that, importing data from one of the other formats might be useful if it comes with labels. R’s “haven” package can import such data with labels and other attributes. When working with large datasets, importing only the necessary variables might be useful. For example, the commands from “haven” have an option `col_select` where we can give the names of the variables of interest. These have to be identified in advance using the study codebook or questionnaire. In this way, we can import just a handful of essential variables instead of hundreds. Similarly, we can select only the cases of interest at this point to make the data size more manageable. Because we will combine data from multiple waves, longitudinal data could get quite big. Blogpost that can guide you on this topic: –          [Data structures for longitudinal analysis: wide versus long](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) –          [Preparing longitudinal data for analysis in R: a step-by-step guide](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) ## 2. Transforming data ![Diagram illustrating various data transformation techniques applied in longitudinal data analysis.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_transform-101x300.png) Once we decide what data and variables are essential, we can combine them. Before that, it is useful to rename variables to make them easier to identify. One format often used is “varname\_wavenumber” (e.g., education\_2 for education in wave 2) for [time-varying variables](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (i.e., those that change in time). For [time-constant](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) predictors (that do not change in time), we can just use the variable name. Effective data merging requires identifying a unique ID for each case. For example, ‘pidp’ is the individual-level unique ID in Understanding Society. This is also time constant, meaning that we can merge cases over time. On the other hand, we need to use the household id (“hidp”) to merge individual-level and household-level information. Nevertheless, this is not time constant, meaning that it changes over time. As a result, it’s useful only when merging data within the same wave. Understanding such issues is essential for making the correct data mergers. Usually, studies have user guides that advise on this process. Once we have the data of interest with the renamed variables and the ID information, we can merge them. There are different strategies to do this. My recommendation is to merge the data in the wide format. This can be done in R easily with the xxx\_join() commands. For example, the full\_join(us1, us2, by = “pidp”) will merge all the cases in waves 1 and 2 of Understanding Society using the “pidp” variable. The xxx\_join() commands give the flexibility to decide who to include and make it easier to see if the merger was successful. At this stage, we can also filter cases. For example, if we want to keep only cases that are present in all waves ([balanced data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/)), this can be done using the `filter()` command. Finally, we need to prepare the data for cleaning. My recommendation is to do that in the [long format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). This tends to be easier as you can clean each variable once for all the points in time. Also, the process would be the same regardless of how many waves of data you have. To do this, we can reshape the data using, for example, the [`pivot_longer()`](https://tidyr.tidyverse.org/articles/pivot.html) command. Blogpost that can guide you on this topic: –          [Data structures for longitudinal analysis: wide versus long](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) –          [Preparing longitudinal data for analysis in R: a step-by-step guide](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) ## 3. Cleaning data ![Diagram illustrating various data cleaning techniques applied in longitudinal data analysis.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_clean-186x300.png) We can start cleaning it once we have just the variables of interest from all the waves in the [long format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). This involves describing each variable and recoding the necessary categories for our research. This also involves recording missing categories. For example, in Understanding Society, negative values tend to be associated with missing information. These would need to be coded as NA in R. We might also want to recode categorical variables as factors and give them appropriate labels or collapse variables with many categories. Similarly, we might want to transform continuous variables if they are skewed or lag them. In this process, we must always remember what we are trying to achieve and how best to code variables for it. We should also understand the potential limitations of your data. For example, are there variables with lots of missing information? If yes, we might need to find alternative measures, impute the missing information or drop them from our analysis. Blogpost that can guide you on this topic: –          [Cleaning longitudinal data in R: a step-by-step guide](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) ## 4. Exploring data ![Set of graphs displaying initial exploratory data analysis of a longitudinal dataset, including trends over time and distributions.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_describe-221x300.png) The next step is also known as Exploratory Data Analysis. Once we have the data in the right format and cleaned, we can start to understand the patterns in the data better. This can be done with tables, summary statistics and visualizations. I recommend beginning with simple analyses and progressively moving to more complex ones. Begin with univariate statistics and progress to exploring changes over time and differences between groups. In this process, we can develop our hypotheses about relationships and find anomalies in the data. Again, try to remember the research questions and models of interest to guide the exploration of the data. For example, if we want to look at changes in time, we can use line graphs. If we need to decide how to model change in time (linear or non-linear), graphs and tables can inform that decision. Blogpost that can guide you on this topic: –          [Exploring longitudinal data in R: tables and summaries](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) –          [Complete guide to visualizing longitudinal data in R](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/) ## 5. Analysing data ![Diagram showing main types of statistical models for longitudinal data analysis](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_analyse-82x300.png) There are many types of models and ways to set them up. Before running the models, focus on the research questions and hypotheses to determine the appropriate models. Make a plan for the sequence of models needed to answer the research questions. In general, starting from a simple model and building it up towards more complex ones is recommended. Let’s look at an example. If our main research question is to look at changes in time of cognitive ability in children and to see if that is affected by parents’ education, then the best models to use would be the multilevel model for change or the latent growth model. Let’s imagine we select the former, and we can plan a sequence of models next. For example, we might start with an empty model to estimate the amount of between and within variation (also known as IntraClass Correlation). ([see an interactive explanation of within and between variation](https://longitudinalanalysis.com/interactive/within-between/)) Then, we might run a sequence of models to decide if the change in time is linear or non-linear. Finally, we could start adding variables to the model. This could be in blocks, for example first the variables of interest (like parental education) could be added, then the control variables (like gender, type of school, etc.) and then any interactions we are interested in (like the interaction between time and parental education). Doing the analysis might also lead to new questions or the realization that we need other variables. This is where iteration comes in, and we might need to go back to the data-cleaning step to recode new variables. For example, we might need to recode parental education to better capture its impact on cognitive ability of the child before redoing the analysis. Blogpost that can guide you on this topic: –          [Estimating and visualizing multilevel models for change in R](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) –          [Understanding causal direction using the cross-lagged model](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) –          [Estimating and visualizing Latent Growth Models with R](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) ## 6. Communicating results ![Infographic summarizing key findings from longitudinal data analysis and tips for effectively communicating results](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_communicate-300x242.png) At this stage, it is useful to consider the audience and our aims. This will impact both your communication methods, such as text, tables, and graphs and the format of the outputs, reports, papers, presentations, etc. For example, if we want to share intermediate results with colleagues, we can use a dynamic document with outputs from the analysis. In this case things don’t have to be polished and can be more technical. On the other hand, a final report for policymakers would need to be more polished and less technical. We may need to focus more on creating visualizations and text that can easily transmit the findings to a larger audience. R offers a powerful framework for creating dynamic documents. This framework combines text, R code, and R outputs to create presentations, papers, books, and reports. I recommend you learn more about [Rmarkdown](https://rmarkdown.rstudio.com/) and its newer sibling, [Quarto](https://quarto.org/), as it can save considerable time in the long run. Blogpost that can guide you on this topic: –          [Exploring longitudinal data in R: tables and summaries](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) –          [Complete guide to visualizing longitudinal data in R](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/) ## Other considerations Storage and version control are some of the other practical things to remember in this process. In general, it’s recommended that you have backups for your work. This can be achieved by working directly with programs like Dropbox, OneDrive, and Google Drive. This way, we know that in case of computer failure or loss, there is a backup of our work. One thing to keep in mind is our data agreement. This might restrict the possibility of storing data on such platforms. A solution is to keep only the code and outputs on these platforms while storing the data locally. The other thing to consider is version control. This specially developed software keeps a history of our work and backs it up. The most popular platforms for this are Git and GitHub. There is increasing pressure to use such platforms both from the scientific community (to encourage reproducible research) and from data science. My recommendation is to learn more about using this in your own work. For R users, a good starting point is [happygitwithr.com](https://happygitwithr.com). ## Conclusions Longitudinal data is complex, and working with it is time-consuming. Here, we discussed the main stages of going from raw data to communicating results when using such data. While this cannot cover all the complex decisions to be made and all the commands to be used, we hope it provides a useful overview of the process. You can use it as a map to guide you in this process and to show the way forward. ![Illustration showing the workflow of longitudinal data analysis, including data import, transformation, cleaning, exploration, analysis, and communication.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process-1024x557.png) --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data cleaning, data management, data restructuring, longitudinal data analysis, r --- ### [Estimating and visualizing multilevel models for change in R](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how to analyse longitudinal data using the multilevel model for change with R. Hands on example using real world data and syntax. **Content:** Longitudinal data is fascinating as it enables us to examine change in time, better understand causal relationships, and explain events and their timing. To use this type of data, we typically need to move beyond classical statistical methods, such as OLS regression and ANOVA, to models that can deal with the extra complexity of the data. One popular model for analyzing longitudinal data is the **MultiLevel Model for Change** (**MLMC**). This enables the estimation of change in time while accounting for the hierarchical nature of the data (multiple points in time nested within individuals). It is similar to the [Latent Growth Model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/), but it is estimated using the multilevel model framework (also known as hierarchical modeling or random effects) and uses the [long data format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (each row is a specific time point for an individual). More precisely, the MLMC can help: - understand how change happens in time - explain change using [time-varying](https://longitudinalanalysis.com/understanding-time-varying-predictors-in-multilevel-models-for-longitudinal-data/) and [time-constant predictors](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/) - decompose variance in **between** and **within** variation - can efficiently deal with continuous time, [unbalanced data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (not all individuals are present at all times), and different timings (not everyone gives data at the same time) Here, I’ll give a high-level introduction to MLMC, how to estimate it in R, and how to visualize change using it. ## Preparing the data You can follow this guide by running the code in R on your computer. Our examples will use synthetic (simulated) data modelled after [Understanding Society](https://www.understandingsociety.ac.uk/), a comprehensive panel study from the UK. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! [In a previous blog](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/), we cleaned the data, and have both [the long and the wide formats](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). We will use that cleaned data here. Before we start, make sure you have the `tidyverse` and `lme4` packages installed and loaded by running the following code: ``` install.packages("lme4") install.packages("tidyverse") library(lme4) library(tidyverse) ``` We will mainly use the `lme4` package to run multilevel models and `tidyverse` for some light data cleaning. ## Importing and exploring the data Next, we will load the data prepared in the [previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/). This contains long and wide format data in an “RData” file. We will load the long-format data and have a quick look at it: ``` load("./data/us_clean_syn.RData") glimpse(usl) ``` ``` ## Rows: 204,028 ## Columns: 32 ## $ pidp 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 10, 10, 10, 10, 11, 11… ## $ wave 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4… ## $ age 28, 28, 28, 28, 80, 80, 80, 80, 60, 60, 60, 60, 42, 4… ## $ hiqual 1, 1, 1, 1, 9, 9, 9, 9, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1,… ## $ single 1, 1, 1, 0, 0, 0, 0, 0, 1, NA, NA, NA, 0, NA, 0, NA, … ## $ fimngrs 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ sclfsato -9, 6, 2, 1, 6, 6, -8, 3, 2, NA, NA, NA, -9, NA, 5, N… ## $ sf12pcs 54.51, 62.98, 56.97, 56.15, 53.93, 46.39, NA, 46.16, 33.18… ## $ sf12mcs 55.73, 36.22, 60.02, 59.04, 46.48, 45.39, NA, 37.02, 46.80… ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009,… ## $ sf1 2, 2, 1, 3, 4, 3, 3, 3, 5, NA, NA, NA, 2, NA, 2, NA, … ## $ present TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, … ## $ gndr.fct Male, Male, Male, Male, Male, Male, Male, Male, Male, Male… ## $ single.fct Single, Single, Single, In relationship, In relationship, … ## $ urban.fct Urban, Urban, Urban, Urban, Urban, Urban, Urban, Urban, Ur… ## $ degree.fct Degree, Degree, Degree, Degree, No degree, No degree, No d… ## $ vote6.fct Not very, Not at all, Not at all, Not at all, Not at all, … ## $ sati NA, 6, 2, 1, 6, 6, NA, 3, 2, NA, NA, NA, NA, NA, 5, NA, NA… ## $ sati.fct NA, Mostly satisfied, Mostly dissatisfied, Completely diss… ## $ fimngrs.cap 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ logincome 8.099818, 8.297170, 8.196070, 6.757514, 6.809039, 6.577861… ## $ year 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, NA, … ## $ sati.ind 3.000000, 3.000000, 3.000000, 3.000000, 5.000000, 5.000000… ## $ sati.dev NA, 3.000000, -1.000000, -2.000000, 1.000000, 1.000000, NA… ## $ sf12pcs.ind 57.65250, 57.65250, 57.65250, 57.65250, 48.82667, 48.82667… ## $ sf12pcs.dev -3.1425000, 5.3275000, -0.6825000, -1.5025000, 5.1033333, … ## $ sf12mcs.ind 52.75250, 52.75250, 52.75250, 52.75250, 42.96333, 42.96333… ## $ sf12mcs.dev 2.977500, -16.532500, 7.267500, 6.287500, 3.516667, 2.4266… ## $ waves 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4… ## $ sati.lag NA, NA, 6, 2, NA, 6, 6, NA, NA, 2, NA, NA, NA, NA, NA, 5, … ## $ sf12pcs.lag NA, 54.51, 62.98, 56.97, NA, 53.93, 46.39, NA, NA, 33.18, … ## $ sf12mcs.lag NA, 55.73, 36.22, 60.02, NA, 46.48, 45.39, NA, NA, 46.80, … ``` Before we get into MLMC, let’s examine the data we want to analyze. Let’s imagine we are interested in how income changes over time and what the main sources of that change. More precisely, we want to separate **between** **variation**, how people change compared to others, and **within variation**, how people vary relative to their own average/trend. ([see an interactive explanation of within and between variation](https://longitudinalanalysis.com/interactive/within-between/)) Let’s explore the data. First, let’s look at the long data that we will use for the modeling and graphs: ``` head(usl, n = 10) ``` ``` ## # A tibble: 10 × 32 ## pidp wave age hiqual single fimngrs sclfsato sf12pcs sf12mcs istrtdaty ## ## 1 5 1 28 1 1 3284. -9 54.5 55.7 2009 ## 2 5 2 28 1 1 4002. 6 63.0 36.2 2010 ## 3 5 3 28 1 1 3617. 2 57.0 60.0 2011 ## 4 5 4 28 1 0 850. 1 56.2 59.0 2012 ## 5 6 1 80 9 0 896 6 53.9 46.5 2010 ## 6 6 2 80 9 0 709 6 46.4 45.4 2011 ## 7 6 3 80 9 0 702 -8 NA NA 2012 ## 8 6 4 80 9 0 829. 3 46.2 37.0 2013 ## 9 7 1 60 3 1 1458. 2 33.2 46.8 2009 ## 10 7 2 60 3 NA NA NA NA NA NA ## # ℹ 22 more variables: sf1 , present , gndr.fct , ## # single.fct , urban.fct , degree.fct , vote6.fct , ## # sati , sati.fct , fimngrs.cap , logincome , year , ## # sati.ind , sati.dev , sf12pcs.ind , sf12pcs.dev , ## # sf12mcs.ind , sf12mcs.dev , waves , sati.lag , ## # sf12pcs.lag , sf12mcs.lag ``` We see that each row is a combination of individual (variable “pidp”) and time (variable “wave”). This is also the format we need for doing visualization using `ggplot2`. To see what we will be modeling, we can make a simple graph showing the average change in time for the whole data as well as a line for the change of each individual (intro to graphs for longitudinal data [here](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/)): ``` ggplot(usl, aes(wave, logincome, group = pidp)) + geom_line(alpha = 0.01) + stat_summary( aes(group = 1), fun = mean, geom = "line", size = 1.5, color = "red" ) + theme_bw() + # nice theme labs(x = "Wave", y = "Logincome") # nice labels ``` ![change in time of income in the UK](https://longitudinalanalysis.com/wp-content/uploads/2024/02/image-6-1024x731.png) So we see a positive average change in time but also quite a lot of variation in how people change (gray lines all over the place). MLMC can estimate both of these things at the same time! ## What is multilevel modeling? Multilevel modeling is an extension of regression modeling in which we can decompose different sources of variation. Why is this important? Traditional, OLS regression assumes that all the cases are independent. This implies that there is no correlation between the observed measures due to things like clustering. This is often not true in social science data. For example, individuals are nested within households, neighborhoods, regions, and countries. Students are nested in classes, schools, areas, and countries. This nested structure makes individuals similar to each other. For example, health outcomes will probably be similar for people living in the same neighborhoods because of self-selection (similar income and education), quality of health provision, or air quality. If this is true, we can’t treat people from the same neighborhood as independent. Multilevel modeling solves this issue by estimating random effects (i.e., variation) for the different levels present in the data. This way, the regression coefficients (like standard errors) will be corrected for this nested structure. Additionally, these models can estimate how much variation comes from each level. This can be very informative. For example, by decomposing the variation of student outcomes at the student level, class level, and school level, we can understand the main factors impacting the students’ grades. This can inform theory and policy. ## Between and within variation Longitudinal data is also nested. Measures at different points in time are nested within an individual. These observations are not independent, as stable individual characteristics (like genes, personality, or context) lead to consistent responses within the individuals and across time. So, multilevel modeling can help correct this nesting and facilitate the separation of two primary sources of variation in longitudinal data: **between variation** and **within variation**. The former refers to how individuals are different from each other in the outcome of interest (e.g., one individual has, on average, a higher income compared to another), while the latter refers to how the measure is different in a particular year compared to their individual average (e.g., do they have a lower or higher income compared to their average income). To better understand these sources of variation, let’s look at this graph that shows three hypothetical individuals and how they change in time: ![three trajectories in time in a longitudinal study](https://longitudinalanalysis.com/wp-content/uploads/2024/02/image-5-1024x731.png) The trends capture two sources of variation. We can imagine creating a linear trend for each individual to understand how that works. Now, each individual has their own trajectory: ![between and within variation decomposition in longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2024/02/image-1024x731.png) When we discuss **between variation**, we refer to how the individual lines are different from each other. On the other hand, when we discuss **within variation**, we refer to the difference between each individual’s trend and their observed scores (represented by dots in the above graph). To make this even clearer, we could completely separate the two sources of variation. On the one hand, we could extract just the individual trends, which would capture just the between variation. On the other hand, we can subtract these trends from the data, and we would be left just with the within variation: ![](blob:https://longitudinalanalysis.com/40cdaa0a-e546-4c8d-a11f-4fde060129f3)![](blob:https://longitudinalanalysis.com/bc0992c5-b315-4a8e-b077-5cba775c4c4d) The multilevel model for change allows us to concurrently model these two sources of variation to indicate what is happening at the individual level. At the same time, it would estimate the average effects, indicating the overall patterns in the data. ## The unconditional change model (a.k.a. random effects) Now that we have a basic understanding of multilevel modeling and longitudinal data we can try them out. We typically start from a simple model that aims to separate within and between variation. We can define the model as follows: Yij=γ00+ξ0i+ϵij Where: - *Yij* is the variable of interest (for example, log income), and it varies by individual (i) and time (j) - *γ00* is the intercept in the regression. We can interpret it as the **grand mean** or the average of the outcome over all the individuals and time points - *ξ0i* is the **between variation** and tells us how different people are from each other in their income. If everyone had the same income, this would be 0. The more different they are, the larger this coefficient will be - *ϵij* this is the residual but also has here the interpretation of **within variation** and tells us how much each individual varies around their average. The larger this coefficient, the more individuals fluctuate in their outcomes Now that we know what we want to model, let’s see how to do it in `R` and `lme4`. For estimating multilevel models, we will use the `lmer()` command. We need to give the data and the formula. Our outcome is “logincome”, so that is on the left side of `~`. We have “1” on the right side, which stands for the intercept. In the brackets, we define the random effects. Here we say that we want the intercept, (“1”) to vary by individual (“\| pidp”). This all leads to this syntax: ``` # unconditional means model (a.k.a. random effects model) m0 <- lmer(data = usl, logincome ~ 1 + (1 | pidp)) # check results summary(m0) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + (1 | pidp) ## Data: usl ## ## REML criterion at convergence: 488875.1 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.1929 -0.1640 0.1208 0.3555 4.0537 ## ## Random effects: ## Groups Name Variance Std.Dev. ## pidp (Intercept) 1.1198 1.0582 ## Residual 0.8712 0.9334 ## Number of obs: 152509, groups: pidp, 50995 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.782034 0.005373 1262 ``` So, let’s interpret the main coefficients: - under “Fixed effects,” we have the “(Intercept)”, 6.78, which is the grand mean (*γ00*) and tells us that over all the time points and individuals, the average log income is 7.16 - under “Random effects,” everything that varies by “pidp” represents **between variation**. In this case, the between variation for the intercept (*ξ0i*) is 1.12 - under “Random effects,” the “Residual” coefficient represents **within variation**. In this case, the within variation for the intercept (*ϵij*) is 0.87 To make the between and within variation easier to understand, we can calculate the **IntraClass Coefficient** (**ICC**): ρ=σ0/(σ0+σϵ)=1.12/(1.12+0.87)=0.56 Where the σ0 stands for the **between variation** and σϵ **within variation** The equation is just a ratio of the two and tells us the proportion of variation that is between individuals. In our case, it shows that around 56% of the variation in log income is caused by differences between people while the remaining (~ 44%) is within people. Substantively, this would indicate that the differences between people in income are more important than within ones (i.e., Bob can work as much as he wants, but it’s doubtful that he will become the next Jeff Bezos). To better understand what the model does, we can predict the scores and do a graph showing the predicted individual score (lines) and the observed ones (points) for five individuals: ``` usl$pred_m0 <- predict(m0, newdata = usl, allow.new.levels = TRUE) set.seed(1234) random_people <- unique(usl$pidp) |> sample(3) usl %>% filter(pidp %in% random_people) %>% # select just five individuals ggplot(aes(wave, pred_m0, color = as.factor(pidp))) + geom_point(aes(wave, logincome)) + # points for observer logincome geom_smooth( method = lm, se = FALSE, size = 0.7) + # linear line based on prediction# geom_smooth(data = usl, group = 1, method = lm, se = FALSE, color = "black") + # linear line based on prediction theme_bw() + # nice theme labs(x = "Wave", y = "Logincome") + # nice labels theme(legend.position = "none") # hide legend ``` ![predicted scores based on a random effect model](https://longitudinalanalysis.com/wp-content/uploads/2024/02/image-4-1024x731.png) A few things to notice here. We are predicting just one score for each individual, so at this point, we don’t have any change in time (lines are horizontal). The differences between the lines represent **between variation** (e.g., blue is higher than green) while the difference between lines and points of the same color represents **within variation** (observed individual scores are different to their prediction). ## The unconditional change model This model helps give us an idea of how much variation we have at each level, but we also want to look at changes in time! So, let’s expand the model: Yij=γ00+γ10TIMEij+ξ0i+ϵij In this model, we add time (“wave” in our case) as a predictor. Now γ00 will represent average income when time is 0 while γ10 represents the rate of change of income when time goes up by 1. To make things easier to interpret, let’s change our time variable a little. We want it to start from 0, so the γ00 has a nice interpretation of expected log income at the start of the study. So here we use a new variable where we subtract 1 from wave: ``` # create new variable starting from 0 usl <- mutate(usl, wave0 = wave - 1) # see how it looks like count(usl, wave, wave0) ``` ``` ## # A tibble: 4 × 3 ## wave wave0 n ## ## 1 1 0 51007 ## 2 2 1 51007 ## 3 3 2 51007 ## 4 4 3 51007 ``` Now we can run our model by adding the new time variable as a fixed effect: ``` # unconditional change model (a.k.a. MLMC) m1 <- lmer(data = usl, logincome ~ 1 + wave0 + (1 | pidp)) summary(m1) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave0 + (1 | pidp) ## Data: usl ## ## REML criterion at convergence: 486596.1 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.4071 -0.1733 0.1190 0.3684 4.1306 ## ## Random effects: ## Groups Name Variance Std.Dev. ## pidp (Intercept) 1.1099 1.0535 ## Residual 0.8565 0.9254 ## Number of obs: 152509, groups: pidp, 50995 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.661570 0.005903 1128.58 ## wave0 0.107170 0.002231 48.03 ## ## Correlation of Fixed Effects: ## (Intr) ## wave0 -0.424 ``` The main difference with the previous model is in the fixed effects part. Now, we interpret the intercept (6.66) as the expected log income at the beginning of the study (wave 1). The effect of “wave0”, 0.107, tells us the average rate of change with the passing of a wave. So, individual log income slowly increases each wave. Again, let’s visualize the results based on the model: ``` usl$pred_m1 <- predict(m1, newdata = usl, allow.new.levels = T) usl %>% filter(pidp %in% random_people) %>% # select just five individuals ggplot(aes(wave, pred_m1, color = as.factor(pidp))) + geom_point(aes(wave, logincome)) + # points for observer logincome geom_smooth(method = lm, se = FALSE, size = 0.7) + # linear line based on prediction geom_smooth(data = usl, group = 1, method = lm, se = FALSE, color = "black") + # linear line based on prediction theme_bw() + # nice theme labs(x = "Wave", y = "Logincome") + # nice labels theme(legend.position = "none") # hide legend ``` ![predicted change in time based on multilevel model for change with no between variation for time](https://longitudinalanalysis.com/wp-content/uploads/2024/02/image-2-1024x731.png) So now we see a positive trend which is due to the coefficient for time. We also notice that the lines are parallel. This means that we assume the change in time is the same for all individuals. In more technical terms, we assume there is no **between variation** in the rate of change. This is typically quite a strong assumption. In our case, we wouldn’t expect that given the first graph we created. So, let’s expand the model to include the between variation in the rate of change: Yij=γ00+γ10TIMEij+ξ0i+ξ1iTIMEij+ϵij Now, we see that we have two sources of **between variation**. The coefficient ξ0i represents the **between variation at the start of the study,** while ξ1i represents the **between variation in the rate of change**. This means that we allow individuals to have different logincomes at wave 1 and different trends. To run such a model in `lme4` we can simply add “wave0” to the random part of the model: ``` # unconditional change model (a.k.a. MLMC) with re for change m2 <- lmer(data = usl, logincome ~ 1 + wave0 + (1 + wave0 | pidp)) summary(m2) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave0 + (1 + wave0 | pidp) ## Data: usl ## ## REML criterion at convergence: 481633.8 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.6628 -0.1560 0.1112 0.3260 4.6631 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 1.64416 1.2822 ## wave0 0.08809 0.2968 -0.71 ## Residual 0.71638 0.8464 ## Number of obs: 152509, groups: pidp, 50995 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.657833 0.006575 1012.62 ## wave0 0.115675 0.002460 47.02 ## ## Correlation of Fixed Effects: ## (Intr) ## wave0 -0.624 ## optimizer (nloptwrap) convergence code: 0 (OK) ## Model failed to converge with max|grad| = 0.00502323 (tol = 0.002, component 1) ``` *You can ignore the warning regarding convergence for now.* In the results, we see that the random part of the model now has two coefficients that vary by “pidp”. The “(Intercept)”, 1.64, represents **between variation at the starting point of the study** (ξ0i) while, the coefficient for “wave0”, 0.088, represents **between variation in the rates of change** (ξ1i). If we now investigate the predictions, we see that individuals are allowed to have both different starting points and different trends: ``` # let's look at prediction base on this model usl$pred_m2 <- predict(m2, newdata = usl, allow.new.levels = T) usl %>% filter(pidp %in% random_people) %>% # select just five individuals ggplot(aes(wave, pred_m2, color = as.factor(pidp))) + geom_point(aes(wave, logincome)) + # points for observer logincome geom_smooth(method = lm, se = FALSE, size = 0.7) + # linear line based on prediction geom_smooth(data = usl, group = 1, method = lm, se = FALSE, color = "black") + # linear line based on prediction theme_bw() + # nice theme labs(x = "Wave", y = "Logincome") + # nice labels theme(legend.position = "none") # hide legend ``` ![predicted trajectories of change in logincome based on multilevel model for change](https://longitudinalanalysis.com/wp-content/uploads/2024/02/image-1-1024x731.png) The larger the ξ0i coefficient, the more prominent the difference between people at the start of the study, while larger ξ1i indicates more diverse rates of change. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions Hopefully, this gives you an idea about what is the multilevel model for change, how to estimate it in `R`, and how to visualize this change. This model is similar to the [Latent Growth Model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) and a made an intro to that [here](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/). You can learn how to expand the model to include time-constant predictors and time-varying predictors [here](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/) and [here](https://longitudinalanalysis.com/understanding-time-varying-predictors-in-multilevel-models-for-longitudinal-data/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, multilevel modeling, r, visualization --- ### [How to run a multiple mediation model in R](https://longitudinalanalysis.com/a-multiple-mediation-model-r/) **Published:** June 19, 2026 **Author:** Alex Cernat **Excerpt:** Fit a multiple mediation model in R with lavaan using parallel, serial, and longitudinal examples with code and path diagrams. **Content:** Representing complex social relationships using statistical models is often a challenge. Popular techniques like regression analysis do not really capture the full complexity of relationships between variables. One approach to moving beyond this simplistic model is to use techniques such as mediation analysis. This allows for the inclusion of multiple pathways to better represent the relationship between variables. In [a previous post](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/), we introduced mediation analysis, and we looked at some relatively simple examples. Here, we extend this to examine what happens in a more complex situation when using a multiple mediation model. As an example, let’s consider the association between being single and life satisfaction. Physical health, mental health, and income could each contribute to that association. Estimating three separate single-mediator models would only give us a limited and bias image of the relationships in the data. To better understand these relationships we need a multiple mediation model. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! # What is a multiple mediation model? A standard mediation model contains one mediator between a predictor and an outcome. A multiple mediation model contains two or more mediators. The mediators can operate in parallel, in sequence, or through a mixture of both. Parallel mediation asks whether several mechanisms explain the a relationship at the same time. Serial mediation makes a stronger claim: one mediator changes another mediator, which then changes the outcome. The distinction matters because the indirect effect is calculated from different paths. In the R package `lavaan`, an indirect effect is defined by labelling regression coefficients and multiplying them. For a pathway from `X` to `M` to `Y`, the indirect effect is `a*b`: ``` model <- ' M ~ a*X Y ~ b*M + c*X indirect := a*b total := c + indirect ' ``` For a refresher on the single-mediator case, see the [practical introduction to path and mediation analysis in R](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/). The official [`lavaan` mediation tutorial](https://lavaan.ugent.be/tutorial/mediation.html) also explains parameter labels and defined effects. # How to fit a multiple mediation model in R The examples use `usw`, which is [the wide data from Understanding Society](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/), where each respondent represents one row and repeated measurements have wave suffixes such as `_1`, `_2`, and `_3`. ``` load("./data/us_clean_syn.RData") dat <- usw |> mutate( age_num = as.numeric(haven::zap_labels(age)), age10 = (age_num - mean(age_num, na.rm = TRUE)) / 10, female = ifelse(gndr.fct == "Female", 1, 0), degree = ifelse(degree.fct == "Degree", 1, 0), single1 = as.numeric(haven::zap_labels(single_1)) ) dat |> select(single1, degree, age10, female, logincome_1, sati_1, sf12pcs_1, sf12mcs_1, sf12pcs_2, sf12mcs_2, sati_3) |> summary() ``` ``` ## single1 degree age10 female ## Min. :0.0000 Min. :0.0000 Min. :-2.9534 Min. :0.0000 ## 1st Qu.:0.0000 1st Qu.:0.0000 1st Qu.:-1.4534 1st Qu.:0.0000 ## Median :0.0000 Median :0.0000 Median :-0.1534 Median :1.0000 ## Mean :0.3864 Mean :0.3251 Mean : 0.0000 Mean :0.5473 ## 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.: 1.3466 3rd Qu.:1.0000 ## Max. :1.0000 Max. :1.0000 Max. : 5.5466 Max. :1.0000 ## NA's :111 ## logincome_1 sati_1 sf12pcs_1 sf12mcs_1 ## Min. :2.303 Min. :1.000 Min. : 4.41 Min. : 0.00 ## 1st Qu.:6.267 1st Qu.:5.000 1st Qu.:45.08 1st Qu.:45.91 ## Median :7.012 Median :6.000 Median :53.46 Median :52.99 ## Mean :6.633 Mean :5.248 Mean :49.49 Mean :50.44 ## 3rd Qu.:7.581 3rd Qu.:6.000 3rd Qu.:57.20 3rd Qu.:57.16 ## Max. :9.211 Max. :7.000 Max. :74.90 Max. :76.35 ## NA's :42 NA's :11581 NA's :3593 NA's :3593 ## sf12pcs_2 sf12mcs_2 sati_3 ## Min. : 5.06 Min. : 0.00 Min. :1.000 ## 1st Qu.:44.66 1st Qu.:44.62 1st Qu.:4.000 ## Median :53.56 Median :51.83 Median :6.000 ## Mean :49.76 Mean :49.84 Mean :5.115 ## 3rd Qu.:57.49 3rd Qu.:57.09 3rd Qu.:6.000 ## Max. :71.95 Max. :77.09 Max. :7.000 ## NA's :23293 NA's :23293 NA's :23641 ``` Age is centred and divided by ten, so a one-unit increase means ten years. The models adjust for age and gender to control for their possible confounding. # Example 1: Two parallel mediators In the first example we explore whether being single is associated with life satisfaction through physical and mental health. The two mediators are estimated together and their residuals are allowed to correlate to account for any common variance. ``` model_1 <- ' sf12pcs_1 ~ a1*single1 + age10 + female sf12mcs_1 ~ a2*single1 + age10 + female sati_1 ~ b1*sf12pcs_1 + b2*sf12mcs_1 + c*single1 + age10 + female sf12pcs_1 ~~ sf12mcs_1 ind_physical := a1*b1 ind_mental := a2*b2 ind_total := ind_physical + ind_mental total := c + ind_total ' fit_1 <- fit_mediation(model_1) ``` ![Flow diagram showing how being single relates to physical and mental health, which contribute to life satisfaction.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/a-multiple-mediation-model-example-1-6-1024x469.webp) Blue arrows are positive and red arrows are negative. The labels show standardised coefficients. Age, gender, and the mediator residual correlation remain in the fitted model but are omitted from the diagram. Here are the key coefficients of interest: | Effect | Estimate | SE | p | 95% CI | Standardized | |---|---|---|---|---|---| | ind\_physical | -0.049 | 0.003 | <.001 | \[-0.055, -0.044\] | -0.016 | | ind\_mental | -0.076 | 0.006 | <.001 | \[-0.087, -0.065\] | -0.025 | | ind\_total | -0.125 | 0.006 | <.001 | \[-0.138, -0.113\] | -0.042 | | total | -0.266 | 0.016 | <.001 | \[-0.297, -0.236\] | -0.089 | Indirect effects for the two-mediator model Being single predicts poorer physical and mental health. Both health measures predict higher life satisfaction, so both indirect effects are negative. The indirect effect through physical health is -0.049; the effect through mental health is -0.076. Together they account for an indirect effect of -0.125 points on the satisfaction scale. Mental health provides a stronger pathway, but both effects are small. With more than 50,000 respondents, small coefficients can be estimated precisely, so statistical significance should not be mistaken for practical importance. # Example 2: Three mediators in a multiple mediation model A multiple mediation model can include more than two mediators. Here, we add log income to the physical- and mental-health pathways. ``` model_2 <- ' sf12pcs_1 ~ a1*single1 + age10 + female sf12mcs_1 ~ a2*single1 + age10 + female logincome_1 ~ a3*single1 + age10 + female sati_1 ~ b1*sf12pcs_1 + b2*sf12mcs_1 + b3*logincome_1 + c*single1 + age10 + female sf12pcs_1 ~~ sf12mcs_1 + logincome_1 sf12mcs_1 ~~ logincome_1 ind_physical := a1*b1 ind_mental := a2*b2 ind_income := a3*b3 ind_total := ind_physical + ind_mental + ind_income total := c + ind_total ' fit_2 <- fit_mediation(model_2) ``` Here is a visual representation of the results and the main coefficients of interest: ![Infographic: a flow diagram where 'Single' leads to 'Physical health', 'Mental health', and 'Log income', all pointing to 'Life satisfaction'.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/a-multiple-mediation-model-example-2-6-1024x469.webp) | Effect | Estimate | SE | p | 95% CI | Standardized | |---|---|---|---|---|---| | ind\_physical | -0.051 | 0.003 | <.001 | \[-0.057, -0.045\] | -0.017 | | ind\_mental | -0.077 | 0.006 | <.001 | \[-0.088, -0.065\] | -0.025 | | ind\_income | 0.015 | 0.002 | <.001 | \[0.011, 0.019\] | 0.005 | | ind\_total | -0.113 | 0.007 | <.001 | \[-0.126, -0.099\] | -0.037 | | total | -0.266 | 0.016 | <.001 | \[-0.297, -0.236\] | -0.089 | Indirect effects for the three-mediator model The physical-health (-0.051) and mental-health (-0.077) pathways are negative. The income pathway is small and positive (0.015). It partially offsets the health pathways rather than reinforcing them. This is exactly why separate mediation models are a poor substitute for one multiple-mediator model. Separate models would not show how the pathways compete after accounting for the same controls and the other mediators. # Example 3: Parallel and serial pathways together The third model uses degree status as the predictor and mental health as the outcome. Education can operate through income alone, satisfaction alone, or income followed by satisfaction. ``` model_3 <- ' logincome_1 ~ a*degree + age10 + female sati_1 ~ d*logincome_1 + e*degree + age10 + female sf12mcs_1 ~ b*sati_1 + f*logincome_1 + c*degree + age10 + female ind_income := a*f ind_satisfaction := e*b ind_serial := a*d*b ind_total := ind_income + ind_satisfaction + ind_serial total := c + ind_total ' fit_3 <- fit_mediation(model_3) ``` Again, here is the visual representation and main coefficients. ![Directed diagram of causal links: Degree influences Log income, Life satisfaction, and Mental health; Log income also affects Life satisfaction; a red arrow highlights a direct path from Log income to Life satisfaction; Life satisfaction influences Mental health.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/a-multiple-mediation-model-example-3-6-1024x469.webp) | Effect | Estimate | SE | p | 95% CI | Standardized | |---|---|---|---|---|---| | ind\_income | 0.056 | 0.024 | 0.019 | \[0.009, 0.103\] | 0.003 | | ind\_satisfaction | 0.467 | 0.042 | <.001 | \[0.384, 0.549\] | 0.022 | | ind\_serial | -0.032 | 0.011 | 0.003 | \[-0.054, -0.011\] | -0.001 | | ind\_total | 0.490 | 0.047 | <.001 | \[0.399, 0.582\] | 0.023 | | total | 1.222 | 0.093 | <.001 | \[1.04, 1.404\] | 0.057 | Indirect effects for the hybrid model The satisfaction-only pathway is the largest (0.467). By comparison, the income-only pathway is positive but small (0.056). A negative serial pathway (-0.032) appears because, conditional on education and the other controls, income has a small negative association with satisfaction in this synthetic dataset. # Example 4: Longitudinal parallel mediation The previous examples use only cross-sectional data. Their paths make assumptions about causal order but the variables are measured at the same wave. This means that we are just assuming the relationships go in that particular direction. When using longitudinal data we can use the temporal order to help us decide on the causal direction. In this example, age at the first wave predicts physical and mental health at wave 2. Those mediators predict life satisfaction at wave 3. The model controls wave-1 physical health, mental health, and satisfaction in both the mediator and outcome equations. ``` model_4 <- ' sf12pcs_2 ~ a1*age10 + sf12pcs_1 + sf12mcs_1 + sati_1 + female sf12mcs_2 ~ a2*age10 + sf12pcs_1 + sf12mcs_1 + sati_1 + female sati_3 ~ b1*sf12pcs_2 + b2*sf12mcs_2 + c*age10 + sati_1 + sf12pcs_1 + sf12mcs_1 + female sf12pcs_2 ~~ sf12mcs_2 ind_physical := a1*b1 ind_mental := a2*b2 ind_total := ind_physical + ind_mental total := c + ind_total ' fit_4 <- fit_mediation(model_4) ``` ![Diagram of a causal model: Age (+10 years) influences physical health and mental health, which in turn influence life satisfaction (W3). Arrows show pathways including a curved path from Age to Life satisfaction.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/a-multiple-mediation-model-example-4-6-1024x469.webp) Baseline controls are omitted from the diagram but remain in the model and are shown below. | Effect | Estimate | SE | p | 95% CI | Standardized | |---|---|---|---|---|---| | ind\_physical | -0.013 | 0.002 | <.001 | \[-0.017, -0.009\] | -0.015 | | ind\_mental | 0.011 | 0.001 | <.001 | \[0.009, 0.013\] | 0.013 | | ind\_total | -0.002 | 0.002 | 0.365 | \[-0.006, 0.002\] | -0.002 | | total | 0.039 | 0.006 | <.001 | \[0.027, 0.05\] | 0.046 | Indirect effects for the longitudinal model | Outcome | Predictor | Estimate | p | Standardized | |---|---|---|---|---| | sf12pcs\_2 | age10 | -1.371 | <.001 | -0.226 | | sf12pcs\_2 | sf12pcs\_1 | 0.487 | <.001 | 0.500 | | sf12pcs\_2 | sf12mcs\_1 | 0.092 | <.001 | 0.084 | | sf12pcs\_2 | sati\_1 | 0.317 | <.001 | 0.043 | | sf12pcs\_2 | female | 0.029 | 0.791 | 0.001 | | sf12mcs\_2 | age10 | 0.443 | <.001 | 0.083 | | sf12mcs\_2 | sf12pcs\_1 | 0.029 | <.001 | 0.034 | | sf12mcs\_2 | sf12mcs\_1 | 0.169 | <.001 | 0.175 | | sf12mcs\_2 | sati\_1 | 1.568 | <.001 | 0.238 | | sf12mcs\_2 | female | -0.896 | <.001 | -0.046 | | sati\_3 | sf12pcs\_2 | 0.009 | <.001 | 0.068 | | sati\_3 | sf12mcs\_2 | 0.025 | <.001 | 0.157 | | sati\_3 | age10 | 0.041 | <.001 | 0.048 | | sati\_3 | sati\_1 | 0.204 | <.001 | 0.198 | | sati\_3 | sf12pcs\_1 | 0.001 | 0.253 | 0.010 | | sati\_3 | sf12mcs\_1 | 0.007 | <.001 | 0.044 | | sati\_3 | female | 0.002 | 0.914 | 0.001 | Regression paths for the longitudinal model The physical-health indirect effect is negative (-0.013), while the mental-health indirect effect is positive (0.011). Both are different from zero. Their sum is only -0.002 and is not statistically significant. While longitudinal mediation improves our understanding of the relationships in the data it does come with assumptions. Time-varying events between waves could affect both health and satisfaction, and the spacing of the waves may not match the speed of the process. The model could be extended to include more controls and pathways to get closer the real world mechanisms. For a fuller treatment of temporal ordering, see the [guide to longitudinal mediation in R](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! # Choosing a multiple mediation model What type of mediation processes should you use in your research? The main guide should be grounded in theory or prior empirical findings. Usually, the parallel mediation is a good starting point. Use a serial model only when the sequence is supported by theory or the timing of the data collection. If repeated waves are available, a longitudinal model with baseline controls is usually more credible, although it does not remove all time-varying confounding. # Where to go next Mediation models (and SEM more generally) force users to put their theoretical expectations on paper. While this makes it more challenging, it often makes an important contribution to our understanding of the mechanisms underlying the relationships of interest. If you want a structured treatment of mediation, moderation, assumptions, and interpretation in R, [**see the mediation and moderation course**](https://longitudinalanalysis.com/). For another worked example now, read the [longitudinal mediation guide with R code](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis, statistics **Tags:** longitudinal data analysis, mediation analysis, r, structural equation modelling --- ### [Mediating vs Moderating Variable: How to Choose the Right One](https://longitudinalanalysis.com/mediating-vs-moderating-variable-how-to-choose-the-right-one/) **Published:** January 26, 2026 **Author:** Alex Cernat **Excerpt:** Mediating vs moderating variable with examples. Learn how to distinguish between mediation and moderation, choose the right model, and avoid common mistakes. **Content:** One of the most common sources of confusion in research is the distinction between a mediating vs moderating variable. Many researchers know that both involve a “third variable,” yet struggle to decide which concept applies to their research question. This confusion manifests in many ways. Researchers are often unsure whether a variable explains *how* an effect works or *when* it works. They are also unclear about how to include these variables in the model. These problems are not merely technical; they reflect a deeper conceptual ambiguity. At its core, the issue is that mediating and moderating variables answer fundamentally different questions. This post clarifies the differences between mediating and moderating variables, helping you decide which framework best fits your analysis. --- ## What Is a Mediating Variable? A **mediating variable** explains *how or why* an independent variable (X) influences a dependent variable (Y). Conceptually, a mediator sits **inside the causal chain** between X and Y. The effect of X on Y is transmitted, fully or partially, through the mediator (M). In other words, X affects M, and M in turn affects Y. We can visually represent this relationship in a graph like this: ![Mediation model with three variables using path analysis. The graph helps visualize difference between a mediating vs moderating variable](https://longitudinalanalysis.com/wp-content/uploads/2026/01/image.webp) Classic examples include education influencing health through income, autonomy shaping employee turnover through job satisfaction, or political knowledge affecting electoral participation through trust. In each case, the mediating variable represents a **mechanism** that translates an initial cause into an outcome, making mediation analysis central to theory-driven explanations of social processes. Modern approaches for modelling such relationships include path analysis, structural equation models, and causal mediation frameworks. You can find out more about estimating such models in this [blog post on mediation](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/). So, mediation analysis is appropriate when you have a clear theory about **processes or pathways**. It is useful when your goal is to explain *why* an effect exists rather than merely whether it is present. This approach also works when the temporal or causal ordering X→M→YX \\rightarrow M \\rightarrow Y is theoretically defensible. This tends to be easier if you have longitudinal data, leading to longitudinal mediation, which we introduce [here](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/). ## Want to learn more? Check [our on-demand course on moderation and mediation](https://leanpub.com/c/mediation-moderation-r). [Explore course](https://leanpub.com/c/mediation-moderation-r) ## What Is a Moderating Variable? A **moderating variable** explains **when, for whom, or under what conditions** an independent variable (X) influences a dependent variable (Y). Conceptually, a moderator does **not** sit inside the causal chain between X and Y. Instead, it changes the **strength or direction** of their relationship. In other words, the effect of X on Y depends on the value of the moderator (W). We can see this visually in the graph below: ![Moderation model with three variables. The graph helps visualize difference between a mediating vs moderating variable](https://longitudinalanalysis.com/wp-content/uploads/2026/01/image-1.webp) Classic examples include the effect of stress on health differing by gender, the relationship between education and income varying by cohort, or the impact of political information on turnout depending on political interest. In each case, the moderator captures **heterogeneity or context**, identifying situations in which an effect is stronger, weaker, or absent. Modern approaches to moderation include using regression models with interaction effects, multi-group analysis or Johnson-Neyman Intervals. You can find a practical introduction to estimating moderation models in this blog post [on moderation](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/). So, moderation analysis is appropriate when your theory predicts that **relationships depend on contextual factors** or if you expect **effect heterogeneity**. It is useful when you want to explain *when* or *for whom* an effect occurs rather than *why*. ## Mediating vs Moderating Variable: Key Differences Although mediators and moderators are both “third variables,” they answer **different questions**. Here is a summary of how a mediating vs moderating variable can be distinguished. | Dimension | Mediating Variable | Moderating Variable | |---|---|---| | ***Main question*** | **How / why** does X affect Y? | **When / for whom** does X affect Y? | | ***Causal role*** | Lies **between** X and Y | Alters the **X–Y relationship** | | ***Typical focus*** | Mechanisms and processes | Contexts and conditions | | ***Statistical test*** | Indirect effects (paths a × b) | Interaction terms or group differences | | ***Model position*** | Endogenous (both cause and effect) | Exogenous (independent variable) | | ***Statistical models used*** | Path analysis, causal mediation, Structural Equation Modelling | Interaction effects, multi-group analysis, multilevel models | When not sure which one to use, ask yourself, is the third variable a **mechanism** through which X is causing Y? If yes, then most likely it is a mediation. If, on the other hand, the variable describes **context** or **conditions** in which the effects happen, think of moderation. Other things to consider are whether the variable is plausibly caused by X or exists independently of it. If it is caused by X, it suggests a possible mediation process. On the other hand, if you find unexpected results, consider if it could be due to moderation effects. For example, you are looking at a particular group where the relationships differ. Real-world research is often much more complex and does not limit itself to a simple dichotomy of a mediating vs moderating variable. Theories and data highlight complex patterns that involve **both mediation and moderation** rather than only one. For example, job training (X) may increase long-term earnings (Y) by boosting confidence (M). But this mediating process may be stronger for workers with high social support or weaker for those in precarious labour markets. In such cases, the mediation happens only under certain conditions. This leads to **moderated mediation** (when the indirect effect varies across contexts) or **mediated moderation** (when an interaction effect operates through a mediator). A practical introduction to these approaches, with diagrams and applied examples, is available [in this guide](https://longitudinalanalysis.com/a-guide-to-moderated-mediation-and-mediated-moderation/). ## Finding a mediating vs moderating variable in your own research Distinguishing between a mediating vs moderating variable is ultimately a theoretical decision, not a statistical one. Mediating variables help explain *how or why* an effect occurs by identifying the mechanism linking a cause to an outcome. Meanwhile, moderating variables help you understand *when, for whom, or under what conditions* the effect holds. Clear conceptual thinking is needed to understand the role of such variables in your model. Once that is clear, using the appropriate statistical model is easier. When deciding whether a variable in your own research is mediating or moderating, start from your substantive theory and research question. Ask whether the variable lies inside the causal process you are trying to explain, or whether it defines contexts in which an effect becomes stronger, weaker, or disappears. Clarifying this distinction early will guide your study design, model specification, and interpretation of results, and will help you do better research. If you’re interested in how these distinctions translate into actual models, including interaction terms, indirect effects, and their interpretation. I cover these topics in detail in my applied course, [Mediation and Moderation Analysis using R](https://leanpub.com/c/leanpub/mediation-moderation-r). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** statistics **Tags:** mediation, moderation, statistics --- ### [Visualizing transitions in time using R and alluvial graphs](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how to visualize transitions in time for categorical data using Sankey plot/river/alluvial graphs and R. Easy hands one example using real data **Content:** Working with longitudinal data is exciting as we can see how people, societies and institutions change in time. Often, it helps to visualize this change to understand better what is happening and to help tell a good story. While visualizing change in time for continuous variables is relatively straightforward, it is a little more complicated when we have categorical variables. One solution to this is the Sankey plot/river/alluvial graph. Here, I’m going to show you how to create such a plot in `R`. Here are the packages we will be using: ``` # package for data cleaning and graphs library(tidyverse) # package for alluvial plots library(ggalluvial) # optional # nice themes library(ggthemes) # nice colors library(viridis) ``` As an example data source, I will use the survey outcomes from five waves of the [Understanding Society Innovation Panel](https://www.understandingsociety.ac.uk/documentation/innovation-panel). This is part of [some methodological work](https://ojs.ub.uni-konstanz.de/srm/article/view/7669) we have been doing to understand how people answer using different interview modes (like face-to-face and web) at different times in a longitudinal study. ``` # load local data data <- read.csv("./data/ex_trans.csv") # have a look at our data head(data) ## id out_5 out_6 out_7 out_8 out_9 ## 1 1 F2f Web Web Web Web ## 2 2 F2f Web Web Web Web ## 3 3 Other non-resp Web Web Web Web ## 4 4 Other non-resp Web Other non-resp Other non-resp Not-issued ## 5 5 F2f F2f Web Web Web ## 6 6 Other non-resp Refusal Web Refusal Web ``` ## Cleaning the data So we have the data in wide format, where each row is an individual (“id” = individual), and then we have the outcomes at five waves (5 to 9). The first thing we need to do is to summarize the data. What we need is a count of all the possible transitions that can take place in our data. There are a couple of ways of doing that, but the easiest is to use the `count()` command with the outcome variables. We also create a unique ID, which is just the row number in the dataset, so we can quickly identify the unique patterns later on. *`%>%` is called a pipe and just lets us chain multiple commands in a way that is easy to read. It takes the results from what is on the left of it and gives it as input to the command to the right.* ``` # calculate all combinations, make unique id and save data2 <- count(data, out_5, out_6, out_7, out_8, out_9) %>% mutate(id = row_number()) # create new id variable # look at data head(data2) ## out_5 out_6 out_7 out_8 out_9 n id ## 1 F2f F2f F2f F2f F2f 73 1 ## 2 F2f F2f F2f F2f Not-issued 6 2 ## 3 F2f F2f F2f F2f Other non-resp 10 3 ## 4 F2f F2f F2f F2f Refusal 2 4 ## 5 F2f F2f F2f F2f Web 12 5 ## 6 F2f F2f F2f Not-issued F2f 1 6 ``` So far, so good. We have a nice dataset with all possible combinations of transitions. We must restructure the data to a long format to create the graph. Again, there are many ways to do that, but the easiest is using the gather() command. Here, we say what the data is, the names of the two new variables and any variables we do not want to restructure (`-n, -id` tells `R` to ignore these variables when it restructures the data). ``` # make long data data3 <- gather(data2, value, key, -n, -id) # look at data head(data3) ## n id value key ## 1 73 1 out_5 F2f ## 2 6 2 out_5 F2f ## 3 10 3 out_5 F2f ## 4 2 4 out_5 F2f ## 5 12 5 out_5 F2f ## 6 1 6 out_5 F2f ``` The new data tells us the wave, the outcome, and how many cases had that type of transition. We can link different kinds of transitions in the long format using the “id” variable. Next, we do some data cleaning. We make a continuous version of the wave variable, make the outcome a factor and change the order of the categories (to make the graph easier to interpret). ``` # clean up data for graph data4 <- data3 %>% mutate(wave = as.numeric(str_remove(value, "out_")), key = as.factor(key), key = fct_relevel(key, "Web", "F2f", "Refusal", "Other non-resp")) # look at the data head(data4) ## n id value key wave ## 1 73 1 out_5 F2f 5 ## 2 6 2 out_5 F2f 5 ## 3 10 3 out_5 F2f 5 ## 4 2 4 out_5 F2f 5 ## 5 12 5 out_5 F2f 5 ## 6 1 6 out_5 F2f 5 ``` ## Doing the graph We have all we need for our graph now! The `ggalluvial` package helps us to make the graph we want, but in the background, it uses the ggplot package. This makes it flexible and extensible (as we will see soon). Using the `ggplot()` command, we give it the dataset and then the main dimensions of the graph (in `aes()`): - on the x-axis, we want time, or “wave” in this case - on the y-axis, we want the frequency, or “n” in our case - we want the bar plots at each wave as well as the `fill` to depend on our outcome, which here is called “key” - `alluvium` is used to define the transitions. We use the “id” for that We use two different “geoms” for our graph. First, `geom_stratum()` creates the bar at each wave. Second, `geom_flow()` creates the transitions between them. Here, we make the graph slightly transparent to make it easier to read (`alpha = .5`). So the syntax looks something like this: ``` # make basic transition graph plot <- ggplot(data4, aes(x = wave, y = n, stratum = key, fill = key, alluvium = id)) + geom_stratum(alpha = .5) + geom_flow() # print plot ``` ![visulize transitions](https://www.alexcernat.com/wp-content/uploads/2021/03/unnamed-chunk-6-1.png) This looks good, but we can make it even better. We will choose a minimalistic theme (theme\_tufte()), add labels and give it nicer colours. We can add these to the previously saved object called (creatively) “plot”. ``` # enhance the look of the graph plot + theme_tufte(base_size = 18) + labs(x = "Wave", y = "Frequency", fill = "Outcome") + scale_fill_viridis_d(direction = -1) ``` ![visulize transitions](https://www.alexcernat.com/wp-content/uploads/2021/03/unnamed-chunk-6-2.png) Much nicer. So here is the full syntax to make the graph once we have the data prepared: ``` # full graph syntax data4 %>% ggplot(aes( x = wave, stratum = key, alluvium = id, y = n, fill = key )) + geom_flow() + geom_stratum(alpha = .5) + theme_tufte(base_size = 18) + labs(x = "Wave", y = "Frequency", fill = "Outcome") + scale_fill_viridis_d(direction = -1) ``` --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** visualization **Tags:** data cleaning, data management, data restructuring, longitudinal data analysis, r --- ### [Complete guide to visualizing longitudinal data in R](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/) **Published:** April 3, 2024 **Author:** Alex Cernat **Excerpt:** Unlock the secrets of longitudinal data in R with this complete guide. Master the art of insightful visualizations for impactful analysis. **Content:** Longitudinal data can be complex as it includes multiple cases with observations at different points in time. This complexity grows with missing data patterns, nested structures like individuals within households, and various variable types (like [time-constant versus time-varying](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). Visualizing this complicated data can help us understand it better. This post will cover the main types of graphs used to explore longitudinal data using R. We will apply these techniques to the synthetic data from our previous post that replicates a large social science panel study. Visualization complements data exploration using tables and summary statistics we covered in [a previous post](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/). ## Preparing for visualization You can follow this guide by running the code in R on your own computer. Our examples will use synthetic (simulated) data modelled after Understanding Society, a comprehensive panel study from the UK. The real data can be accessed for free from the [UK Data Archive](https://beta.ukdataservice.ac.uk/datacatalogue/series/series?id=2000053). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! [In a previous blog](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/), we cleaned the data and stored it in both [the long and the wide formats](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). We will use that cleaned data here. Before we start, make sure you have the `tidyverse` and `haven` packages installed and loaded by running the following code: ``` install.packages("tidyverse") library(tidyverse) library(haven) ``` Although the `haven` package is not required for importing data; it simplifies working with and recoding data originally imported using it. We will use the `ggplot2` package from the `tidyverse` for visualization. Next, we will load the data prepared in the previous post. This contains both the long and the wide format data in an “RData” file. We will load the long-format data and have a quick look at it: ``` load("./data/us_clean_syn.RData") glimpse(usl) ``` ``` ## Rows: 204,028 ## Columns: 32 ## $ pidp 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 10, 10, 10, 10, 11, 11… ## $ wave 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4… ## $ age 28, 28, 28, 28, 80, 80, 80, 80, 60, 60, 60, 60, 42, 42… ## $ hiqual 1, 1, 1, 1, 9, 9, 9, 9, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, … ## $ single 1, 1, 1, 0, 0, 0, 0, 0, 1, NA, NA, NA, 0, NA… ## $ fimngrs 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ sclfsato -9, 6, 2, 1, 6, 6, -8, 3, 2, NA, NA, NA, -9, NA… ## $ sf12pcs 54.51, 62.98, 56.97, 56.15, 53.93, 46.39, NA, 46.16, 33.18… ## $ sf12mcs 55.73, 36.22, 60.02, 59.04, 46.48, 45.39, NA, 37.02, 46.80… ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, … ## $ sf1 2, 2, 1, 3, 4, 3, 3, 3, 5, NA, NA, NA, 2, NA… ## $ present TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, … ## $ gndr.fct Male, Male, Male, Male, Male, Male, Male, Male, Male, Male… ## $ single.fct Single, Single, Single, In relationship, In relationship, … ## $ urban.fct Urban, Urban, Urban, Urban, Urban, Urban, Urban, Urban, Ur… ## $ degree.fct Degree, Degree, Degree, Degree, No degree, No degree, No d… ## $ vote6.fct Not very, Not at all, Not at all, Not at all, Not at all, … ## $ sati NA, 6, 2, 1, 6, 6, NA, 3, 2, NA, NA, NA, NA, NA, 5, NA, NA… ## $ sati.fct NA, Mostly satisfied, Mostly dissatisfied, Completely diss… ## $ fimngrs.cap 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ logincome 8.099818, 8.297170, 8.196070, 6.757514, 6.809039, 6.577861… ## $ year 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, NA, … ## $ sati.ind 3.000000, 3.000000, 3.000000, 3.000000, 5.000000, 5.000000… ## $ sati.dev NA, 3.000000, -1.000000, -2.000000, 1.000000, 1.000000, NA… ## $ sf12pcs.ind 57.65250, 57.65250, 57.65250, 57.65250, 48.82667, 48.82667… ## $ sf12pcs.dev -3.1425000, 5.3275000, -0.6825000, -1.5025000, 5.1033333, … ## $ sf12mcs.ind 52.75250, 52.75250, 52.75250, 52.75250, 42.96333, 42.96333… ## $ sf12mcs.dev 2.977500, -16.532500, 7.267500, 6.287500, 3.516667, 2.4266… ## $ waves 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4… ## $ sati.lag NA, NA, 6, 2, NA, 6, 6, NA, NA, 2, NA, NA, NA, NA, NA, 5, … ## $ sf12pcs.lag NA, 54.51, 62.98, 56.97, NA, 53.93, 46.39, NA, NA, 33.18, … ## $ sf12mcs.lag NA, 55.73, 36.22, 60.02, NA, 46.48, 45.39, NA, NA, 46.80, … ``` ## Simple univariate visualizations We will start with some simple visualizations to get to know `ggplot2`. By diving into the data, let’s uncover how voting trends have shifted over the years. For example, we could look at the voting variable using a barplot. `Ggplot2` is a powerful package for creating visualizations in R. It is based on the grammar of graphics and allows for a high degree of customization. It has two main components: the data with the main dimensions, which are fed in the `ggplot()` command and the geometries, which are added using the `geom_` commands. The dimensions of the graph are set using the `aes()` command. The different parts of the graphs are layered on top of each other using `+`. Having set the stage, let’s create a barplot of the voting variable to demonstrate these concepts in practice. Here, the variable of interest is “vote6.fct”, and the geometry is a barplot (`geom_bar()`): ``` ggplot(usl, aes(vote6.fct)) + geom_bar() ``` ![Bar chart depicting the distribution of voting behavior categories within the dataset. Categories include 'Very', 'Fairly', 'Not very', 'Not at all', and data not available ('NA').](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image.png) We see that `ggplot2` automatically calculates the number of cases in each category and then adjusts the bar height based on this information. At times, raw data may be inaccessible, or we might prefer crafting our own summary statistics for a tailored visualization. The package allows us to do that as well. Let’s imagine that instead of the number of cases, we want to see the proportion of cases in each category. We can do this by making a table with the absolute frequencies and then creating a new variable with the proportions: ``` tab1 <- count(usl, vote6.fct) |> mutate(prop = n / sum(n)) tab1 ``` ``` ## # A tibble: 5 × 3 ## vote6.fct n prop ## ## 1 Very 14638 0.0717 ## 2 Fairly 49363 0.242 ## 3 Not very 41082 0.201 ## 4 Not at all 38036 0.186 ## 5 60909 0.299 ``` *Note that we are using the `|>` (pipe) operator here. We introduced this in [a previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/).* Now, we can redo the barplot using the new variables. For the dimensions, we use the new variables, and for the geometries, we use `geom_bar(stat = "identity")`. This is because we are inputting the values directly and not letting `ggplot2` calculate them: ``` ggplot(tab1, aes(vote6.fct, prop)) + geom_bar(stat = "identity") ``` ![Bar chart showing the proportions of voting behavior categories. Each bar represents a category such as 'Very', 'Fairly', 'Not very', 'Not at all', with the height indicating the proportion of respondents in each category.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-24.png) Let’s next look at a continuous variable. We can start by looking at the distribution of the monthly income variable. We can use a histogram (`geom_histogram()`) for this: ``` ggplot(usl, aes(x = fimngrs.cap)) + geom_histogram() ``` ![Histogram of the monthly income variable, displaying a skewed distribution with a majority of data points concentrated on the lower end of the income scale.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-2.png) We see that income is skewed, with most people on the left of the distribution and relatively few on the right side (with larger incomes). ## Uni-variate visualizations over time ### Continuous variables So far, we looked at the distribution of variables at one point in time. We can also look at how the distribution of variables changes over time. For example, we can investigate how the distribution of mental health (sf12mcs) changes over time. One way to do that is by using a boxplot that shows the median, the interquartile range, and the outliers. We can use the geom\_boxplot() command for this. As we want to look at the distribution over time, we can use the `wave` variable as the x-axis (first input in `aes()`) and the `sf12mcs` as the y-axis (second input in `aes()`): ``` ggplot(usl, aes(as.factor(wave), sf12mcs)) + geom_boxplot() ``` ![Boxplot illustrating the distribution of mental health scores across different waves of the study, with the 'wave' variable treated as categorical.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-1.png) *Note that here we want to treat “wave” as a categorical variable (using `as.factor()`) to have distinct distributions at each wave.* We see that the median and distribution are pretty stable over time. We can also use a violin plot to see the distribution of the variable over time. This is similar to a boxplot but also shows the distribution’s density. We can use the `geom_violin()` command for this: ``` ggplot(usl, aes(as.factor(wave), sf12mcs)) + geom_violin() ``` ![Violin plot depicting the distribution density of mental health scores over time, shown for different waves of data collection](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-3.png) Your visualization goals determine whether to use a boxplot or a violin plot. If you aim to highlight the median and distribution spread, use a boxplot. Conversely, use the violin plot for a detailed view of the distribution’s density. ### Categorical variables We can also look at how the distribution of categorical variables changes over time. For example, to look at how voting behaviour changes over time, we can use the same geom\_bar() command. We can add the fill argument to colour the bars by the categories of the voting variable. Similar to before, we add the `wave` variable to see the change in time. ``` usl |> ggplot(aes(wave, fill = vote6.fct)) + geom_bar() ``` ![Chart showing the stability of proportions within voting behavior categories over time](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-4.png) We observe that the big trend is the increasing number of missing data due to the drop-off in the study. We can also look at the proportion of each category over time while ignoring the missing cases. We first filter all the missing cases out and then use the `position == "fill"` option to calculate the proportions within each wave. This results in: ``` usl |> filter(!is.na(vote6.fct)) |> ggplot(aes(wave, fill = vote6.fct)) + geom_bar(position = "fill") ``` ![barplot of voting over time](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-6.png) Once we remove the missing cases, we will see that the proportions for each category are pretty stable over time. This aggregate stability could hide individual-level changes. We explore this in a separate post using a [Sankey plot/river/alluvial graph](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/). We can further explore the aggregate distribution of voting over time by creating our own statistics. We use again the `count()` command to calculate the number of cases in each category and then calculate the proportion of cases in each category: ``` tab4 <- usl |> filter(!is.na(vote6.fct)) |> group_by(wave) |> count(vote6.fct) |> mutate(prop = n / sum(n)) tab4 ``` ``` ## # A tibble: 16 × 4 ## # Groups: wave [4] ## wave vote6.fct n prop ## ## 1 1 Very 4948 0.104 ## 2 1 Fairly 16107 0.339 ## 3 1 Not very 13968 0.294 ## 4 1 Not at all 12520 0.263 ## 5 2 Very 3824 0.106 ## 6 2 Fairly 12732 0.353 ## 7 2 Not very 10161 0.282 ## 8 2 Not at all 9334 0.259 ## 9 3 Very 3020 0.0971 ## 10 3 Fairly 10759 0.346 ## 11 3 Not very 8927 0.287 ## 12 3 Not at all 8404 0.270 ## 13 4 Very 2846 0.100 ## 14 4 Fairly 9765 0.344 ## 15 4 Not very 8026 0.282 ## 16 4 Not at all 7778 0.274 ``` We can use this table to create an alternative barplot where we have a different plot at each wave, and the height depends on the proportions we calculated. The `position = "dodge"` option puts the bars next to each other while the `stat = "identity"` option makes the bars have the height we calculated: ``` tab4 |> ggplot(aes(wave, prop, fill = as.factor(vote6.fct))) + geom_bar(position = "dodge", stat = "identity") ``` ![Chart showing the stability of proportions within voting behavior categories over time](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-11.png) We can flip the axes and have the different categories on the x-axis to make it easier to see the changes over time. We can do this by switching the `x` and `fill` arguments in the `aes()` command: ``` tab4 |> ggplot(aes(x = vote6.fct, prop, fill = as.factor(wave))) + geom_bar(position = "dodge", stat = "identity") ``` ![Chart showing the stability of proportions within voting behavior categories over time](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-8.png) Again, we see that the proportions are pretty stable over time. Which version of the graph you should use depends on what you want to show. The first version is better for showing the overall distributions and how they change in time, while the second facilitates comparisons within categories over time. ## Simple change plots for 2-3 time points Sometimes, we want to compare the distribution of a variable at two or three time points. This could be due to data limitations (we only have 2-3 waves) or the fact that we want to highlight the overall change in a certain period. There are two popular ways to do this, both of which combine points and lines. Imagine we want to see the overall change in the likelihood of voting from the start of the study (2009 in our case) to the end (2014). Let’s start by calculating the proportion of people voting each year. We can use the `filter()` command to keep only the relevant years and then use the `group_by()` and `count()` commands to calculate the number of cases in each category. We can then calculate the proportion of cases in each category: ``` tab2 <- usl |> filter(year %in% c(2009, 2014)) |> group_by(year) |> count(vote6.fct) |> mutate(prop = n / sum(n)) tab2 ``` ``` ## # A tibble: 10 × 4 ## # Groups: year [2] ## year vote6.fct n prop ## ## 1 2009 Very 2446 0.0998 ## 2 2009 Fairly 7846 0.320 ## 3 2009 Not very 7048 0.288 ## 4 2009 Not at all 6661 0.272 ## 5 2009 512 0.0209 ## 6 2014 Very 122 0.0985 ## 7 2014 Fairly 412 0.333 ## 8 2014 Not very 302 0.244 ## 9 2014 Not at all 292 0.236 ## 10 2014 110 0.0889 ``` One strategy to visualize such data is to have a line for each category and points for the proportions at each time. We can also add a line between the points to facilitate visualisation of the change. In the plot below, we add the proportions on the y-axis and the categories on the x-axis. We colour the lines and points by the year and group them by category. We use the `geom_point()` command to add the points and the `geom_line()` command to add the lines: ``` tab2 |> ggplot(aes(prop, vote6.fct, color = as.factor(year), group = vote6.fct)) + geom_point() + geom_line() ``` ![line plot showing change in voting behaviour over time](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-9.png) *Note that we must make “year” a factor to treat the years as* distinct categories. We also need to make the voting variable *the `group` to make lines for each category.* We see that the proportion of people choosing “Not at all” has increased over time while the proportion of people choosing “Very” has remained pretty stable. We can make the graph a little nicer by excluding missing cases, reversing the order of the labels (using `fct_rev()`), adding labels (`labs()`) and changing the theme (`theme_bw()`): ``` tab2 |> na.omit() |> mutate(Year = as.factor(year), Vote = fct_rev(vote6.fct)) |> ggplot(aes(prop, Vote, color = Year, group = Vote)) + geom_point() + geom_line() + labs(y = "Vote", x = "Proportion") + theme_bw() ``` ![line plot showing change in voting behaviour over time. nice formatting](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-10.png) The second strategy for visualizing such data is to have a line for each category and points for the proportions at each point in time. This is similar to the previous plot, but the x-axis and y-axis are switched. Here, the slope of the lines shows the amount of change we have in our data. We can do this by switching the `prop` and `year` variables in the `aes()` command: ``` tab2 |> na.omit() |> ggplot(aes(as.factor(year), prop, color = vote6.fct, group = vote6.fct)) + geom_point() + geom_line() + labs(y = "Proportion", x = "Year", color = "Voting") + theme_bw() ``` ![alternative line plot showing change in voting behaviour over time. nice formatting](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-25.png) *Note that we need to add `group = vote6.fct` to force the creation of the line across the discrete time points.* Adopting a similar approach allows us to track how a continuous variable evolves over time. For example, if we want to see how satisfaction has changed between 2009 and 2014 based on the residence of the respondents we can filter the data, group it by “urban.fct” and “year” and calculate the mean satisfaction. We can then visualize this using the same approach as before: ``` tab3 <- usl |> filter(year %in% c(2009, 2014)) |> group_by(year, urban.fct) |> summarise(mean_sati = mean(sati, na.rm = T)) tab3 ``` ``` ## # A tibble: 4 × 3 ## # Groups: year [2] ## year urban.fct mean_sati ## ## 1 2009 Rural 5.39 ## 2 2009 Urban 5.24 ## 3 2014 Rural 5.20 ## 4 2014 Urban 5.02 ``` The first type of plot we covered above would be: ``` tab3 |> ggplot(aes(mean_sati, urban.fct, color = as.factor(year), group = urban.fct)) + geom_point() + geom_line() + labs(y = "Residence", x = "Mean satisfaction", color = "Year") + theme_bw() ``` ![line plot showing change in time of satisfaction by residence](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-5.png) While the second would be created using: ``` tab3 |> ggplot(aes(as.factor(year), mean_sati, color = urban.fct, group = urban.fct)) + geom_point() + geom_line() + labs(y = "Mean satisfaction", x = "Year", color = "Residence") + theme_bw() ``` ![line plot showing change in time of satisfaction by residence](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-7.png) Satisfaction deteriorated for both groups at similar rates. The second graph makes it a little easier to see the differences between the groups in terms of the rate of change. ## Line graphs The line graph is the most popular type of visualization when we have longitudinal data. It is pretty flexible, as it can capture different types of changes and can be done both at the individual level and the aggregate level. ### Individual-level line graphs A good way to get an intuition about the data, especially when it is large, is to sample just a few cases and see how they change over time. We can do this by randomly sampling a few people from the data. Before that, setting up a starting point for the sampling procedure is useful. This will ensure that we consistently get the same results (and your graphs will look the same as mine if you are trying to run this on your own computer). We can do this using the `set.seed()` command: ``` set.seed(1234) ``` We can then sample 20 people from the data and create a smaller version with only these people in it. Here, we first select all unique IDs (using unique(usl$pidp)) and then use the sample() command to select 20 of them randomly: ``` random_people <- unique(usl$pidp) |> sample(20) ``` We then create a smaller dataset using only these individuals: ``` susl <- filter(usl, pidp %in% random_people) ``` Now, we can use this data to look at individual changes in time. We will look at how mental health changed over time using the `geom_line()` command. The `group` argument needs to be used to make sure that the lines are connected for the same individual: ``` ggplot(susl, aes(wave, sf12mcs, group = pidp)) + geom_line() ``` ![Line graph showcasing the mental health trajectories of 20 randomly selected individuals across four waves. Each line represents one individual's mental health score trend over time, illustrating the variability in mental health changes.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-12.png) We see that there is some variation, with some people improving while others deteriorating. To simplify reading individual trends, let’s create separate graphs for each person by using `facet_wrap()`: ``` susl |> ggplot(aes(wave, sf12mcs, group = pidp)) + geom_line() + facet_wrap(~ pidp, ncol = 5) + theme(strip.text.x = element_blank(), strip.background = element_blank()) ``` ![Collection of small line graphs, each representing one individual's mental health trend over four waves. The graphs are arranged in a grid, facilitating comparison across individuals.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-13.png) *Note that we ask for the graphs to be shown in five columns using `ncol = 5` and remove the heading with the individual ID that appears by default using `theme()`.* Such graphs are also useful to inform how to model the change in time for the variable of interest. For example, if we employ linear models using either multilevel or latent growth modelling, we will estimate the time change for each individual with a straight line. We can see how well this would represent the individual change by adding a linear trend for each individual. The `geom_smooth()` command with the argument `method = "lm"` will add a linear trend line to the graph: ``` susl |> ggplot(aes(wave, fimngrs.cap, group = pidp)) + geom_line() + geom_smooth(method = "lm", se = F, alpha = 0.5) + facet_wrap(~ pidp, ncol = 5) + theme(strip.text.x = element_blank(), strip.background = element_blank()) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/06/image.png) *Note that the `se = F` argument for removing the confidence intervals for the trend line.* We see that a linear trend would capture the change in time pretty well for most individuals. ### Aggregate line graphs Another aspect we might want to explore is how the average mental health changes over time. We can do this by adding a summary line to the graph. The `stat_summary()` command will calculate the mean for each wave and then add a line and a point for each wave. We can use the fun = mean argument to tell ggplot2 to calculate the mean and the geom = “line” and geom = “point” arguments to tell it to add a line and a point, respectively: ``` susl |> ggplot(aes(wave, fimngrs.cap)) + geom_line(aes(group = pidp), alpha = 0.3) + stat_summary(fun = mean, geom = "line", color = "blue") + stat_summary(fun = mean, geom = "point", size = 2, color = "blue") ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-15.png) When looking at the aggregate change in time, it is useful to use the full dataset. We can use either the `geom_smooth()` command to calculate a trend or the average from the data. Below is a graph that shows both: ``` usl |> ggplot(aes(wave, sf12mcs)) + geom_smooth(method = "lm", se = F) + stat_summary(fun = mean, geom = "line", color = "red") ``` ![Line graph depicting the average mental health scores across four waves. The graph includes both a smooth trend line and points representing the mean scores at each wave, highlighting overall trends in mental health.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-14.png) In this case, the linear model is slightly different from the average in the data. This might indicate that a nonlinear model might better represent the change in mental health. We can explore this in a separate post using [growth curve modelling](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/) and the [multilevel model for change](https://longitudinalanalysis.com/estimating-non-linear-change-in-time-using-the-multilevel-model-for-change/). ### Trends by groups In addition to looking at the overall change in time, we might want to see how this differs among groups. For example, we might want to see how the change in mental health differs by education level. We can do this by adding colour to the lines for each group. The color argument in the aes() command will colour the lines by the group, and the `group` argument to make sure that the lines are connected for the same group: ``` ggplot(usl, aes(wave, sf12mcs, color = degree.fct, group = degree.fct)) + geom_smooth(method = "lm") ``` ![Line graph showing the trends in mental health over time, differentiated by education level. Lines represent the average mental health scores for individuals with and without a degree, indicating differences and changes over time.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-20.png) We could make this graph a little nicer by removing the missing cases, adding the labels and changing the theme: ``` usl |> filter(!is.na(degree.fct)) |> ggplot(aes(wave, sf12mcs, color = degree.fct, group = degree.fct)) + geom_smooth(method = "lm") + theme_bw() + labs(y = "Mental health", x = "Wave", color = "Education") ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-21.png) We see that people with a degree have higher mental health than those without. We also see that the difference between the two groups decreases over time. We can add another dimension to the graph by using faceting (i.e., multiple graphs by group). We can do this by adding the `facet_wrap()` command to the graph. In this case, we will make a separate graph for each category of the “urban.fct” variable: ``` ggplot(usl, aes(wave, sf12mcs, color = degree.fct, group = degree.fct)) + geom_smooth(method = "lm") + facet_wrap(~ urban.fct) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-17.png) This graph is useful for exploring **moderation effects**. In this case, we could explore how time changes for people with a degree and without depending on where they live. To make it a little easier to compare, we can remove the missing cases: ``` usl |> filter(!is.na(urban.fct)) |> filter(!is.na(degree.fct)) |> ggplot(aes(wave, sf12mcs, color = degree.fct, group = degree.fct)) + geom_smooth(method = "lm") + facet_wrap(~ urban.fct) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-16.png) Here, we see that there is a convergence in mental health for people with and without a degree. This is happening both in rural and urban areas, although the initial difference is larger in urban areas. Sometimes, having all the groups in the same graph is easier to interpret. We can add an interaction directly to the `aes()` by adding the `:` between the two variables: ``` usl |> filter(!is.na(urban.fct)) |> filter(!is.na(degree.fct)) |> ggplot(aes(wave, sf12mcs, color = degree.fct:urban.fct, group = degree.fct:urban.fct)) + geom_smooth(method = "lm") ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-18.png) Now, it’s clearer that people with no degree in urban areas have the lowest levels of mental health, and while the differences go down over time, they are still present in wave 4. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ### Area graphs Another way to visualize change over time is using area graphs. These are similar to line graphs, but colours fill the area under the line. This can be useful when we have multiple groups and want to see how the change in time is distributed between them. We can use the geom\_area() command to create area graphs. We can use the fill argument to colour the areas by the group and the `position = "stack"` argument to stack the areas on top of each other. To see how the likelihood of voting has changed over time, we can use: ``` usl |> group_by(wave) |> count(vote6.fct) |> na.omit() |> mutate(prop = n / sum(n), wave = as.numeric(wave)) |> ggplot(aes(wave, n, fill = vote6.fct)) + geom_area(position = "stack") ``` ![Stacked area graph illustrating the change in proportions of voting behavior categories over time. The areas are color-coded by voting behavior, showing the dynamics of each category across four waves](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-23.png) We can use a similar approach if we want to summarize a continuous variable using a categorical one. For example, we can look at how mental health has changed over time for people with a degree and people without one. To facilitate comparisons, we can overlay the two areas using `position = "identity"` and render them transparent with `alpha = 0.4`: ``` usl |> filter(!is.na(degree.fct)) |> group_by(year, degree.fct) |> summarise(meantal_health = mean(sf12mcs, na.rm = T)) |> ggplot(aes(year, meantal_health, fill = degree.fct)) + geom_area(position = "identity", alpha = 0.4) ``` ![Area graph showing the average mental health scores over time, separated by education level. The areas overlap and are semi-transparent, allowing for comparison of trends between those with and without a degree.](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-19.png) Overall, the two distributions are pretty similar, indicating no differences in mental health by education level. We can look at another example where we average satisfaction by voting behaviour. Here, we stack the areas and remove missing cases in voting to make it easier to read: ``` usl |> filter(!is.na(vote6.fct)) |> group_by(year, vote6.fct) |> summarise(satisfaction = mean(sati, na.rm = T)) |> ggplot(aes(year, satisfaction, fill = vote6.fct)) + geom_area(position = "stack") ``` ![Stacked area graph depicting the average satisfaction levels over time, categorized by voting behavior. Each area represents a voting category, illustrating how satisfaction changes across categories over time](https://longitudinalanalysis.com/wp-content/uploads/2024/04/image-22.png) ### Exporting the graphs Once we create the graphs we want, we can easily export them using the ggsave() command. This command takes the name of the file we want to save. For example, to save the last graph we created, we can use a png file we can run: ``` ggsave("satisfaction_by_vote.png") ``` The command is pretty flexible. You can also save a graph and export it later. Other common things you might want to change are the format, height, width and resolution (dpi). For example, we create a graph and export it as a tiff file with a resolution of 300 dpi, a width of 10 inches and a height of 5 inches: ``` grph1 <- ggplot(usl, aes(wave, sf12mcs, color = degree.fct, group = degree.fct)) + geom_smooth(method = "lm") ggsave(grph1, "mental_health_degree.tiff", device = "tiff", dpi = 300, width = 10, height = 5) ``` ## Conclusions ![visualizing longitudinal data using R key commands](https://longitudinalanalysis.com/wp-content/uploads/2024/04/long_process_visualize_crop-222x300.png) In this guide, we journeyed through the art of visualizing longitudinal data with R. We started by looking at simple univariate visualizations and then moved to more complex ones, discussing both continuous and categorical data. This should cover the most common types of graphs used with longitudinal data. You can see a summary of the key commands in the figure. Now that you’re armed with these techniques, why not dive into your data and uncover the stories waiting to be told? Have we overlooked anything? We welcome your questions and insights in the comments below. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management, visualization **Tags:** data exploration, data management, visualization --- ### [AI Agent for Data Analysis and Why You Need Taste](https://longitudinalanalysis.com/ai-agent-for-data-analysis-and-why-you-need-taste/) **Published:** July 10, 2026 **Author:** Alex Cernat **Excerpt:** An AI agent for data analysis can write code quickly, but researchers still have to build expertise and understand what decisions are made **Content:** Watching an AI agent do data analysis is quite impressive. In a few minutes, it can handle relatively complex data, involving importing, merging, cleaning, and analysing it. The amount of code produced in a short amount of time is truly impressive. Now you can leave tools like [Claude Code](https://www.anthropic.com/claude-code) or [OpenAI Codex](https://openai.com/codex/) to work for hours on your data. When they finish, you will see something that looks reasonable, but at the end of the day, they produce a black box that becomes increasingly complex. In this post, I want to step back from the usual “how to” format. Instead, I will reflect on how tools like these are changing the way we do quantitative analysis. ## Three ways of writing analysis code If you have done quantitative research for a while and also tried to keep up with advances in coding tools, you have probably written code in three different ways. The first is the traditional way where you write code yourself, line by line. It is slow and methodical. You need to make a plan and go step by step, from describing your data to analysis ([see an example of a longitudinal workflow](https://longitudinalanalysis.com/understanding-the-longitudinal-data-workflow-a-comprehensive-guide/)). While it is time-consuming, it also provides an opportunity to learn about the data and make important decisions, such as how to recode variables, whom to include or exclude in the analysis, and so on. The second way to write code is the assisted way, using tools like [GitHub Copilot](https://github.com/features/copilot). The tool watches what code you write and suggests the next line or block. This can be really helpful sometimes, though about half the time it doesn’t recommend exactly the code you want. You can reject the suggestions, but sometimes you might accept some code that is almost what you want just because it is faster. For example, it might recommend a more verbose way of coding than you normally use. The third way to code is to use coding agents, such as [Claude Code](https://www.anthropic.com/claude-code) or [Codex](https://openai.com/codex/). Here you describe an outcome, such as “clean these five waves of data, merge them, and run a fixed effects model”. Then the AI agent for data analysis writes, runs, debugs and revises the code and creates a report. Now you have moved from analysis to commissioning. ![Three ways of using AI agent for data analysis](https://longitudinalanalysis.com/wp-content/uploads/2026/07/ChatGPT-Image-Jul-10-2026-10_52_22-AM-1024x576.webp) ## What an AI agent for data analysis decides for you Here is the problem with just asking the AI agent to “clean this dataset and run the analysis”. It sounds like one instruction, but in reality, it contains tens of decisions. Anyone who works with data knows this intimately. Take something as routine as [cleaning and merging multiple waves of data](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/). Do you keep everyone who appears in at least one wave, or only complete cases? How do you treat someone who skipped wave 3 but returned in wave 4? What about a variable measured on a 5-point scale in early waves and a 7-point scale later? None of these has a “correct” answer. Andrew Gelman called this [the garden of forking paths](http://www.stat.columbia.edu/~gelman/research/unpublished/p_hacking.pdf). The same nominal analysis contains thousands of possible routes, yet researchers only ever see the one they walked. When you write the code by hand, you walk the garden yourself. Slowly, sometimes badly, but you see (most of) the forks. In contrast, when an AI agent for data analysis does the work, the garden disappears from view and decisions are made for you. You get somewhere faster, but you’re not sure how you got there and if it’s really where you want to be. ## Reasonable can still be wrong Of course, you can ask the agent to explain its choices, and it will do so eloquently. But being told about a fork is not the same as having stood at one and made your own decision. A justification you are handed is something you check for plausibility. A decision you make yourself is weighed against everything you know about the data and the research question. These are different mental operations, and only one of them builds expertise. The uncomfortable part is that the agent’s choices are, individually, almost always reasonable. If an AI agent for data analysis wrote bad code, we could potentially catch it. But as the code becomes more complex and the amount of AI-created code increases, this becomes more difficult to identify. Also, small decisions can compound, leading to an implausible result. ## Taste: the skill an AI agent cannot give you One essential skill when starting to automate statistical analyses is expertise, or “taste”. By taste, I mean the ability to recognise good-quality work as well as problems, based on countless hours of writing and reviewing code and results. This is an essential skill that enables you to identify key decisions and mistakes. Taste is not intelligence, and it is not textbook knowledge. It is an intuitive sense of how analyses go wrong, built from past experiences and failures. The building blocks of taste are the hundreds of mistakes you have made over the long hours you have spent working with data. ## What AI agents for data analysis mean for teaching and training This brings me to the part I actually worry about: current students and new researchers. Traditionally, part of doing quantitative analysis was spending time with data and code, finding errors and making hundreds of decisions. This is tedious work, but it is also where “taste” and expertise are developed. Now the AI agent does the grunt work. As a result, new researchers can produce a polished analysis in an afternoon without confronting a single decision. They will be more productive than we were at their stage, and they will have learned less. Worse, their output gives no outward sign of the difference. So the question is not whether students should use these tools. They will. The question is how to develop taste and expertise when the tools remove the experiences that build it. So, while we figure out how best to use AI coding agents for doing quantitative analyses, we also need to consider how to build the skills needed for the next generation of researchers. ## Three practical suggestions Things are changing very fast, and I don’t have a complete answer, but I think there are two things we should consider given the current state of these models. First, sequencing. Students need extended contact with raw, messy data before they automate anything. They should write the [cleaning and preparation code](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) themselves, hit the forks themselves, and sometimes choose wrong. Aviation is a useful comparison. Pilots learn the fundamentals through extensive manual practice before being expected to manage advanced automation. Second, teach how to audit work produced by AI agents, as well as how to create guardrails. For example, we could give students a pipeline built by an AI agent for data analysis and have them interrogate it as a reviewer would. Where did observations disappear? What happened to the missing data? What are the important decisions, and how can we ensure we are in the loop? We also need to keep experimenting with these new tools to develop best practices for working with AI in quantitative analyses. This will also help us understand what skills new researchers need. ## Conclusions on AI agents for data analysis An AI agent for data analysis can walk the garden of forking paths for you. But you still have to know the garden and what paths have been taken. That knowledge is built by hand, one small mistake at a time, ideally inside a [reproducible workflow](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/) that makes your decisions visible. And while we figure out how best to integrate AI tools into our work, we also need to discover how best to develop “taste” and expertise in the next generation of researchers. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** AI, data analysis --- ### [Understanding causal direction using the cross-lagged model](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how to investigate the causal direction of two variables using the cross-lagged model and longitudinal data. Hands on example using R and real data **Content:** Longitudinal data, or data collected multiple times from the same cases, are increasingly popular. They come in many shapes and sizes, from traditional panel surveys to social media, administrative, or sensor data. One of the great strengths of this type of data is its ability to facilitate causal analysis. While it does not “prove causality”, by understanding the causal order of events, we can get one step closer to understanding the underlying processes involved in the social world. This type of data can also help answer one particular kind of question that appears in many fields: what is the causal direction of variables? For example, we might know that mental and physical health are related, but we might not be sure which is the cause and which is the effect. We may have plausible theoretical mechanisms in both directions. For example, a decrease in physical health can lead to anxiety, depression and outcomes associated with mental health. We can also think of an opposite process where a sudden reduction in mental health can lead to lower physical health due to a decrease in physical activity. Longitudinal data can be used to disentangle such processes. One of the models developed explicitly to investigate such questions is the cross-lagged model. This model uses the Structural Equation Modelling (SEM) framework to estimate the two processes concurrently while controlling for possible confounders. In this blog post, we will walk through how to apply this method using R and how you can formally test the causal direction of two variables. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! --- ## The cross-lagged model To understand this model, we can use the SEM visualization framework. In this framework, observed variables are represented by squares, regression coefficients by single-headed arrows, correlations by double-headed arrows, and residuals by small circles. Given this notation, we can represent the cross-lagged model using such a graph: ![Visual representation of the cross-lagged model in the Structural Equation Modelling framework](https://www.alexcernat.com/wp-content/uploads/2022/12/cross_lag_eq-1024x678.png)Visual representation of the cross-lagged model in the Structural Equation Modelling framework Here, we have two variables of interest: *x* and *y*. They are each measured at three points in time (e.g., *x*1, *x*2, *x*3). The model has three different parts: 1. **Cross-lagged effects** capture the impact of one variable at a previous wave on another’s current values. For example, λy21 (lambda) represents the effect of *y* in wave 1 on *x* in wave 2. The opposite effect, *λx21*, represents the effect of x in wave 1 on *y* in wave 2. By comparing these two coefficients, we can understand if the effects in one direction are stronger than those in the other. This comparison is at the heart of this model and informs us about the causal direction. 2. **Stability coefficients** capture how stable each variable is. It is estimated by including **auto-regressive** coefficients in which the values at the previous wave influence the values at the current wave. For example, coefficient *βy21* (beta) captures the stability of y1 on y2. If *y* represents something like mental health, we would interpret it as the stability of mental health from wave 1 to wave 2. The closer the value is to 1, the more stable the variable (i.e., cases don’t change their rank order on mental health). If the coefficient is close to 0, it means that the previous values do not affect the current status, while if it is -1, it means that the order of the individuals on that variable is reversed. Typically, in this model, we are not interested in this type of coefficient, but we treat it as a control. We are effectively controlling for previous levels of *x* and *y*, which, in turn, makes the assumption of controlling for possible confounders more plausible. These coefficients are also known as lag-1 effects or a Markov chain, as the model implies that only the prior wave information is important for the current status. 3. **Time-specific correlations** capture the correlation between the two variables of interest at each point in time. They also control possible time-specific confounders that might impact both variables. For example, a global pandemic may occur during the data collection at the second time point, leading to a decrease in both *x* and *y*. These correlations would capture this process and control for it. We can also represent the model using a set of formulas. These represent the same model as above. The ***β*** coefficients represent the **stability,** and the *λ* represents the cross-lagged effects. The *ϵ* (epsilon) is each dependent variable’s regression residual coefficients (or unexplained variance). The ν (nu) represents the intercept or the expected value of the outcome when the predictors are 0. Lastly, we correlate *x* and *y* at each **wave** (***j***). *x**j* = *ν**xj* + *β**x*, *j*, *j* − 1*x**j* − 1 + *λ**y*, *j*, *j* − 1*y**j* − 1 + *ϵ**xj* *y**j* = *ν**yj* + *β**y*, *j*, *j* − 1*y**j* − 1 + *λ**x*, *j*, *j* − 1*x**j* − 1 + *ϵ**yj* *Cov*(*x**j*,*y**j*) --- ## Running the cross-lagged model in R Now that we have an idea about why we would use the cross-lagged model and its main components, we can see how to estimate it in R. Here, we will use data from the first three waves of the [Understanding Society survey](https://www.understandingsociety.ac.uk/). Our research question focuses on the causal direction of mental health (“mcsc”) and physical health (“pcsc”). These are calculated scores based on the SF12 scale. The values go from 0 to 100, where a higher number = better health. *Here, we centred the variables. We do this by subtracting the average from each variable, so the new mean is 0. This does not change regression coefficients but does make intercepts easier to interpret.* To run the model, we use the `lavaan` package. ``` library(tidyverse) library(lavaan) load("./data/us_clean_syn.RData") usw <- usw |> mutate( pcsc_1 = sf12pcs_1 - mean(sf12pcs_1, na.rm = TRUE), pcsc_2 = sf12pcs_2 - mean(sf12pcs_2, na.rm = TRUE), pcsc_3 = sf12pcs_3 - mean(sf12pcs_3, na.rm = TRUE), mcsc_1 = sf12mcs_1 - mean(sf12mcs_1, na.rm = TRUE), mcsc_2 = sf12mcs_2 - mean(sf12mcs_2, na.rm = TRUE), mcsc_3 = sf12mcs_3 - mean(sf12mcs_3, na.rm = TRUE) ) ``` We split the process into three steps. First, we write the model as a simple text object and save it as “model”: ``` model <- 'pcsc_2 ~ 1 + pcsc_1 + mcsc_1 pcsc_3 ~ 1 + pcsc_2 + mcsc_2 mcsc_2 ~ 1 + mcsc_1 + pcsc_1 mcsc_3 ~ 1 + mcsc_2 + pcsc_2 pcsc_1 ~~ mcsc_1 pcsc_2 ~~ mcsc_2 pcsc_3 ~~ mcsc_3' ``` We have four regression models represented by the “~” symbol. We have the dependent variable or outcome on the left of the symbol. On the right side, we have the predictors or independent variables. For example, the first line says that we want to explain physical health in wave 2 (“pcsc\_2”) by physical health in wave 1 (“pcsc\_1”, this represents stability) and mental health in wave 1 (“mcsc\_1”, this represents the cross-lagged effect). The “1” value in the regression represents the intercept. We also include correlations between variables at each wave, represented by `~~`. *Note that `lavaan` figures out* if the correlation is between the observed variables *or the residuals.* Now that we have the model, we can estimate it using the `sem()` command. We give it as inputs the model and the data (“usw” stands for Understanding Society in wide format). We also add an option to estimate the model using Full Information Maximum Likelihood (`missing = "ML"`). This uses all the available information to estimate the model and leads to fewer missing cases in the model than listwise deletion (which is the default). ``` m1 <- sem(model, data = usw, missing = "ML") ``` Now that the model is stored as “m1”, we can print the results using the `summary()` command. We also ask for the standardized coefficients using the `standardized = TRUE` option. ``` summary(m1, standardized = TRUE) ## lavaan 0.6-19 ended normally after 91 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 23 ## ## Used Total ## Number of observations 48440 51007 ## Number of missing patterns 7 ## ## Model Test User Model: ## ## Test statistic 5063.374 ## Degrees of freedom 4 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Observed ## Observed information based on Hessian ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## pcsc_2 ~ ## pcsc_1 0.607 0.005 128.736 0.000 0.607 0.618 ## mcsc_1 0.102 0.005 18.908 0.000 0.102 0.091 ## pcsc_3 ~ ## pcsc_2 0.570 0.005 107.215 0.000 0.570 0.583 ## mcsc_2 0.079 0.006 12.413 0.000 0.079 0.070 ## mcsc_2 ~ ## mcsc_1 0.290 0.006 51.353 0.000 0.290 0.302 ## pcsc_1 0.036 0.005 7.095 0.000 0.036 0.042 ## mcsc_3 ~ ## mcsc_2 0.452 0.006 75.997 0.000 0.452 0.457 ## pcsc_2 0.069 0.005 13.154 0.000 0.069 0.081 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## pcsc_1 ~~ ## mcsc_1 0.795 0.535 1.485 0.138 0.795 0.007 ## .pcsc_2 ~~ ## .mcsc_2 -10.064 0.496 -20.279 0.000 -10.064 -0.123 ## .pcsc_3 ~~ ## .mcsc_3 -15.103 0.498 -30.304 0.000 -15.103 -0.197 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .pcsc_2 -0.391 0.052 -7.503 0.000 -0.391 -0.035 ## .pcsc_3 -0.111 0.056 -1.983 0.047 -0.111 -0.010 ## .mcsc_2 -0.265 0.055 -4.812 0.000 -0.265 -0.027 ## .mcsc_3 0.015 0.053 0.275 0.783 0.015 0.002 ## pcsc_1 -0.024 0.053 -0.458 0.647 -0.024 -0.002 ## mcsc_1 -0.004 0.046 -0.077 0.938 -0.004 -0.000 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .pcsc_2 77.832 0.662 117.539 0.000 77.832 0.610 ## .pcsc_3 80.159 0.726 110.466 0.000 80.159 0.658 ## .mcsc_2 86.335 0.734 117.594 0.000 86.335 0.907 ## .mcsc_3 73.169 0.662 110.468 0.000 73.169 0.787 ## pcsc_1 132.207 0.859 153.861 0.000 132.207 1.000 ## mcsc_1 102.607 0.666 153.978 0.000 102.607 1.000 ``` The coefficients of interest are under the “Regressions” section of the output. Physical health has stability coefficients of **0.607** and 0.570, while the corresponding mental-health coefficients are **0.290** and 0.452. The outcomes therefore remain related to their earlier values, although the estimates are smaller than those in the previous output. The cross-lagged effects from mental health to later physical health are **0.102** and **0.079**. The corresponding effects from physical health to later mental health are **0.036** and **0.069**. All four effects are statistically different from zero. As before, the results suggest reciprocal relationships, with the mental-to-physical paths somewhat larger at both transitions. To help interpret this model, I recommend drawing the model and adding the observed coefficients in the appropriate place. For example, if we take the coefficients from the output and put them in the SEM figure, we would get: ![Cross lagged panel model showing three waves of physical and mental health with coefficients estimated from the synthetic data.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/cross_lagged_estimates.webp)Cross-lagged panel model with estimates from the synthetic data The graph shows that mental and physical health are related in both directions. The mental-to-physical effect is larger at each transition. Next, we can test formally whether the two coefficients at the first transition differ significantly. *Note that here, the two variables use the same scale, and we can compare them using the unstandardized coefficients. When the variables have different scales, either rescale them or interpret the standardized coefficients (the last column in the output “Std.all”).* --- ## Testing the equality of cross-lagged coefficients The SEM framework offers some useful tools for explicitly testing the equality of coefficients. The typical procedure for this is to run a model without constraints (like the one we ran above) and then run a model with some constraints. These can be added by fixing a coefficient to a particular value (e.g., saying a regression coefficient is 0) or forcing some coefficients to be equal. Our research question focuses on the equality of the cross-lagged effects. We want to formally test if the impact of mental health on physical health is significantly different from the reverse relationship. Adding such a restriction gives the two coefficients the same “name.” Below is a visual representation where we show how we would restrict the cross-lagged effects from wave 1 to wave 2 to be called “a” while those from wave 2 to wave 3 to be called “b.” ![Cross-lagged model with conceptual representaiton of equality testing](https://www.alexcernat.com/wp-content/uploads/2022/12/cross-lagged_2-1024x722.png)The cross-lagged model with the conceptual representation of equality testing In general, I recommend doing this in stages. Here, we test whether the cross-lagged coefficients from wave 1 to wave 2 are equal. This compares **0.102** with **0.036** in the population. If the restricted model fits significantly worse, we can conclude that the two effects differ. To add a name or a restriction in `lavaan` we simply put the value before the coefficient with a “`*`” next to it. The code below fixes the cross-lagged coefficients from wave 1 to wave 2 to be called “a” (thus making them equal). ``` model <- 'pcsc_2 ~ 1 + pcsc_1 + a*mcsc_1 pcsc_3 ~ 1 + pcsc_2 + mcsc_2 mcsc_2 ~ 1 + mcsc_1 + a*pcsc_1 mcsc_3 ~ 1 + mcsc_2 + pcsc_2 pcsc_1 ~~ mcsc_1 pcsc_2 ~~ mcsc_2 pcsc_3 ~~ mcsc_3' m2 <- sem(model, data = usw, missing = "ML") summary(m2, standardized = TRUE) ## lavaan 0.6-19 ended normally after 92 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 23 ## Number of equality constraints 1 ## ## Used Total ## Number of observations 48440 51007 ## Number of missing patterns 7 ## ## Model Test User Model: ## ## Test statistic 5142.904 ## Degrees of freedom 5 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Observed ## Observed information based on Hessian ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## pcsc_2 ~ ## pcsc_1 0.603 0.005 128.335 0.000 0.603 0.616 ## mcsc_1 (a) 0.066 0.004 18.166 0.000 0.066 0.060 ## pcsc_3 ~ ## pcsc_2 0.570 0.005 107.139 0.000 0.570 0.581 ## mcsc_2 0.083 0.006 13.141 0.000 0.083 0.074 ## mcsc_2 ~ ## mcsc_1 0.296 0.006 52.594 0.000 0.296 0.306 ## pcsc_1 (a) 0.066 0.004 18.166 0.000 0.066 0.078 ## mcsc_3 ~ ## mcsc_2 0.451 0.006 76.022 0.000 0.451 0.458 ## pcsc_2 0.065 0.005 12.415 0.000 0.065 0.076 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## pcsc_1 ~~ ## mcsc_1 0.775 0.535 1.447 0.148 0.775 0.007 ## .pcsc_2 ~~ ## .mcsc_2 -10.088 0.498 -20.277 0.000 -10.088 -0.123 ## .pcsc_3 ~~ ## .mcsc_3 -15.105 0.498 -30.301 0.000 -15.105 -0.197 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .pcsc_2 -0.372 0.052 -7.138 0.000 -0.372 -0.033 ## .pcsc_3 -0.116 0.056 -2.070 0.038 -0.116 -0.011 ## .mcsc_2 -0.282 0.055 -5.128 0.000 -0.282 -0.029 ## .mcsc_3 0.019 0.053 0.365 0.715 0.019 0.002 ## pcsc_1 -0.024 0.053 -0.462 0.644 -0.024 -0.002 ## mcsc_1 -0.002 0.046 -0.051 0.959 -0.002 -0.000 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .pcsc_2 77.904 0.663 117.500 0.000 77.904 0.616 ## .pcsc_3 80.173 0.726 110.454 0.000 80.173 0.659 ## .mcsc_2 86.487 0.736 117.486 0.000 86.487 0.900 ## .mcsc_3 73.171 0.662 110.467 0.000 73.171 0.786 ## pcsc_1 132.208 0.859 153.865 0.000 132.208 1.000 ## mcsc_1 102.603 0.666 153.983 0.000 102.603 1.000 ``` In the restricted model, the two coefficients named “a” have the same value: **0.066**. We can now compare this model with the previous one to see whether the equality restriction makes the fit worse. There are different ways to compare models in SEM. A quick way to do it is to use the `anova()` command with the two models we estimated. This will create a small table with the AIC, BIC and the Chi-square test for the difference: ``` anova(m1, m2) ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## m1 4 1516407 1516609 5063.4 ## m2 5 1516485 1516678 5142.9 79.53 0.040264 1 < 2.2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` AIC and BIC are relative fit indices. They do not have a fixed scale, but lower values are better. Based on these two indicators, “m1” is better. We can also use the Chi-square difference test (sometimes represented as Δχ2). This takes the difference of the Chi-square and the degrees of freedom of the two models. The null hypothesis is that the models have equal fit. Here, the test is statistically significant. This implies that the model with the restriction (“m2”) is significantly worse than the first model. As a result, we should select “m1”. All the fit indices favour “m1”. The chi-square difference is **79.53** with one degree of freedom (*p* < .001). We therefore reject the equality restriction and conclude that the mental-to-physical effect of **0.102** is larger than the physical-to-mental effect of **0.036**. We should still be careful when interpreting this comparison. Both cross-lagged coefficients are statistically different from zero, so the results support influence in both directions. Their difference is **0.066** (0.102 − 0.036). Whether this is substantively important depends on the research context, theory and existing evidence. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! --- ## Conclusions We saw how we can use longitudinal data and the cross-lagged model to understand the causal direction of two variables. This model is useful when we have two related variables but are unsure about the causal direction. We saw how we can run the model in R and `lavaan` and how we can formally test the equality of the coefficients. The model represents an elegant way to test the causal direction. It also has the advantage of controlling for some possible confounders. This is done by controlling for the values on the variables of interest at the previous wave (i.e., the stability coefficients) and with the time-specific correlations. That being said, the model is far from perfect. It is still possible to have missing confounders that could bias our estimates (which we might want to control for). You can see how to include controls in [this blog post](https://longitudinalanalysis.com/how-to-include-control-variables-in-a-cross-lagged-panel-model/). Also, in this form, the model does not separate “within” and “between” variation (see this post for a discussion on these two types of variance). The SEM framework is extremely flexible, and the model can be extended to deal with these challenges. --- For more on longitudinal data analysis, check out [an introduction to the multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) and one for the [latent growth model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, r, structural equation modelling --- ### [Estimating and visualizing Latent Growth Models with R](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Tutorial showing you how to visualize change in time and how to estimate it using Latent Growth Modelling with R. Hands on longitudinal data analysis. **Content:** Longitudinal data is very exciting as it enables us to look at change in time, get a better understanding of causal relationships and explain events and their timing. To make use of this type of data typically we need to move beyond classical statistical methods, such as OLS regression and ANOVA, to models that can deal with the extra complexity of the data. One popular model for analyzing longitudinal data is the Latent Growth Model (LGM). This enables the estimation of change in time while taking into account the hierarchical nature of the data (multiple points in times nested within individuals). It is similar to the [multilevel model of change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) but it is estimated using the Structural Equation Modeling (SEM) framework and uses data in [the wide format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (each row is an individual and measurement in time appears as different columns). More precisely the LGM can help: - understand how change happens in time - explain change using time-varying and time-constant predictors - decompose variance in between and within variation - can be easily extended (e.g., mixture LGM, second order LGM, parallel LGM) Here I’m going to give a brief intro to LGM, how to estimate it and how to visualize change estimates. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! First, let’s load the packages. We will use `tidyverse` for cleaning and visualization of the data and `lavaan` for running the LGM in `R`. ``` library(tidyverse) library(lavaan) load("./data/usl_all_syn.RData") # The guide uses the first six waves and a balanced sample. usw <- usl_all |> filter(wave <= 6) |> pivot_wider( names_from = wave, values_from = logincome, names_prefix = "logincome_" ) |> drop_na(logincome_1:logincome_6) usl <- usl_all |> filter(pidp %in% usw$pidp, wave <= 6) ``` The balanced six-wave sample contains 21,178 respondents and 127,068 respondent-wave observations. Before we get into LGM let’s have a look at the kind of data we would want to analyse. Here I use log income from the first six waves of synthetic data based on the [Understanding Society survey](https://www.understandingsociety.ac.uk/). The original study is a large representative panel of the UK population collected every year. Let’s imagine we are interested in how income changes in time. More precisely, we want to see how income changes on average as well as separating **between variation**, how people change compared to others, and **within variation**, how people vary relative to their own average/trend. First, let’s see how the data looks like. Let’s look at the wide data, this is the data used to run LGM: ``` head(usw) ## # A tibble: 6 × 7 ## pidp logincome_1 logincome_2 logincome_3 logincome_4 logincome_5 logincome_6 ## ## 1 1 7.26 7.08 7.01 6.92 7.22 7.18 ## 2 7 6.01 6.14 6.10 5.72 4.26 4.41 ## 3 8 6.59 6.54 6.58 6.78 6.72 6.54 ## 4 11 2.30 2.30 2.30 2.30 2.31 7.25 ## 5 12 5.64 8.09 5.82 5.75 6.08 6.62 ## 6 13 6.23 6.17 6.31 6.34 6.27 6.50 ``` Next, let’s look at the long format where each row is a combination of individual and time. This is the format we need for visualization using `ggplot2 `and for other models (like the [multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/)). ``` head(usl) ## # A tibble: 6 × 3 ## pidp wave logincome ## ## 1 1 1 7.26 ## 2 1 2 7.08 ## 3 1 3 7.01 ## 4 1 4 6.92 ## 5 1 5 7.22 ## 6 1 6 7.18 ``` To get an understanding of what we will be modelling, let’s plot a reproducible sample of 2,000 individual trajectories and calculate the red average line from the full balanced sample. ``` set.seed(20260803) plot_ids <- sample(unique(usl$pidp), 2000) observed_means <- usl |> group_by(wave) |> summarise(logincome = mean(logincome), .groups = "drop") usl |> filter(pidp %in% plot_ids) |> ggplot(aes(wave, logincome, group = pidp)) + geom_line(alpha = 0.01) + geom_line( data = observed_means, aes(wave, logincome), inherit.aes = FALSE, linewidth = 1.5, colour = "red" ) + theme_bw() + labs(x = "Wave", y = "Log income") ``` ![Longitudinal data analysis plot of observed log-income trajectories across six waves, with the full-sample average shown in red.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/intro-lgm-observed-trajectories.webp) So we see we have an average change in time that we want to estimate but also quite a lot of variation in the way people change. LGM is able to estimate both at the same time! --- ## What is Latent Growth Modelling? So now that we have an idea about the data and the kind of research questions we might have we can move to the LGM. The formula for the LGM is actually very similar to the one for [the multilevel model of change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/): *y**j* = *α*0 + *α*1*λ**j* + *ζ*00 + *ζ*11*λ**j* + *ϵ**j* Where: - ***y**j*** is the variable of interest (logincome for us) that change in time, *j*. - ***α*0** represents the average value at the start of the data collection (the starting point of the red line above). - ***α*1*λ**j*** is the average rate of change in time (the slope of the red line in the graph above). Here *λ**j* just represents a measure of time. - ***ζ*00** is the **between variation** **at the start** of the data. Summarises how different are the individual starting points compared to the average starting point. - ***ζ*11*λ**j*** is the **between variation** **in the rate of change**. Summarizing how different are the individual slopes of change compared to the average change (red line above). - ***ϵ**j*** is the **within variation** or how much individuals vary around their predicted trend. We can get a better idea of the different sources of variation in the graph below: ``` example_ids <- usw |> slice_head(n = 2) |> pull(pidp) usl |> filter(pidp %in% example_ids) |> ggplot(aes(wave, logincome, colour = factor(pidp))) + geom_point() + geom_smooth(method = "lm", se = FALSE) + theme_bw() + labs(x = "Wave", y = "Log income", colour = "Respondent") ``` ![Longitudinal data analysis example showing observed log income and fitted lines for two respondents, illustrating within and between variation.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/intro-lgm-two-respondents.webp) The **within variation** is represented by the distance between the line and the points. This is done separately for each individual (by colour in the graph). The **between variation** refers to how different are the lines. This could be either the starting point or the slope. Structural Equation Modeling has its own way of representing these statistical relationships. Here is how we would represent the model described above: ![](https://www.alexcernat.com/wp-content/uploads/2021/04/lgm-1024x674.png) In this framework, latent variables are represented by circles (the two *η* variables) while observed variables are represented by squares (the four *y* variables). We also get the residuals (small circles representing *ϵ*). For the latent variables, we have averages (α) and variances (ζ). These are estimated and have the interpretation described before. The arrows between the latent and observed variables (which are just regression slopes or loadings) are fixed in advance. For the intercept latent variable (represented by η0) the loadings are fixed to 1 (that is why there is nothing multiplied with α0 and ζ00 in the formula above). The loadings for the slope latent variable (represented by η1) are fixed according to the change in time (λj in the formula above). In this case it simply goes from 0 to 3. We also correlate the starting point and the change in time, represented by the double arrow ζ01. This is not often interpreted but it basically gives you an idea that people are converging (or become more similar in time) or diverging (becoming more different). Now with the technical part out of the way, we can do some modelling and more graphs! --- ## How to estimate Latent Growth Models in R? Now we will apply the model above. Here I split the process in three parts: writing the syntax for the model and saving it as an object, running the model using the growth() command and look at the summary. We use logincome measured at six points in time (“logincome\_1” to “logincome\_6”). We estimate two latent variables, “i” representing the intercept and “s” representing the slope, using the `=~` command. To run the model we also fix the loadings in advance (as seen in the figure before) to “1” for the intercept and as time (0 to 5) for the slope. ``` # first LGM model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 + 1*logincome_5 + 1*logincome_6 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 + 4*logincome_5 + 5*logincome_6' fit1 <- growth(model, data = usw) summary(fit1, standardized = TRUE) ## lavaan 0.6-19 ended normally after 40 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 11 ## ## Number of observations 21178 ## ## Model Test User Model: ## ## Test statistic 1122.274 ## Degrees of freedom 16 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.121 0.791 ## logincome_2 1.000 1.121 0.908 ## logincome_3 1.000 1.121 0.955 ## logincome_4 1.000 1.121 0.970 ## logincome_5 1.000 1.121 0.981 ## logincome_6 1.000 1.121 1.003 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.166 0.135 ## logincome_3 2.000 0.333 0.284 ## logincome_4 3.000 0.499 0.432 ## logincome_5 4.000 0.666 0.583 ## logincome_6 5.000 0.832 0.745 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.116 0.003 -44.994 0.000 -0.622 -0.622 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.885 0.009 801.397 0.000 6.144 6.144 ## s 0.056 0.002 33.268 0.000 0.334 0.334 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.751 0.010 74.715 0.000 0.751 0.374 ## .logincome_2 0.473 0.006 74.687 0.000 0.473 0.310 ## .logincome_3 0.473 0.006 83.529 0.000 0.473 0.344 ## .logincome_4 0.527 0.006 87.255 0.000 0.527 0.394 ## .logincome_5 0.533 0.006 83.182 0.000 0.533 0.409 ## .logincome_6 0.460 0.007 64.709 0.000 0.460 0.368 ## i 1.256 0.015 81.824 0.000 1.000 1.000 ## s 0.028 0.001 44.340 0.000 1.000 1.000 ``` There are six types of coefficients that are interesting here: - **intercept i**: the value 6.885 represents the average expected logincome at the start of the study for all the respondents. - **intercept s**: the value 0.056 represents the average rate of change for all the respondents. So with each wave log income goes up by 0.056. - **variance i**: the value 1.256 represents the **between variation** **at the start of the study**. So how different are people compared to the average. - **variance s**: the value 0.028 represents the **between variation** **in the rate of change**. It shows how different are change slopes for different people. - **variance logincome**: the values ranging from 0.460 to 0.751 represent the **within variation** at each point in time. - **correlation between i and s**: the value -0.622 highlights that people’s income converges in time. --- ## How to visualize change? A good way to understand what you are modelling is to visualize the predicted scores from your model. We will use the predict() command to save a new object with the individual-level predicted scores for the intercept and slope. ``` # predict the two latent variables pred_lgm <- predict(fit1) ``` This has the predicted score for the intercept and slope for each individual: ``` head(pred_lgm) ## i s ## [1,] 7.015034 0.03169830 ## [2,] 5.920918 -0.11830624 ## [3,] 6.541709 0.04652843 ## [4,] 2.268350 0.48729258 ## [5,] 6.440448 0.01116318 ## [6,] 6.188213 0.07281722 ``` These are based on our model. So, for example, we could estimate the mean of these variables and it should give us the same results as above: ``` # average of the intercepts mean(pred_lgm[, "i"]) ## [1] 6.885196 # average of the slopes mean(pred_lgm[, "s"]) ## [1] 0.05565429 ``` To plot the results we want to transform this data (intercept (*η*0) and slope (*η*1)) into expected scores at each wave (*y**j*). We can do this transformation based on the path model we have seen in above: *y**j* = *η*0 + *η*1*λ**j* So, for the first wave the expected value is just the intercept (*η*0) because *λ**j* is equal to 0. For the second wave, the expected value would be the intercept (*η*0), slope (*η*1). For wave three it would be intercept + 2 \* slope, and so on. In `R` we could calculate all these waves by hand or we could do it automatically using a loop or functional programming. Based on the formula above we can create a counterpart in `R`: ``` pred_lgm[, 1] + x * pred_lgm[, 2] ``` where `x` represents our coding of time (or *λ**j*). We can apply this function multiple times using the `map()` command. The syntax below applies this formula for the numbers 0, 1, 2, 3, 4, 5 (our coding of time). ``` map(0:5, # what to loop over, in this case numbers 0 to 5 function(x) pred_lgm[, 1] + x * pred_lgm[, 2]) # formula to use ``` All of this hopefully should give you an intuition how the latent variables translate in expected values in our original data. Below I build on this formula and make a long dataset that has the predicted scores for the individuals at different waves. We can then use this to do nice plots using `ggplot2`. *A good way to understand syntax is to run it in stages. So you could first just run the `map()` command, then `map()` and `reduce()` together and so on, to understand what each step does.* ``` # create long data for each individual pred_lgm_long <- map( 0:5, function(x) pred_lgm[, "i"] + x * pred_lgm[, "s"] ) |> reduce(cbind) |> as.data.frame() |> setNames(str_c("Wave ", 1:6)) |> mutate(id = row_number()) |> pivot_longer(-id, names_to = "wave", values_to = "pred") set.seed(20260803) predicted_plot_ids <- sample(unique(pred_lgm_long$id), 2000) predicted_means <- pred_lgm_long |> group_by(wave) |> summarise(pred = mean(pred), .groups = "drop") pred_lgm_long |> filter(id %in% predicted_plot_ids) |> ggplot(aes(wave, pred, group = id)) + geom_line(alpha = 0.01) + geom_line( data = predicted_means, aes(wave, pred, group = 1), inherit.aes = FALSE, linewidth = 1.5, colour = "red" ) + theme_bw() + labs(y = "Log income", x = "Wave") ``` ![Longitudinal data analysis predictions from a latent growth model across six waves, with the average trajectory shown in red.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/intro-lgm-predicted-trajectories.webp) This is the predicted change over time based on our model. The red line starts at about 6.885 and increases by about 0.056 per wave. The individual lines have different starting points and rates of change, and this diversity is captured by the two latent variance estimates. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! --- ## Conclusions Hopefully, that gives you an idea about what is LGM, how to estimate it in `R` and how to visualize change using it. If you liked this you can check [the follow-up post that shows how to estimate non-linear change using LGM](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/) or see[ how this model compares to the multilevel model for chan](https://longitudinalanalysis.com/comparing-the-multilevel-model-with-the-latent-growth-model/)ge. You can also learn how to include time-constant and time-varying predictors in LGM models [here ](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/)and [here](https://longitudinalanalysis.com/how-to-include-time-varying-predictors-in-latent-growth-models-lgm-in-r/) and how to run parallel LGM [here](https://longitudinalanalysis.com/how-to-estimate-and-interpret-parallel-latent-growth-models-lgm-in-r-a-step-by-step-guide/). Also, [this post](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) looking at visualizing transition in time for categorical variables might be of interest. If you have questions feel free to post them in the comments below. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** latent growth modelling, longitudinal data analysis, r, structural equation modelling --- ### [Estimating non-linear change in time using the multilevel model for change](https://longitudinalanalysis.com/estimating-non-linear-change-in-time-using-the-multilevel-model-for-change/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how to model non-linear change in time using the multilevel model for change in R. Hands on tutorial with real data. **Content:** [In a previous post](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/), we introduced the multilevel model for change, a powerful model that can estimate change in time while separating within and between variation. While we discussed the basic model in detail, it can be expanded in several ways. Here, we will cover how to estimate non-linear change in time using the multilevel framework. In the basic multilevel model for change, we have only one coefficient to describe the effect of time. This implies a stable or linear rate of change. In many applications, this is not an appropriate assumption, as rates of change can be different at different points in time. There are two main ways of modelling these non-linear trends: including polynomials and treating time as discrete. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Nonlinear change in time using polynomials Let’s start with the first approach, including polynomials of time in the model. This is quickly done by creating new variables that take the values of time and square/cube/etc them. We will use as reference “wave0” which is a recoded version of time that starts from 0 (this is used to make the intercept easier to interpret, as discussed [here](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/)). ``` library(tidyverse) library(lme4) load("./data/usl_all_syn.RData") complete_ids <- usl_all |> filter(wave <= 6) |> group_by(pidp) |> summarise( complete = n() == 6 && all(!is.na(logincome)), .groups = "drop" ) |> filter(complete) |> pull(pidp) usl <- usl_all |> filter(pidp %in% complete_ids, wave <= 6) usl <- mutate( usl, wave0 = wave - 1, wave_sq = wave0^2, wave_cu = wave0^3 ) select(usl, wave0, wave_sq, wave_cu) ``` ``` ## # A tibble: 127,068 × 3 ## wave0 wave_sq wave_cu ## ## 1 0 0 0 ## 2 1 1 1 ## 3 2 4 8 ## 4 3 9 27 ## 5 4 16 64 ## 6 5 25 125 ## 7 0 0 0 ## 8 1 1 1 ## 9 2 4 8 ## 10 3 9 27 ## # ℹ 127,058 more rows ``` By including these new variables in a model, we allow for the effect of time to shift. When time has low values the main effect will have a large impact on the outcome, as time increases the square and the cube will become more and more important (due to their increased size). This allows for the rate of change to be different at different points in time. With the addition of each polynomial, we allow the change rate to “bend” once. If the effect of the polynomial is positive, the bend will be upwards, if it’s negative, it will bend downwards. The larger the size, the stronger the shift. Let’s look at an example. Below are the predicted scores for a hypothetical outcome where the main effect is 0. We see how the size of the outcome changes in time non-linearly due to the impact of the square estimate: ![Multilevel model square effects](https://www.alexcernat.com/wp-content/uploads/2023/02/bp_mlmchange_nonlinear_1-1-1024x731.png) We can also look at some hypothetical examples that include a cube effect. Again, the main effect is 0, so it would indicate no trend. However, the combination of square and cube effects allows for different trends in time. ![multilevel model for change square and cube effects](https://www.alexcernat.com/wp-content/uploads/2023/02/bp_mlmchange_nonlinear_2-1024x731.png) If we look at the situation when the square effect is 1, and the cube has an effect of -0.2, we see an initial upward trend and then a decrease, reaching 0 by wave 5. If both the square and the cube are positive, we will see an accelerated trend that increases as time passes. We also see that we can reach similar estimates in wave 5 with different change patterns. For example, both having a square effect of -1 and a cube effect of 0.1 and having a square effect of 0 and a cube effect of -.1 reach a similar point in wave 5, but if we continue that trend, the trajectories would become quite different. Let’s look at the linear model so we can use it as a reference (for an in-depth interpretation of the coefficient, check [this post](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/)). ``` model_control <- lmerControl( optimizer = "bobyqa", optCtrl = list(maxfun = 200000) ) m2 <- lmer( data = usl, logincome ~ 1 + wave0 + (1 + wave0 | pidp), control = model_control ) summary(m2) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave0 + (1 + wave0 | pidp) ## Data: usl ## Control: model_control ## ## REML criterion at convergence: 343010 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -7.3188 -0.1576 0.0694 0.2929 5.3691 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 1.29501 1.1380 ## wave0 0.02997 0.1731 -0.64 ## Residual 0.52694 0.7259 ## Number of obs: 127068, groups: pidp, 21178 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.873652 0.008613 798.1 ## wave0 0.058614 0.001684 34.8 ## ## Correlation of Fixed Effects: ## (Intr) ## wave0 -0.656 ``` These results imply that log income increases linearly by **0.059** for each wave. We can add polynomials if we believe the rate of change is not constant. For example, we can include the square of time using this code: ``` m2_sq <- lmer( data = usl, logincome ~ 1 + wave0 + wave_sq + (1 + wave0 | pidp), control = model_control ) summary(m2_sq) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave0 + wave_sq + (1 + wave0 | pidp) ## Data: usl ## Control: model_control ## ## REML criterion at convergence: 342930.4 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -7.3515 -0.1582 0.0704 0.2932 5.3437 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 1.2953 1.1381 ## wave0 0.0300 0.1732 -0.64 ## Residual 0.5264 0.7255 ## Number of obs: 127068, groups: pidp, 21178 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.8475608 0.0090321 758.135 ## wave0 0.0977514 0.0044137 22.147 ## wave_sq -0.0078274 0.0008159 -9.593 ## ## Correlation of Fixed Effects: ## (Intr) wave0 ## wave0 -0.517 ## wave_sq 0.301 -0.924 ``` The quadratic model has an initial positive slope of **0.098** and a negative square effect of **-0.008**. We therefore expect log income to increase initially, with the rate of increase becoming smaller in later waves. We can also compare the predicted scores from the model that assumes linear change and the model that also includes square effects against the observed average. It appears that the square effect fits the observed data better, albeit not perfectly. ![Multilevel analysis figure comparing observed, linear and quadratic average log-income trajectories across six waves.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/quadratic-comparison-figure-1.webp) The previous model keeps the quadratic bend fixed across respondents. We can allow each respondent to have their own non-linear trajectory by adding the squared time term to the random part. The synthetic file provides all eleven waves for this example. We scale time only inside the random-effects terms to improve numerical estimation; the fixed effects remain on the original per-wave scale. ``` usl_all <- usl_all |> mutate( wave0 = wave - 1, wave_sq = wave0^2, wave_re = wave0 / 10, wave_sq_re = wave_re^2 ) m2_sq_re <- lmer( data = usl_all, logincome ~ 1 + wave0 + wave_sq + (1 + wave_re + wave_sq_re | pidp), control = model_control ) summary(m2_sq_re) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave0 + wave_sq + (1 + wave_re + wave_sq_re | ## pidp) ## Data: usl_all ## Control: model_control ## ## REML criterion at convergence: 890416 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -6.9844 -0.1506 0.0782 0.3077 4.9922 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 1.6981 1.303 ## wave_re 9.8504 3.139 -0.64 ## wave_sq_re 7.4127 2.723 0.44 -0.91 ## Residual 0.6337 0.796 ## Number of obs: 307858, groups: pidp, 50994 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.6540184 0.0064927 1024.84 ## wave0 0.1181185 0.0022988 51.38 ## wave_sq -0.0079764 0.0002315 -34.45 ``` Across eleven waves, the model estimates an initial positive trend of **0.118** and a negative quadratic term of **-0.008**. We can see below the average change in time as well as three individuals with their trajectories. ![example of non-linear change with multilevel model](https://www.alexcernat.com/wp-content/uploads/2023/02/bp_mlmchange_nonlinear_4-1024x731.png) ## Nonlinear change in time using a categorical variable An alternative way to model non-linear change is to treat time as a discrete/categorical variable. In that case, we can estimate the expected value of the outcome at each point in time or in a particular range of time. The most general approach treats each time point as a discrete variable. While this doesn’t make any assumptions about the shape of the change in time, it is a complex model that may have estimation problems. To try this out with our model, we can define the time variable as a factor. By default, `lmer()` (like the `lm()` command) transforms factors into dummy variables and treats the first category as the reference. We can use this to model non-linear change. ``` usl <- mutate(usl, wave_fct = as.factor(wave)) ``` We can now include this in our model. ``` m2_dummy <- lmer( data = usl, logincome ~ 1 + wave_fct + (1 + wave0 | pidp), control = model_control ) summary(m2_dummy) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave_fct + (1 + wave0 | pidp) ## Data: usl ## Control: model_control ## ## REML criterion at convergence: 342809.3 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -7.3267 -0.1602 0.0700 0.2944 5.3225 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 1.29574 1.1383 ## wave0 0.03005 0.1733 -0.64 ## Residual 0.52553 0.7249 ## Number of obs: 127068, groups: pidp, 21178 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.825304 0.009274 736.00 ## wave_fct2 0.143486 0.007145 20.08 ## wave_fct3 0.205471 0.007437 27.63 ## wave_fct4 0.222739 0.007899 28.20 ## wave_fct5 0.261674 0.008505 30.77 ## wave_fct6 0.335933 0.009225 36.42 ## ## Correlation of Fixed Effects: ## (Intr) wv_fc2 wv_fc3 wv_fc4 wv_fc5 ## wave_fct2 -0.465 ## wave_fct3 -0.533 0.520 ## wave_fct4 -0.583 0.515 0.567 ## wave_fct5 -0.617 0.502 0.572 0.623 ## wave_fct6 -0.639 0.484 0.569 0.633 0.678 ``` *Notice that we still treat the random part of the model* linearly. Again, estimating a random effect at each wave can lead to issues with model estimation, *so we use a simplified random effect.* The intercept gives the expected log income at wave 1, which is **6.825**. At wave 2, the expected value is 6.825 + 0.143 = **6.969**. The corresponding differences for waves 3 to 6 are 0.205, 0.223, 0.262 and 0.336. We can compare these values with the observed averages and the predictions from the quadratic model. ![Multilevel analysis figure comparing observed, quadratic and categorical-time average log-income trajectories across six waves.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/categorical-comparison-figure-1.webp) The new prediction is almost identical to the observed data (lines overlap). That being said, there is a trade-off between the model’s simplicity and how well it explains the data. We can formally compare the different models we estimated to decide how to treat the change in time for log income. ``` anova(m2, m2_sq, m2_dummy) ``` ``` ## Data: usl ## Models: ## m2: logincome ~ 1 + wave0 + (1 + wave0 | pidp) ## m2_sq: logincome ~ 1 + wave0 + wave_sq + (1 + wave0 | pidp) ## m2_dummy: logincome ~ 1 + wave_fct + (1 + wave0 | pidp) ## npar AIC BIC logLik -2*log(L) Chisq Df Pr(>Chisq) ## m2 6 343003 343061 -171495 342991 ## m2_sq 7 342913 342981 -171449 342899 91.98 1 < 2.2e-16 *** ## m2_dummy 10 342780 342877 -171380 342760 139.10 3 < 2.2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` The AIC, BIC and chi-square comparisons all favour the categorical-time model. The quadratic model still improves clearly on the linear model and gives a relatively close, more parsimonious description of the average trajectory. The preferred specification therefore depends on whether we prioritise flexibility or a compact functional form. Below we plot the predicted scores. ![Multilevel analysis figure showing individual log-income profiles with observed and quadratic average trajectories across six waves.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/individual-trajectories-figure-1.webp) We see considerable variation between respondents. The black observed average and red quadratic prediction are nevertheless close across the six waves. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions Hopefully, this will give you an idea of how the multilevel model for change can be expanded to include non-linear effects. Other, more complex trends can be estimated using models such as splines (an introduction [here](https://psycnet.apa.org/doiLanding?doi=10.1037%2Fmet0000193)). The model can also include time-constant predictors, as discussed here. You can also compare this approach with modelling [non-linear effects using Latent Growth Models](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, multilevel modeling, r, visualization --- ### [Explaining change using multilevel and time constant predictors](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how to explain change in time using time constant predictors using the multilevel model. Examples with real data and R code **Content:** [In a previous post, we discussed the multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/), which investigates average change in time while accounting for individual-level variation. In this blog post, we will discuss how to extend this model to include predictors. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Time-varying versus time-constant variables When working with longitudinal data, we can consider variables to be [**time-varying** or **time-constant**](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). For example, a survey measure of general satisfaction is a time-varying variable as it is collected in each wave. So, for each individual, this could change (although it does not have to change). The year of birth is a time-constant variable. Collecting this information once from each individual is enough, as we do not expect it to change. There are also some situations where we can treat a variable as time constant or time-varying. For example, we could recode birth year as age, a time-varying variable. Similarly, we could take each individual’s average of general satisfaction and make that variable time constant. In such situations, treating a variable as time-constant or variable should be based on theoretical considerations, our data and the modelling strategy used. You can read more about this in [the post about data structures](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). ## Explaining Change Here, we will expand the multilevel model to include time-constant predictors. In [a previous post](https://longitudinalanalysis.com/estimating-non-linear-change-in-time-using-the-multilevel-model-for-change/), we explored how best to describe the change in time of the outcome by including non-linear effects. This is an essential first step in analyzing longitudinal data. Nevertheless, we often want to understand the causes of that change or at least how different groups may have different rates of change. We will turn to this aspect, discussing the inclusion of time-constant predictors and the same [Understanding Society data](https://www.understandingsociety.ac.uk/). ### Including Time Constant Predictors We will start by adding a time-constant predictor to our model. For example, let’s explore how the change in mental health is different for men and women (where we treat these as time constant). If we add the “gndr” variable to our model, the new formula for our regression will be: *Y**ij* = *γ*00 + *γ*01*GNDR**i* + *γ*10*TIME**ij* + *ξ*0*i* + *ξ*1*i**TIME**ij* + *ϵ**ij* The interpretation of the coefficients is mostly the [same as before](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/). The interpretation of the intercept (γ00) changes and now refers to the expected value of the outcome **when “gndr” and “time” are 0**. In our case, this would refer to males at the beginning of the study. The effect of “gndr” (γ10) refers to how different females are from males in their mental health. The interpretation of the random effects is the same as before. *We will use the linear change in time model to keep things simple, but this can be easily expanded to include non-linear change.* Let’s run this model: ``` library(tidyverse) library(lme4) load("./data/us_clean_syn.RData") usl <- usl |> mutate( wave0 = wave - 1, gndr = gndr.fct, degree = degree.fct ) m3 <- lmer( data = usl, sf12mcs ~ 1 + wave0 + gndr + (1 + wave0 | pidp) ) summary(m3) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: sf12mcs ~ 1 + wave0 + gndr + (1 + wave0 | pidp) ## Data: usl ## ## REML criterion at convergence: 935141.8 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.3978 -0.4295 0.1569 0.5623 3.1354 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 39.181 6.259 ## wave0 3.017 1.737 -0.37 ## Residual 59.118 7.689 ## Number of obs: 127989, groups: pidp, 48630 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 51.05364 0.05852 872.47 ## wave0 -0.41879 0.02172 -19.28 ## gndrFemale -1.37299 0.07123 -19.27 ## ## Correlation of Fixed Effects: ## (Intr) wave0 ## wave0 -0.413 ## gndrFemale -0.681 0.000 ## optimizer (nloptwrap) convergence code: 0 (OK) ## Model failed to converge with max|grad| = 0.00462369 (tol = 0.002, component 1) ``` We will concentrate on the fixed part of the model. The intercept, **51.054**, is the expected mental-health score for men at the first wave. Mental health decreases by **0.419** points per wave. After accounting for time, women score **1.373** points lower than men at the first wave. This model can include multiple time constant predictors of different nature, categorical or continuous. The interpretation will be the same as in a regular regression. ### Allowing for different rates of change One crucial assumption we made so far is that the rate of change is the same for men and females. That means that the difference in mental state remains constant in time. This is often an important question that we want to explore. From a substantive point of view, having different rates of change, which would lead to convergence or divergence, is very important. To explicitly examine this in our model, we can add an interaction between gender and time. This would allow for different rates of change for men and women. We would write this model as follows: *Y**ij* = *γ*00 + *γ*01*GNDR**i* + *γ*10*TIME**ij* + *γ*11*GNDR**i* \* *TIME**ij* + *ξ*0*i* + *ξ*1*i**TIME**ij* + *ϵ**ij* We can easily include interactions in `lmer()` by adding the two variables separated by `:`. So our new model is: ``` m4 <- lmer( data = usl, sf12mcs ~ 1 + wave0 + gndr + gndr:wave0 + (1 + wave0 | pidp) ) summary(m4) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: sf12mcs ~ 1 + wave0 + gndr + gndr:wave0 + (1 + wave0 | pidp) ## Data: usl ## ## REML criterion at convergence: 935117.3 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.3894 -0.4295 0.1573 0.5625 3.1512 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 39.170 6.259 ## wave0 3.006 1.734 -0.37 ## Residual 59.116 7.689 ## Number of obs: 127989, groups: pidp, 48630 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 51.20087 0.06459 792.713 ## wave0 -0.55125 0.03281 -16.802 ## gndrFemale -1.63514 0.08628 -18.952 ## wave0:gndrFemale 0.23567 0.04376 5.385 ## ## Correlation of Fixed Effects: ## (Intr) wave0 gndrFm ## wave0 -0.565 ## gndrFemale -0.749 0.423 ## wv0:gndrFml 0.423 -0.750 -0.564 ## optimizer (nloptwrap) convergence code: 0 (OK) ## Model failed to converge with max|grad| = 0.00399381 (tol = 0.002, component 1) ``` With the interaction included, the intercept remains the expected first-wave score for men (**51.201**). Men decline by **0.551** points per wave, and women start **1.635** points lower. The positive interaction of **0.236** means that women decline more slowly. Their estimated slope is about **-0.316** (-0.551 + 0.236), so the gender gap narrows across the four waves. We can also see this visually by using the predicted scores: ``` gender_predictions <- expand_grid( wave0 = 0:3, gndr = factor(levels(usl$gndr), levels = levels(usl$gndr)) ) |> mutate(predicted = predict(m4, newdata = pick(everything()), re.form = NA)) ggplot(gender_predictions, aes(wave0 + 1, predicted, colour = gndr)) + geom_line(linewidth = 1.2) + geom_point(size = 2) + theme_bw() + labs(x = "Wave", y = "Predicted mental health", colour = "Gender") ``` ![Multilevel modelling predictions showing mental-health trajectories across four waves for men and women.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/gender-figure-1.webp) Men begin with higher predicted mental-health scores. The lines are not parallel: the positive interaction means that women decline more slowly, so the difference becomes smaller across the four waves. We can expand the model to see an important example of interaction effects. Below, we include the effect of degree, another variable we treat as a time constant, as well as the interaction with time. Given the small effect we observed earlier, we keep the main effect of sex but exclude the interaction with time. ``` m5 <- lmer( data = usl, sf12mcs ~ 1 + wave0 + gndr + degree + degree:wave0 + (1 + wave0 | pidp) ) summary(m5) ``` ``` ## Linear mixed model fit by REML ['lmerMod'] ## Formula: sf12mcs ~ 1 + wave0 + gndr + degree + degree:wave0 + (1 + wave0 | ## pidp) ## Data: usl ## ## REML criterion at convergence: 934129.9 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.3917 -0.4289 0.1551 0.5610 3.1577 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 38.931 6.239 ## wave0 3.002 1.733 -0.37 ## Residual 59.121 7.689 ## Number of obs: 127868, groups: pidp, 48573 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 51.72881 0.08395 616.162 ## wave0 -0.55139 0.03650 -15.107 ## gndrFemale -1.37171 0.07120 -19.267 ## degreeNo degree -1.01131 0.09068 -11.153 ## wave0:degreeNo degree 0.19794 0.04543 4.357 ## ## Correlation of Fixed Effects: ## (Intr) wave0 gndrFm dgrNdg ## wave0 -0.503 ## gndrFemale -0.473 -0.004 ## degreeNdegr -0.718 0.468 -0.003 ## wv0:dgrNdgr 0.404 -0.804 0.005 -0.568 ## optimizer (nloptwrap) convergence code: 0 (OK) ## Model failed to converge with max|grad| = 0.0105688 (tol = 0.002, component 1) ``` In the final model, the intercept of **51.729** is the expected first-wave score for men with a degree. Respondents without a degree score **1.011** points lower at the first wave. The degree group declines by **0.551** points per wave, while the positive interaction of **0.198** indicates a slower decline among respondents without a degree. The education gap therefore narrows across the four waves. ``` education_predictions <- expand_grid( wave0 = 0:3, gndr = factor("Male", levels = levels(usl$gndr)), degree = factor(levels(usl$degree), levels = levels(usl$degree)) ) |> mutate(predicted = predict(m5, newdata = pick(everything()), re.form = NA)) ggplot(education_predictions, aes(wave0 + 1, predicted, colour = degree)) + geom_line(linewidth = 1.2) + geom_point(size = 2) + theme_bw() + labs(x = "Wave", y = "Predicted mental health", colour = "Education") ``` ![Multilevel modelling predictions showing four-wave mental-health trajectories by degree status for men.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/education-figure-1.webp) ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions The multilevel model for change can be easily expanded to include time-constant predictors. For the most part, the interpretation is similar to that from multiple regression. Care is needed with the interpretation when including interactions with time to allow for different rates of change for subgroups. You have seen above some example code for using predicted scores and visualizations to better understand your model’s results. You can also check how to include time varying predictors in [this blogpost](https://longitudinalanalysis.com/understanding-time-varying-predictors-in-multilevel-models-for-longitudinal-data/) as well as investigating nonlinear change in time [here](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, r --- ### [Estimating non-linear change with Latent Growth Models in R](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how to estimate and visualize nonlinear Latent Growth Models (LGM) using R. Hands on example using real world longitudinal data and code **Content:** In a [previous post](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/), we covered how to use Latent Growth Modeling in R to examine change in time. In that post, we assumed a simple linear model, which is often unrealistic. Here, I am going to show how we can free this assumption and find the best way to treat change in time. We can use exploratory analysis and previous research to understand how to model change in time. Moreover, we can also compare models that treat change in time in different ways to find the best fit for our data. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! If we look again at the log income in the Understanding Society data, we get this graph (see [previous post](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) for an explanation of the data and [how it is structured](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/ "how it is structured")): ``` set.seed(20260803) plot_ids <- sample(unique(usl$pidp), 2000) observed_means <- usl |> group_by(wave) |> summarise(logincome = mean(logincome), .groups = "drop") usl |> filter(pidp %in% plot_ids) |> ggplot(aes(wave, logincome, group = pidp)) + geom_line(alpha = 0.01) + geom_line( data = observed_means, aes(wave, logincome), inherit.aes = FALSE, linewidth = 1.5, colour = "red" ) + theme_bw() + labs(x = "Wave", y = "Log income") ``` ![Longitudinal data plot showing observed log-income trajectories across six waves, with the full-sample average in red.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/observed-trajectories-1.webp)Exploratory visualization of log income change in time The graph would indicate we have an average change that is overall linear with a slight downward bend. To see the individual level change, I also sampled 20 individuals and plotted each one’s change in income. ``` set.seed(20260803) people <- sample(unique(usl$pidp), 20) usl |> filter(pidp %in% people) |> ggplot(aes(wave, logincome, group = 1)) + geom_line() + facet_wrap(~pidp) + theme_bw() + labs(x = "Wave", y = "Log income") ``` ![Longitudinal data plot showing log-income trajectories for 20 respondents across six waves.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/twenty-respondents-1.webp)Examples of individual trends in time for income It appears that at the individual level, we have a more mixed bag, although linear change would not be a bad approximation for quite a few people. Keeping this in mind, we can also decide on the best way to model change in time by comparing several different models and seeing which fits the data best. As a starting point, we can run the linear model, which will be our reference (see [previous post](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) for an explanation of the model and syntax): ``` model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 + 1*logincome_5 + 1*logincome_6 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 + 4*logincome_5 + 5*logincome_6' fit1 <- growth(model, data = usw) summary(fit1, standardized = TRUE) ## lavaan 0.6-19 ended normally after 40 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 11 ## ## Number of observations 21178 ## ## Model Test User Model: ## ## Test statistic 1122.274 ## Degrees of freedom 16 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.121 0.791 ## logincome_2 1.000 1.121 0.908 ## logincome_3 1.000 1.121 0.955 ## logincome_4 1.000 1.121 0.970 ## logincome_5 1.000 1.121 0.981 ## logincome_6 1.000 1.121 1.003 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.166 0.135 ## logincome_3 2.000 0.333 0.284 ## logincome_4 3.000 0.499 0.432 ## logincome_5 4.000 0.666 0.583 ## logincome_6 5.000 0.832 0.745 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.116 0.003 -44.994 0.000 -0.622 -0.622 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.885 0.009 801.397 0.000 6.144 6.144 ## s 0.056 0.002 33.268 0.000 0.334 0.334 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.751 0.010 74.715 0.000 0.751 0.374 ## .logincome_2 0.473 0.006 74.687 0.000 0.473 0.310 ## .logincome_3 0.473 0.006 83.529 0.000 0.473 0.344 ## .logincome_4 0.527 0.006 87.255 0.000 0.527 0.394 ## .logincome_5 0.533 0.006 83.182 0.000 0.533 0.409 ## .logincome_6 0.460 0.007 64.709 0.000 0.460 0.368 ## i 1.256 0.015 81.824 0.000 1.000 1.000 ## s 0.028 0.001 44.340 0.000 1.000 1.000 ``` The model estimates an average initial log income of **6.885** (about £978) and an average linear increase of **0.056** per wave. The interpretation is the same as before, although the numerical values change with the synthetic data. We can also visualize the change in time based on our model (again, check the [previous post](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) for explanations). ``` pred_lgm <- predict(fit1) pred_lgm_long <- map( 0:5, function(x) pred_lgm[, 1] + x * pred_lgm[, 2] ) |> reduce(cbind) |> as.data.frame() |> setNames(str_c("Wave ", 1:6)) |> mutate(id = row_number()) |> pivot_longer(-id, names_to = "wave", values_to = "pred") set.seed(20260803) prediction_ids <- sample(unique(pred_lgm_long$id), 2000) linear_means <- pred_lgm_long |> group_by(wave) |> summarise(pred = mean(pred), .groups = "drop") pred_lgm_long |> filter(id %in% prediction_ids) |> ggplot(aes(wave, pred, group = id)) + geom_line(alpha = 0.01) + geom_line( data = linear_means, aes(wave, pred, group = 1), inherit.aes = FALSE, linewidth = 1.5, colour = "red" ) + theme_bw() + labs(y = "Log income", x = "Wave") ``` ![Longitudinal data predictions from a linear latent growth model across six waves, with the average in red.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/linear-predictions-1.webp)Predicted change in log income based on linear Latent Growth Model There are two general ways to expand this model to include non-linear change. One is by including polynomials while the other is by looking at relative change in time. We will cover both below. ## Estimating non-linear LGM using polynomials Including polynomials to model nonlinear effects has a similar motivation to regression modelling. A polynomial (or interaction) allows the effect to change depending on the values of a predictor. In the case of LGM, this would mean that we allow the slope to be higher or lower as time passes. This, in effect, would bend the trend upwards or downwards. If we want to allow for multiple bends, then we need to include multiple polynomials. Below, we will include just the square effects modelled as a latent variable “q” (but the model can be easily expanded to include cubed effects and so on). ``` model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 + 1*logincome_5 + 1*logincome_6 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 + 4*logincome_5 + 5*logincome_6 q =~ 0*logincome_1 + 1*logincome_2 + 4*logincome_3 + 9*logincome_4 + 16*logincome_5 + 25*logincome_6' fit2 <- growth(model, data = usw) summary(fit2, standardized = TRUE) ## lavaan 0.6-19 ended normally after 75 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 15 ## ## Number of observations 21178 ## ## Model Test User Model: ## ## Test statistic 461.571 ## Degrees of freedom 12 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.173 0.839 ## logincome_2 1.000 1.173 0.941 ## logincome_3 1.000 1.173 0.996 ## logincome_4 1.000 1.173 1.011 ## logincome_5 1.000 1.173 1.018 ## logincome_6 1.000 1.173 1.064 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.416 0.333 ## logincome_3 2.000 0.831 0.706 ## logincome_4 3.000 1.247 1.074 ## logincome_5 4.000 1.663 1.442 ## logincome_6 5.000 2.078 1.885 ## q =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.069 0.055 ## logincome_3 4.000 0.275 0.234 ## logincome_4 9.000 0.619 0.533 ## logincome_5 16.000 1.101 0.955 ## logincome_6 25.000 1.720 1.560 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.235 0.010 -24.013 0.000 -0.482 -0.482 ## q 0.020 0.002 12.521 0.000 0.246 0.246 ## s ~~ ## q -0.026 0.001 -21.952 0.000 -0.905 -0.905 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.851 0.009 736.245 0.000 5.839 5.839 ## s 0.095 0.005 18.794 0.000 0.229 0.229 ## q -0.007 0.001 -8.026 0.000 -0.106 -0.106 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.577 0.013 44.837 0.000 0.577 0.295 ## .logincome_2 0.484 0.006 76.119 0.000 0.484 0.311 ## .logincome_3 0.438 0.006 76.450 0.000 0.438 0.316 ## .logincome_4 0.481 0.006 79.039 0.000 0.481 0.357 ## .logincome_5 0.533 0.006 82.386 0.000 0.533 0.401 ## .logincome_6 0.387 0.010 38.078 0.000 0.387 0.319 ## i 1.377 0.020 70.478 0.000 1.000 1.000 ## s 0.173 0.007 24.934 0.000 1.000 1.000 ## q 0.005 0.000 21.692 0.000 1.000 1.000 ``` The quadratic model estimates an initial increase of **0.095** per wave and a negative quadratic term of **-0.007**. The average increase therefore becomes smaller in later waves. The variance of “q” is **0.005**, showing that respondents differ in the non-linear part of their income trajectories. All three latent variances are positive. Next, we plot the new estimates of change from the new model. We will use a procedure similar to the one above. The main change is to the formula. Now, we need to add a new term, which is time squared (x^2) multiplied by the coefficient for the square effect (pred\_lgm2\[, 3\]). We also added the line from the linear model for comparison. ``` pred_lgm2 <- predict(fit2) pred_lgm2_long <- map( 0:5, function(x) { pred_lgm2[, 1] + x * pred_lgm2[, 2] + x^2 * pred_lgm2[, 3] } ) |> reduce(cbind) |> as.data.frame() |> setNames(str_c("Wave ", 1:6)) |> mutate(id = row_number()) |> pivot_longer(-id, names_to = "wave", values_to = "pred") quadratic_means_plot <- pred_lgm2_long |> group_by(wave) |> summarise(pred = mean(pred), .groups = "drop") ggplot(quadratic_means_plot, aes(wave, pred, group = 1)) + geom_line(linewidth = 1.5, colour = "blue") + geom_line( data = linear_means, aes(wave, pred, group = 1), linewidth = 1.5, colour = "red", alpha = 0.5 ) + theme_bw() + labs(y = "Log income", x = "Wave") ``` ![Longitudinal data predictions comparing a quadratic latent growth model in blue with a linear model in red.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/quadratic-predictions-1.webp) Comparing estimates of change using latent growth models with linear and non-linear trajectories. The blue quadratic trajectory starts below the red linear trajectory, rises slightly above it in the middle waves and finishes below it. The difference is modest, but the fit statistics show that allowing this curvature improves the model. ## Non-linear change in time using relative change The alternative way to model non-linear change is to estimate relative change. This is similar in spirit to including dummy variables in a regression model. The only thing we need to do is to tweak the loadings for the slope latent variable. We will fix only the first and last loading to 0 and 1. The rest of the loadings will not be fixed and will be estimated. Now, the interpretation of the slope will be the total amount of change from the first wave to the last one. The newly estimated loadings will tell us the proportion of change from the start until that point out of the total change observed. ``` model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 + 1*logincome_5 + 1*logincome_6 s =~ 0*logincome_1 + logincome_2 + logincome_3 + logincome_4 + logincome_5 + 1*logincome_6' fit3 <- growth(model, data = usw) summary(fit3, standardized = TRUE) ## lavaan 0.6-19 ended normally after 75 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 15 ## ## Number of observations 21178 ## ## Model Test User Model: ## ## Test statistic 1004.879 ## Degrees of freedom 12 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.122 0.792 ## logincome_2 1.000 1.122 0.903 ## logincome_3 1.000 1.122 0.962 ## logincome_4 1.000 1.122 0.976 ## logincome_5 1.000 1.122 0.985 ## logincome_6 1.000 1.122 0.992 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 0.156 0.016 9.732 0.000 0.124 0.100 ## logincome_3 0.468 0.011 41.324 0.000 0.373 0.320 ## logincome_4 0.681 0.011 60.655 0.000 0.543 0.473 ## logincome_5 0.876 0.012 70.421 0.000 0.698 0.613 ## logincome_6 1.000 0.797 0.705 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.554 0.017 -32.126 0.000 -0.620 -0.620 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.888 0.009 766.311 0.000 6.142 6.142 ## s 0.258 0.008 30.516 0.000 0.323 0.323 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.746 0.013 58.510 0.000 0.746 0.372 ## .logincome_2 0.442 0.008 54.014 0.000 0.442 0.286 ## .logincome_3 0.480 0.006 83.935 0.000 0.480 0.353 ## .logincome_4 0.521 0.006 85.982 0.000 0.521 0.395 ## .logincome_5 0.520 0.007 75.861 0.000 0.520 0.402 ## .logincome_6 0.492 0.008 63.034 0.000 0.492 0.385 ## i 1.258 0.019 65.513 0.000 1.000 1.000 ## s 0.635 0.020 31.726 0.000 1.000 1.000 ``` From wave 1 to wave 6, the relative-change model estimates a total average increase of **0.258**. The loadings are 0, 0.156, 0.468, 0.681, 0.876 and 1. About 16% of the total change occurs by wave 2 and 47% by wave 3. The largest increment, about 31%, occurs between waves 2 and 3, while about 12% occurs between waves 5 and 6. This pattern is not perfectly linear. We need to extract the loadings to make a nice graph using the formula. We can use the `parameterestimates()` command to do that: ``` parameterEstimates(fit3) ## lhs op rhs est se z pvalue ci.lower ci.upper ## 1 i =~ logincome_1 1.000 0.000 NA NA 1.000 1.000 ## 2 i =~ logincome_2 1.000 0.000 NA NA 1.000 1.000 ## 3 i =~ logincome_3 1.000 0.000 NA NA 1.000 1.000 ## 4 i =~ logincome_4 1.000 0.000 NA NA 1.000 1.000 ## 5 i =~ logincome_5 1.000 0.000 NA NA 1.000 1.000 ## 6 i =~ logincome_6 1.000 0.000 NA NA 1.000 1.000 ## 7 s =~ logincome_1 0.000 0.000 NA NA 0.000 0.000 ## 8 s =~ logincome_2 0.156 0.016 9.732 0 0.125 0.187 ## 9 s =~ logincome_3 0.468 0.011 41.324 0 0.446 0.490 ## 10 s =~ logincome_4 0.681 0.011 60.655 0 0.659 0.704 ## 11 s =~ logincome_5 0.876 0.012 70.421 0 0.851 0.900 ## 12 s =~ logincome_6 1.000 0.000 NA NA 1.000 1.000 ## 13 logincome_1 ~~ logincome_1 0.746 0.013 58.510 0 0.721 0.771 ## 14 logincome_2 ~~ logincome_2 0.442 0.008 54.014 0 0.426 0.458 ## 15 logincome_3 ~~ logincome_3 0.480 0.006 83.935 0 0.469 0.491 ## 16 logincome_4 ~~ logincome_4 0.521 0.006 85.982 0 0.509 0.533 ## 17 logincome_5 ~~ logincome_5 0.520 0.007 75.861 0 0.507 0.534 ## 18 logincome_6 ~~ logincome_6 0.492 0.008 63.034 0 0.477 0.508 ## 19 i ~~ i 1.258 0.019 65.513 0 1.220 1.296 ## 20 s ~~ s 0.635 0.020 31.726 0 0.596 0.674 ## 21 i ~~ s -0.554 0.017 -32.126 0 -0.588 -0.520 ## 22 logincome_1 ~1 0.000 0.000 NA NA 0.000 0.000 ## 23 logincome_2 ~1 0.000 0.000 NA NA 0.000 0.000 ## 24 logincome_3 ~1 0.000 0.000 NA NA 0.000 0.000 ## 25 logincome_4 ~1 0.000 0.000 NA NA 0.000 0.000 ## 26 logincome_5 ~1 0.000 0.000 NA NA 0.000 0.000 ## 27 logincome_6 ~1 0.000 0.000 NA NA 0.000 0.000 ## 28 i ~1 6.888 0.009 766.311 0 6.871 6.906 ## 29 s ~1 0.258 0.008 30.516 0 0.241 0.274 ``` With some manipulation, we can extract just what we want: ``` loadings <- parameterEstimates(fit3) |> filter(lhs == "s", op == "=~") |> pull(est) loadings ## [1] 0.0000000 0.1559671 0.4677954 0.6814987 0.8756568 1.0000000 ``` We can follow a similar approach to the one before to create the long data with predicted scores from the LGM. The only difference is that we now loop over the loadings instead of the numbers 0 to 5: ``` pred_lgm3 <- predict(fit3) pred_lgm3_long <- map( loadings, function(x) pred_lgm3[, 1] + x * pred_lgm3[, 2] ) |> reduce(cbind) |> as.data.frame() |> setNames(str_c("Wave ", 1:6)) |> mutate(id = row_number()) |> pivot_longer(-id, names_to = "wave", values_to = "pred") relative_means_plot <- pred_lgm3_long |> group_by(wave) |> summarise(pred = mean(pred), .groups = "drop") ggplot(relative_means_plot, aes(wave, pred, group = 1)) + geom_line(linewidth = 1.5, colour = "green") + geom_line( data = quadratic_means_plot, aes(wave, pred, group = 1), linewidth = 1.5, colour = "blue", alpha = 0.5 ) + geom_line( data = linear_means, aes(wave, pred, group = 1), linewidth = 1.5, colour = "red", alpha = 0.5 ) + theme_bw() + labs(y = "Log income", x = "Wave") ``` ![Longitudinal data predictions comparing relative-change, quadratic and linear latent growth models across six waves.](https://longitudinalanalysis.com/wp-content/uploads/2026/08/relative-predictions-1.webp)Comparing change estimates using latent growth models with linear, non-linear and relative trajectories. The relative-change trajectory shows the same broad pattern. Income increases most quickly in the earlier waves and the rate of increase becomes smaller towards wave 6. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Finding the best fit We can use chi-square, AIC and BIC to compare the models. The linear and quadratic models are nested, but the quadratic and relative-change models have the same degrees of freedom and are not nested. Their chi-square difference is therefore descriptive rather than a likelihood-ratio test: ``` model_comparison <- anova(fit1, fit2, fit3) model_comparison ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## fit2 12 341502 341621 461.57 ## fit3 12 342045 342164 1004.88 543.31 0.000000 0 ## fit1 16 342154 342242 1122.27 117.40 0.036587 4 < 2.2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` The quadratic model has the lowest chi-square, AIC and BIC. It improves on the linear model by **660.70** chi-square points with four additional parameters. The information criteria also favour it over the relative-change model, so we retain the quadratic specification. ## Conclusions Hopefully, that will give you an idea of how to estimate non-linear LGM, how to visualize this change, and how to interpret it. Visualizing these models is always helpful, as the interpretation can get quite tricky. If you liked this, you could look at other blog posts, such as [this introduction to multilevel modelling for longitudinal data](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) or [this one](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) visualizing transition in time for categorical variables. You can also learn how to include time-constant and time-varying predictors in LGM models [here ](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/)and [here](https://longitudinalanalysis.com/how-to-include-time-varying-predictors-in-latent-growth-models-lgm-in-r/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** latent growth modelling, longitudinal data analysis, r --- ### [Comparing the multilevel model with the Latent Growth Model](https://longitudinalanalysis.com/comparing-the-multilevel-model-with-the-latent-growth-model/) **Published:** February 6, 2024 **Author:** alexcernat **Excerpt:** Learn how the multilevel model for change and the latent growth models are different and when to use each one. Hands on example using real data and R **Content:** In previous blog posts, I have introduced two of the most popular models for estimating change in time: the multilevel model for change (MLM) and the Latent Growth Model (LGM). In my experience teaching this topic, researchers tend to select one of these models depending on the framework they are more familiar with: regression/multilevel vs. Structural Equation Modeling. As a result, they know less about the other method and when to use it. Both of these models answer similar research questions: how does change happen? and *how elements differ in their patterns of change?* There are a couple of reasons why you should try to understand both the multilevel model for change and the latent growth model. Firstly, while the two methods are similar, they have different strengths and weaknesses. As such, it might make sense to switch to the other approach in certain situations. Secondly, by default, these models make slightly different assumptions you must know. Thirdly, you should understand how both of these work to be able to engage with the academic literature. In this post, I’m going to compare the two methods, discuss their differences in assumptions, and explain how to test them. Finally, I will discuss some of each method’s strengths and weaknesses. ## Set-up First, let’s set up things for the comparison. I’m going to use the “lavaan” to run the LGM. This package was developed to run Structural Equation Models and is well-suited to run LGM. We will use “lme4” to run the MLM. Here, I load the two packages (they are already installed): ``` library(tidyverse) library(lavaan) library(lme4) load("./data/us_clean_syn.RData") usw <- usw |> select(pidp, logincome_1:logincome_4) |> drop_na() usl <- usl |> filter(pidp %in% usw$pidp) |> select(pidp, wave, logincome) |> mutate(wave0 = wave - 1) ``` One crucial difference between the two models is that they use data that is structured differently. The LGM uses the [wide data format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/), where each row represents an individual, and variables appear in multiple columns to represent the value at each wave. Here is how the wide data looks like: ``` usw ## # A tibble: 26,635 × 5 ## pidp logincome_1 logincome_2 logincome_3 logincome_4 ## ## 1 5 8.10 8.30 8.20 6.76 ## 2 6 6.81 6.58 6.57 6.73 ## 3 11 8.37 8.30 7.92 8.37 ## 4 13 7.03 5.67 6.52 6.07 ## 5 14 6.54 7.18 6.92 6.91 ## 6 16 5.55 7.35 6.29 6.67 ## 7 18 6.48 7.44 5.15 7.18 ## 8 21 5.24 5.05 6.58 7.10 ## 9 22 4.58 6.62 6.48 7.10 ## 10 23 2.30 6.60 6.49 6.52 ## # ℹ 26,625 more rows ``` The MLM uses the data in [long format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) where each row is a combination of individual and wave. This has fewer variables but is longer as values for different waves appear in the same column: ``` usl ## # A tibble: 106,540 × 4 ## pidp wave logincome wave0 ## ## 1 5 1 8.10 0 ## 2 5 2 8.30 1 ## 3 5 3 8.20 2 ## 4 5 4 6.76 3 ## 5 6 1 6.81 0 ## 6 6 2 6.58 1 ## 7 6 3 6.57 2 ## 8 6 4 6.73 3 ## 9 11 1 8.37 0 ## 10 11 2 8.30 1 ## # ℹ 106,530 more rows ``` ## The statistical models I have introduced the two models in previous posts ([the multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) and the [Latent Growth Model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/)) so do check out those if this is new to you. I want to present the statistical notation of the two models next to each other to see the similarities. The notation for the multilevel model for change is: *Yij = γ00 + γ10TIMEij + ξ0i + ξ1iTIME*ij* + ϵij* The notation for the Latent Growth Model is: *yj = α0 + α1λj + ζ00 + ζ11λj + ϵj* A few things to note. Typically, the individual subscript, i, is missing from SEM notation. Also, time is an explicit variable in the MLM, but it is coded as λ in LGM, and we need to code it by hand. Otherwise, they are very similar. Just a reminder of what all this Greek means: - *Yij/yj* is the variable of interest (logincome for us) that changes in time (*j*). - *γ00/α0* represents the average value at the start of the data collection. - *γ10/α1* is the average rate of change in time. - *ξ0i/ζ00* is the **between variation at the start of the data,** basically summarizing how different the individual starting points are compared to the average starting points. - *ξ*1*i*/*ζ**11* is the **between variation in the rate of change.** They summarize how different the individual slopes of change are from the average change. - *ϵ**ij*/*ϵ**j* is the **within variation** or how different are the observed scores of each individual compared to their expected value. ## Comparing the results Next, let’s compare two simple models where we explore the change in time of log income over four waves of the [Understanding Society survey](https://www.understandingsociety.ac.uk/). The first model we run is the LGM (which we cover in more depth in [this post](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/)) ``` model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4' lgm1 <- growth(model, data = usw) summary(lgm1, standardized = TRUE) ## lavaan 0.6-19 ended normally after 37 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 9 ## ## Number of observations 26635 ## ## Model Test User Model: ## ## Test statistic 1102.403 ## Degrees of freedom 5 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.216 0.864 ## logincome_2 1.000 1.216 0.907 ## logincome_3 1.000 1.216 0.981 ## logincome_4 1.000 1.216 1.045 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.305 0.227 ## logincome_3 2.000 0.610 0.492 ## logincome_4 3.000 0.915 0.786 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.255 0.005 -47.705 0.000 -0.687 -0.687 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.794 0.008 812.223 0.000 5.588 5.588 ## s 0.088 0.003 31.904 0.000 0.289 0.289 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.504 0.011 45.563 0.000 0.504 0.254 ## .logincome_2 0.734 0.008 88.749 0.000 0.734 0.408 ## .logincome_3 0.705 0.008 92.466 0.000 0.705 0.458 ## .logincome_4 0.567 0.010 57.394 0.000 0.567 0.419 ## i 1.479 0.017 85.177 0.000 1.000 1.000 ## s 0.093 0.002 39.527 0.000 1.000 1.000 ``` Next, we run the MLM using the long data (which we cover in more depth in [this post](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/)) ``` mlm1 <- lmer( data = usl, logincome ~ 1 + wave0 + (1 + wave0 | pidp) ) summary(mlm1) ## Linear mixed model fit by REML ['lmerMod'] ## Formula: logincome ~ 1 + wave0 + (1 + wave0 | pidp) ## Data: usl ## ## REML criterion at convergence: 318552.9 ## ## Scaled residuals: ## Min 1Q Median 3Q Max ## -5.8772 -0.1618 0.1034 0.3313 4.7800 ## ## Random effects: ## Groups Name Variance Std.Dev. Corr ## pidp (Intercept) 1.37848 1.1741 ## wave0 0.07159 0.2676 -0.68 ## Residual 0.66717 0.8168 ## Number of obs: 106540, groups: pidp, 26635 ## ## Fixed effects: ## Estimate Std. Error t value ## (Intercept) 6.799674 0.008324 816.88 ## wave0 0.086886 0.002774 31.32 ## ## Correlation of Fixed Effects: ## (Intr) ## wave0 -0.674 ``` To make it easier to compare, we can extract the main coefficients in a table: | Coefficient | Multilevel | Latent growth | |---|---|---| | Fixed effect: intercept | 6.800 | 6.794 | | Fixed effect: slope | 0.087 | 0.088 | | Between variance: intercept | 1.378 | 1.479 | | Between variance: slope | 0.072 | 0.093 | Table comparing coefficients from multilevel mode and latent growth model The estimates are close but not identical. The main difference comes from the residuals, or within variation. The multilevel model estimates one common residual variance of **0.667**, while the unrestricted LGM estimates a separate value for each wave. This is the main additional assumption made by the multilevel model in this comparison. This assumption can be important. These coefficients are substantively interesting as they tell us about the amount of within variation left unexplained. If residuals are not equal in time, this coefficient can be incorrect. Furthermore, other coefficients in the model can be biased as a result. ## Restricting the LGM While there is some debate about whether the assumption of equal residuals in time is reasonable, I believe the best way to deal with it is to investigate it empirically. This can be easily done in LGM. We can run the model again, but this time with the restriction that the residuals are equal in time. We can then compare this model with the prior one to decide on this assumption. ``` model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 logincome_1 ~~ a*logincome_1 logincome_2 ~~ a*logincome_2 logincome_3 ~~ a*logincome_3 logincome_4 ~~ a*logincome_4' lgm2 <- growth(model, data = usw) summary(lgm2, standardized = TRUE) ## lavaan 0.6-19 ended normally after 34 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 9 ## Number of equality constraints 3 ## ## Number of observations 26635 ## ## Model Test User Model: ## ## Test statistic 1420.270 ## Degrees of freedom 8 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.174 0.821 ## logincome_2 1.000 1.174 0.904 ## logincome_3 1.000 1.174 0.967 ## logincome_4 1.000 1.174 0.992 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.268 0.206 ## logincome_3 2.000 0.535 0.441 ## logincome_4 3.000 0.803 0.678 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.215 0.005 -45.592 0.000 -0.683 -0.683 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.800 0.008 816.899 0.000 5.792 5.792 ## s 0.087 0.003 31.317 0.000 0.325 0.325 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincom_1 (a) 0.667 0.004 163.202 0.000 0.667 0.326 ## .logincom_2 (a) 0.667 0.004 163.202 0.000 0.667 0.395 ## .logincom_3 (a) 0.667 0.004 163.202 0.000 0.667 0.453 ## .logincom_4 (a) 0.667 0.004 163.202 0.000 0.667 0.476 ## i 1.378 0.016 84.849 0.000 1.000 1.000 ## s 0.072 0.002 36.603 0.000 1.000 1.000 ``` Now, we see that the residual is the same at each time. If we make a table with all the coefficients, we now see that they are identical for LGM and MLM: | Coefficient | Multilevel | Latent growth | Latent growth restricted | |---|---|---|---| | Fixed effect: intercept | 6.800 | 6.794 | 6.800 | | Fixed effect: slope | 0.087 | 0.088 | 0.087 | | Between variance: intercept | 1.378 | 1.479 | 1.378 | | Between variance: slope | 0.072 | 0.093 | 0.072 | | Within variation | 0.667 | 0.504 | 0.667 | Comparing the multilevel model with the latent growth model with restrictions We can compare the model with restrictions and the original one to see which fits the data best. The `anova()` command is an easy way to do this: ``` lgm_comparison <- anova(lgm1, lgm2) restriction_chisq <- lgm_comparison[["Chisq diff"]][2] lgm_comparison ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## lgm1 5 318235 318308 1102.4 ## lgm2 8 318547 318596 1420.3 317.87 0.062774 3 < 2.2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` The equal-residual restriction increases chi-square by **317.87** with three degrees of freedom (*p* < .001). We therefore reject this restriction. The multilevel model still gives almost the same average trajectory, but the unrestricted latent growth model represents the wave-specific residual variances better. ## When to use each model In addition to this assumption regarding the within variation, which can be freed and tested, there are a couple of other things to consider when choosing between the multilevel model for change and latent growth models. The MLM is handy when analyzing data with continuous time or when data is collected at different points in time for each individual. Because it uses long data, it can easily deal with these situations, which can be problematic for the LGM. Additionally, if you have many time points, it might be easier to write up the model. Conversely, the LGM is useful if you want to use some of the other tools available in the SEM framework. For example, you can easily do multi-group analysis, comparing trends for different groups. You can also combine the LGM with the mixture or latent class to run the Mixture Latent Growth Model. This makes it possible to find clusters of people based on their time changes. Additionally, you can include the LGM in path models, making it possible to examine the relationship between the rate of change and other variables of interest. You can also correct for measurement errors by using second-order latent growth models and investigate invariance in time. Finally, SEM can effectively deal with missing data by using Full Information Maximum Likelihood. ## Conclusions Hopefully, that gave you an idea of the strengths and weaknesses of the multilevel model for change and the latent growth models. Both can be valuable tools for understanding individual-level change in time. There might be situations where one is a better fit than the other, though. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** latent growth modelling, longitudinal data analysis, multilevel modeling, r, structural equation modelling --- ### [Causal Mediation in R: A Practical Guide](https://longitudinalanalysis.com/causal-mediation-in-r/) **Published:** June 30, 2026 **Author:** Alex Cernat **Excerpt:** Learn how to do causal mediation in R using real-world panel data. Learn how to interpret ACME, ADE and how to use binary mediators **Content:** Understanding the mechanisms or pathways that connect variables is fundamental for better theories and interventions. Mediation models are a way to investigate such pathways. For example, education may be associated with mental health partly because it changes income. Partnership status may matter because it changes later mental health. While [path analysis](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/) can help estimate such effects, causal mediation promises to get us closer to causal relationships and treatment effects. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## From [path analysis](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/) to causal mediation Causal mediation promises to get us closer to causal relationships and treatment effects. The diagram below shows a basic mediation model. In this notation, the `a` path links the predictor, `X`, to the mediator, `M`. Path `b` links the mediator to the outcome, `Y`. The direct path, often labelled `c'`, represents the part of the predictor-outcome association that remains after the mediator is included. ![Conceptual path diagram showing predictor X, mediator M, outcome Y, indirect paths a and b, and direct path c prime.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/conceptual-path-analysis-1-5.webp) That path-analysis approach is a useful way to represent a theoretical mechanism. It tells us whether the estimated path through the mediator is large or small, and whether the direct path remains after the mediator is included. However, the interpretation is often framed as a decomposition of regression paths rather than as a direct answer to a causal question. Causal mediation investigates the same types of relationships but changes the focus of interpretation. It estimates an expected treatment effect and calculates how much of the treatment-outcome relationship would operate through the mediator if the treatment changed. This approach has three main benefits over traditional path analysis. First, it makes the assumptions of the mediation models and the context in which it can be interpreted as causal more explicit; see the [original paper](https://imai.fas.harvard.edu/research/files/BaronKenny.pdf) for a discussion of this. Second, it can facilitate interpretation when the moderator or outcomes are categorical. Third, it introduces [tools for sensitivity analysis](https://imai.fas.harvard.edu/research/files/mediation.pdf) of the results. ## Preparing the data for causal mediation The examples use the wide version of the synthetic Understanding Society data. Each respondent is a row, and repeated measures are labelled with suffixes such as `_1`, `_2`, and `_3`. The real [Understanding Society data and documentation](https://www.understandingsociety.ac.uk/documentation/mainstage/) are available on the study website, via the [UK Data Service catalogue entry](https://beta.ukdataservice.ac.uk/datacatalogue/studies/study?id=6614). ``` load("../data/us_clean_syn.RData") dat0 <- usw |> mutate( age_num = as.numeric(haven::zap_labels(age)), age10 = (age_num - mean(age_num, na.rm = TRUE)) / 10, female = ifelse(gndr.fct == "Female", 1, 0), degree = ifelse(degree.fct == "Degree", 1, 0), single1 = as.numeric(haven::zap_labels(single_1)), single2 = as.numeric(haven::zap_labels(single_2)) ) ``` Age is centred and divided by ten, so a one-unit change means ten years. The models use gender, age, degree status, income, and baseline variables as controls where needed. ## Causal mediation in a simple continuous example We start with the example closest to a standard mediation using path models. Degree is the treatment, log income is the mediator, and mental health is the outcome. The mediator and outcome are continuous, so the model is easy to compare with a standard path-analysis approach. The mediator and outcome models must be fitted on the same analysis sample. Therefore, it is safer to create the complete-case dataset first, rather than allowing each model to silently drop a different set of rows. To estimate the model, we need to run the two regressions separately and then include the results in the `mediate()` command. ``` dat_ex1 <- dat0 |> dplyr::select(degree, logincome_1, sf12mcs_1, age10, female) |> drop_na() model_m1 <- lm( logincome_1 ~ degree + age10 + female, data = dat_ex1 ) model_y1 <- lm( sf12mcs_1 ~ degree + logincome_1 + age10 + female, data = dat_ex1 ) med_1 <- mediate( model_m1, model_y1, treat = "degree", mediator = "logincome_1", sims = 200 ) ``` Before using a cleaned table, it is worth looking at the output that R gives. The four rows to read first are `ACME`, `ADE`, `Total Effect`, and `Prop. Mediated`. ``` summary(med_1) ``` ``` ## ## Causal Mediation Analysis ## ## Quasi-Bayesian Confidence Intervals ## ## Estimate 95% CI Lower 95% CI Upper p-value ## ACME 0.019885 -0.029935 0.066655 0.38 ## ADE 1.197903 1.001742 1.388387 <2e-16 *** ## Total Effect 1.217788 1.015919 1.395795 <2e-16 *** ## Prop. Mediated 0.016447 -0.023193 0.053365 0.38 ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Sample Size Used: 47350 ## ## ## Simulations: 200 ``` ACME means **average causal mediation effect**. It is the estimated part of the treatment-outcome relationship that operates through the mediator, averaged over the people in the analysis sample. In this example, it is the pathway from degree status to mental health through income. ADE means **average direct effect**. It is the part of the fitted treatment effect that does not operate through the mediator. The `Total Effect` row combines the mediated and direct parts, while `Prop. Mediated` reports the estimated share carried by the mediator. In this case, the indirect effect through income is small and not statistically different from 0. The ACME is 0.020, while the ADE is 1.198. Therefore, most of the estimated association between degree status and mental health is not through income. ![Path diagram showing causal mediation from degree to mental health through income.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/example-1-diagram-1-5.webp) For a linear model like this one, a path analysis would usually give a similar point estimate for the indirect effect. The approach becomes more useful when we move away from a fully linear model. The next example does that by making the mediator binary. ## Causal mediation with a binary mediator Suppose the mediator is not continuous. In this example, degree status is the treatment, being single at wave 1 is the mediator, and mental health at wave 1 is the outcome. The mediator model is a probit regression. This example is close to the kind of problem that motivates this method in practice. A simple product `a*b` is harder to interpret when one path comes from a probit model and the other path comes from a linear model. In this setting, the `mediate()` function estimates the ACME and ADE offer a better way to interpret the results. ``` dat_ex3 <- dat0 |> dplyr::select(degree, single1, sf12mcs_1, logincome_1, age10, female) |> drop_na() model_m3 <- glm( single1 ~ degree + logincome_1 + age10 + female, data = dat_ex3, family = binomial("probit") ) model_y3 <- lm( sf12mcs_1 ~ degree + single1 + logincome_1 + age10 + female, data = dat_ex3 ) med_3 <- mediate( model_m3, model_y3, treat = "degree", mediator = "single1", sims = 200 ) ``` | Quantity | Estimate | CI low | CI high | p-value | N | |---|---|---|---|---|---| | ACME: indirect effect | 0.094 | 0.073 | 0.112 | < .001 | 47350 | | ADE: direct effect | 1.112 | 0.928 | 1.305 | < .001 | 47350 | | Total effect | 1.206 | 1.029 | 1.398 | < .001 | 47350 | | Proportion mediated | 0.078 | 0.060 | 0.098 | < .001 | 47350 | Causal mediation results with a binary mediator Here, the ACME is 0.094, while the ADE is 1.112. Its mediated proportion is 0.078, so the indirect pathway through single status is modest. This result should be read in relation to the direct effect. The ADE is much larger than the ACME, so single status carries only a small part of the degree-mental health association. ![Path diagram showing causal mediation from degree to mental health through single status as a binary mediator.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/example-3-diagram-1-5.webp) ## Longitudinal causal mediation with temporal ordering Cross-sectional mediation is often problematic because treatment, mediator, and outcome are measured at the same time. A longitudinal design can improve the argument by ordering the variables. It does not remove all confounding, but it makes reverse causation less plausible. Here, single status at wave 1 is the treatment. Mental health at wave 2 is the mediator, and life satisfaction at wave 3 is the outcome. The model also controls for baseline mental health and baseline life satisfaction. ``` dat_ex5 <- dat0 |> dplyr::select( single1, sf12mcs_1, sf12mcs_2, sati_1, sati_3, logincome_1, age10, female, degree ) |> drop_na() model_m5 <- lm( sf12mcs_2 ~ single1 + sf12mcs_1 + sati_1 + logincome_1 + age10 + female + degree, data = dat_ex5 ) model_y5 <- lm( sati_3 ~ single1 + sf12mcs_2 + sf12mcs_1 + sati_1 + logincome_1 + age10 + female + degree, data = dat_ex5 ) med_5 <- mediate( model_m5, model_y5, treat = "single1", mediator = "sf12mcs_2", sims = 200 ) ``` | Quantity | Estimate | CI low | CI high | p-value | N | |---|---|---|---|---|---| | ACME: indirect effect | -0.005 | -0.011 | 0.002 | 0.140 | 18241 | | ADE: direct effect | -0.011 | -0.054 | 0.031 | 0.690 | 18241 | | Total effect | -0.015 | -0.059 | 0.027 | 0.510 | 18241 | | Proportion mediated | 0.134 | -1.599 | 3.314 | 0.590 | 18241 | Longitudinal causal mediation results The ACME is -0.005, which is small and the confidence interval includes zero. For this example, there is little evidence that wave-2 mental health carries much of the association between wave-1 single status and wave-3 life satisfaction. That statement is conditional on controlling baseline mental health and baseline life satisfaction. ![Path diagram showing longitudinal causal mediation from single status at wave 1 to life satisfaction at wave 3 through mental health at wave 2.](https://longitudinalanalysis.com/wp-content/uploads/2026/06/example-5-diagram-1-5.webp) ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Learning the mediation workflow One useful extension to this method is sensitivity analysis, which investigates under what conditions the relationships found could be biased. This is a useful way to check model results and is rarely done in path and Structural Equation Models. If you want a more structured introduction to doing mediation analysis, check out our online course: [Mediation and Moderation Analysis Using R](https://leanpub.com/c/mediation-moderation-r). It covers path analysis, moderation, mediated moderation, causal mediation, and interpretation in R. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis, statistics **Tags:** causality, longitudinal data analysis, r --- ### [Attrition bias: what is it and how to measure it](https://longitudinalanalysis.com/attrition-bias-what-is-it-and-how-to-measure-it/) **Published:** February 27, 2026 **Author:** Alex Cernat **Excerpt:** Attrition bias explained: how participant dropout occurs, how to measure it, and why it matters for valid longitudinal research. **Content:** Longitudinal studies are powerful because they allow us to observe change over time. But this ability also has a big drawback: if people drop out of the study, we lose information about their trajectories. This is called attrition, and it can bias our results. In this post, you will find out what attrition is, how to calculate attrition rates, and how to assess attrition bias. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## What is attrition? Attrition occurs when respondents who participated earlier in a study are no longer observed in later waves. This can happen for various reasons: they may move away, lose interest, or be unable to participate due to health issues. This process is in addition to the challenges of missing data that occur in cross-sectional studies. For example, in a cross-sectional study, we have two main types of missing data. **Item** or **question missing** appears when a respondent participates in the study but does not answer a specific question. This can be due to various reasons, such as the question being sensitive, confusing, or simply skipped. On the other hand **unit missing** or non-response occurs when a respondent does not participate in the survey at all, which can be due to reasons such as inability to contact or refusal to participate. We can visualise this as below, where “1” represents an answer and “0” represents missing data. ![non-response patterns in a cross-sectional study](https://longitudinalanalysis.com/wp-content/uploads/2026/02/image-1.webp) Our ideal is the first unit, or individual, that answers all the questions. Individuals 2 and 3 participate in the study but decide not to answer some questions. This is **item missing**. Individual 4 does not participate in the study at all, which is **unit missing**. If we collect data from the same cases multiple times, as in a longitudinal study, we can have different patterns of missing: ![attrition patterns in a longitudinal study. can be used to understand attrition bias ](https://longitudinalanalysis.com/wp-content/uploads/2026/02/image.webp) Again, our ideal is the first unit, or individual, that participates in all waves. Individuals 2 and 3 participate in the first study, but then they drop out. We see that they exhibit different patterns of participation, with individual 3 later rejoining the study. Individual 4 does not participate in the study at all. In general, we define attrition as cases that participated at least once in the study but then dropped out at some point. Based on this definition, individuals 1 and 2 have attrited. ## Why is attrition important? When people drop out of a study, we lose information about their trajectories. This can lead to biased results if the people who drop out are systematically different from those who remain in the study. For example, if people with lower income are more likely to drop out of a study on income and well-being, then our results may overestimate the average income and well-being of the population. The extent to which this is a problem is estimated using attrition bias. The second issue is that our samples shrink as cases drop out. This can lead to less precise estimates and less statistical power to detect effects. To understand this process, we can use attrition rates. ## How to calculate attrition rate? One way to understand attrition is to examine patterns of participation in the study. As an illustration, we will use data based on the first four waves of [Understanding Society](https://www.understandingsociety.ac.uk/). We will first load the `tidyverse` package for data clearing and exploration, and `haven` to read the data from Stata files. [Understanding Society](https://www.understandingsociety.ac.uk/) data stores each wave of data in a separate file. So, we need to load each wave and then merge them. Each file has a respondent identifier variable called “pidp”, which we will use for the merger. ``` library(tidyverse) library(haven) us1 <- read_dta("./data/a_indresp_syn.dta") us2 <- read_dta("./data/b_indresp_syn.dta") us3 <- read_dta("./data/c_indresp_syn.dta") us4 <- read_dta("./data/d_indresp_syn.dta") ``` Before we bring the data together, we will create an indicator telling us whether a respondent participated in each wave. By default, when you merge data, R does not indicate if a case is present in one dataset or both (unlike Stata, for example). A way around this is to create an indicator in each wave that indicates whether the individual is present. After we merge the data, if an individual has missing information on these indicators, it means that they did not participate in that wave. ``` us1 <- mutate(us1, present_1 = T) us2 <- mutate(us2, present_2 = T) us3 <- mutate(us3, present_3 = T) us4 <- mutate(us4, present_4 = T) ``` We then merge waves using the respondent identifier. Here we will use the `left_join()` command. This will keep all the cases from the first dataset we input, and append information from the second dataset. In this study, people can join later, for example, if a new member joins a family. To keep things simple, we will assume we care only about the original sample, so we will use the first wave as our main dataset and merge the others with it. If we wanted to include new members, we could use a different merge type, such as `full_join()`, which would keep all cases from both datasets. We will merge the data in a stepwise way, first merging the first two waves, then merging the result with the third wave and finally merging that result with the fourth wave. ``` us12 <- left_join(us1, us2, by = "pidp") us123 <- left_join(us12, us3, by = "pidp") us1234 <- left_join(us123, us4, by = "pidp") ``` Now “us1234” has individuals who participated in the first wave and information from four waves. We can now explore the patterns of participation in the study. For example, we can look at how many people participated in the first two waves by using the code below, where `count()` creates a table, and then we also calculate the proportions using `mutate()`: ``` count(us1234, present_1, present_2) |> mutate(prop = n/sum(n)) ``` ``` ## # A tibble: 2 × 4 ## present_1 present_2 n prop ## ## 1 TRUE TRUE 38291 0.751 ## 2 TRUE NA 12716 0.249 ``` Here we see that 38,291 people participated in both waves, while 12,716 dropped out after the first wave. We can now also calculate the **attrition rate**, which is simply the proportion of people who dropped out after the first wave. In this case, it is 12,716/(38,291+12,716) = 0.25, which means that 25% of the original sample dropped out after the first wave. We can follow this procedure for multiple waves. Let’s imagine we want to analyse four data waves. We can use all four indicators: ``` count(us1234, present_1, present_2, present_3, present_4) |> mutate(prop = n/sum(n)) ``` ``` ## # A tibble: 8 × 6 ## present_1 present_2 present_3 present_4 n prop ## ## 1 TRUE TRUE TRUE TRUE 26748 0.524 ## 2 TRUE TRUE TRUE NA 4146 0.0813 ## 3 TRUE TRUE NA TRUE 1618 0.0317 ## 4 TRUE TRUE NA NA 5779 0.113 ## 5 TRUE NA TRUE TRUE 1581 0.0310 ## 6 TRUE NA TRUE NA 622 0.0122 ## 7 TRUE NA NA TRUE 332 0.00651 ## 8 TRUE NA NA NA 10181 0.200 ``` We see now more complex participation patterns. After four waves, we have lost almost half of the sample. The most common patterns of participation are: participating in all four waves (52%), participating in the first wave and dropping out (20%), participating in the first two waves (11%) or dropping out after the third wave (8%). When we analyse more than two waves of data, there are different ways to define attrition rates. Probably the most common one is to compare people who participated in all the waves you plan to analyse with those who dropped out at some point. This is also in line with the definition of [balanced data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) in longitudinal data. If we plan to analyse all four waves here, we can create an indicator to determine whether someone is present in all four waves. We can do this using the `case_when()` command, which allows us to create a new variable based on multiple conditions. In this case, we check if the person is present in all four waves. If they are, we give them a value of “False” (as they did not attrit), and if they are not, we give them a value of “NA” (as we do not know if they attrited or not). ``` us1234 <- mutate( us1234, attrition = case_when( present_1 == T & present_2 == T & present_3 == T & present_4 == T ~ F, TRUE ~ T )) ``` Based on this definition, the attrition rate in the first four waves is 48%: ``` count(us1234, attrition) |> mutate(prop = n/sum(n)) ``` ``` ## # A tibble: 2 × 3 ## attrition n prop ## ## 1 FALSE 26748 0.524 ## 2 TRUE 24259 0.476 ``` ## Attrition versus item missing Attrition depends on whether an individual participates in a particular wave. But in addition to this, we still have the challenge of item missing, which is when a respondent participates in a wave but does not answer a specific question. It is useful to separate these two types of missing data because they may have different mechanisms and solutions. As an illustration, let’s look at the patterns of missing data in income. We will take the original income variables and create a new version that indicates whether an individual has missing data in each wave. The code below uses the `mutate_at()` command, which allows us to apply a function to multiple variables at once. Here, we use `vars(matches("grs"))` to select all variables that have “grs” in their name, which are the income variables in our dataset. We then apply` is. na ()` to check whether the value is missing. This creates new variables with the suffix “\_miss” that indicate whether the corresponding original variable is missing. ``` us1234 <- mutate_at(us1234, vars(matches("grs")), list("miss" = ~ is.na(.))) ``` Now we can explore the patterns of missing income. For example, we can look at how many people have missing data on income in each wave: ``` us1234 |> count(a_fimngrs_dv_miss, b_fimngrs_dv_miss, c_fimngrs_dv_miss, d_fimngrs_dv_miss) |> mutate(prop = n/sum(n)) |> arrange(desc(n)) ``` ``` ## # A tibble: 16 × 6 ## a_fimngrs_dv_miss b_fimngrs_dv_miss c_fimngrs_dv_miss d_fimngrs_dv_miss n ## ## 1 FALSE FALSE FALSE FALSE 26635 ## 2 FALSE TRUE TRUE TRUE 10175 ## 3 FALSE FALSE TRUE TRUE 5771 ## 4 FALSE FALSE FALSE TRUE 4178 ## 5 FALSE FALSE TRUE FALSE 1629 ## 6 FALSE TRUE FALSE FALSE 1611 ## 7 FALSE TRUE FALSE TRUE 632 ## 8 FALSE TRUE TRUE FALSE 334 ## 9 TRUE FALSE FALSE FALSE 13 ## 10 TRUE TRUE TRUE TRUE 12 ## 11 TRUE TRUE FALSE FALSE 8 ## 12 TRUE FALSE TRUE TRUE 5 ## 13 TRUE FALSE FALSE TRUE 1 ## 14 TRUE FALSE TRUE FALSE 1 ## 15 TRUE TRUE FALSE TRUE 1 ## 16 TRUE TRUE TRUE FALSE 1 ## # ℹ 1 more variable: prop ``` We see that 26,635 have income in all four waves, while the rest show different patterns of missing. While this is useful, it is actually combining attrition and item missing. If we want to better understand how important attrition or item missingness is in this process, we have two options. The first approach is to look only at individuals who are present in all the waves and then calculate the number of items missing: ``` us1234 |> filter(attrition == F) |> count(a_fimngrs_dv_miss, b_fimngrs_dv_miss, c_fimngrs_dv_miss, d_fimngrs_dv_miss) |> mutate(prop = n/sum(n)) |> arrange(desc(n)) ``` ``` ## # A tibble: 7 × 6 ## a_fimngrs_dv_miss b_fimngrs_dv_miss c_fimngrs_dv_miss d_fimngrs_dv_miss n ## ## 1 FALSE FALSE FALSE FALSE 26635 ## 2 FALSE FALSE FALSE TRUE 46 ## 3 FALSE TRUE FALSE FALSE 35 ## 4 FALSE FALSE TRUE FALSE 13 ## 5 TRUE FALSE FALSE FALSE 13 ## 6 TRUE TRUE FALSE FALSE 5 ## 7 FALSE FALSE TRUE TRUE 1 ## # ℹ 1 more variable: prop ``` Now it becomes clear that most of the missing income data are due to attrition. Among those who participated in all four waves, 99% have income data in all four. The second approach is to look at the unit and the item missing at the same time. For example, for the first two waves, these are the patterns of missing data: ``` us1234 |> count(present_1, a_fimngrs_dv_miss, present_2, b_fimngrs_dv_miss) |> mutate(prop = n/sum(n)) |> arrange(desc(n)) ``` ``` ## # A tibble: 6 × 6 ## present_1 a_fimngrs_dv_miss present_2 b_fimngrs_dv_miss n prop ## ## 1 TRUE FALSE TRUE FALSE 38213 0.749 ## 2 TRUE FALSE NA TRUE 12702 0.249 ## 3 TRUE FALSE TRUE TRUE 50 0.000980 ## 4 TRUE TRUE TRUE FALSE 20 0.000392 ## 5 TRUE TRUE NA TRUE 14 0.000274 ## 6 TRUE TRUE TRUE TRUE 8 0.000157 ``` Again, it is clear that the main mechanism is people dropping out of the study. ## What is attrition bias? So far, we looked at the rate at which people drop out of the study. But the more important question is whether this attrition is random or systematic. If the people who drop out differ from those who remain in the study, we have **attrition bias**. This can lead to incorrect results and misleading conclusions. We can calculate attrition bias by comparing the characteristics of people who dropped out with those who remained in the study. Typically, we use information from the first waves to do this, since we have information on all respondents at the beginning of the study. Alternatively, other data sources, such as administrative records or information aboutwhere people live, can be used to compare the characteristics of people who dropped out with those who remained in the study. Here, we will explore attrition bias by comparing the characteristics of people who dropped out with those who remained in the study, using wave 1 data. For example, we can look at the attrition rate separately by sex: ``` us1234 |> group_by(sex) |> summarise(attrition_rate = mean(attrition)) ``` ``` ## # A tibble: 2 × 2 ## sex attrition_rate ## ## 1 Male 0.489 ## 2 Female 0.465 ``` In this case, men have a higher attrition rate (48.8%) than women (46.4%). This indicates that we have attrition bias on gender. The differences are not huge, but they are there. As another example, we can look at the average age of people who dropped out compared to those who remained in the study: ``` us1234 |> group_by(attrition) |> summarise(age = mean(age, na.rm = T)) ``` ``` ## # A tibble: 2 × 2 ## attrition age ## ## 1 FALSE 47.5 ## 2 TRUE 43.4 ``` Here we see that people who dropped out are, on average, younger (43.3 years) than those who remained in the study (47.6 years). This indicates that we have attrition bias on age as well. ## Estimating attrition bias using regressions A more systematic way to assess the extent of attrition bias is to run a regression model in which the outcome is the attrition indicator and the predictors are the characteristics of people at the beginning of the study. The advantage of this approach is that it accounts for the potential bias of other variables. In this way, we can better understand the main mechanisms related to attrition. As an example, we can run a logistic regression model where the outcome is attrition in the first four waves and the predictors are sex, age, single, urban and degree: ``` m1 <- glm(attrition ~ sex + age + single + urban + degree, data = us1234, family = "binomial") exp(cbind(OR = coef(m1), confint(m1))) ``` ``` ## OR 2.5 % 97.5 % ## (Intercept) 1.2653067 1.1928472 1.3421986 ## sexFemale 0.8891965 0.8582038 0.9213022 ## age 0.9883368 0.9873441 0.9893292 ## singleYes 1.3336241 1.2852941 1.3837777 ## urbanrural area 0.8771820 0.8393900 0.9166397 ## degreeNo degree 1.3012695 1.2528007 1.3516534 ``` We can interpret the results as odds ratios, where values above 1 indicate a higher chance of attrition and values below 1 indicate a lower chance of attrition. For example, females have approximately 11% lower odds of attrition than men, while each additional year of age is associated with a 1% lower odds of attrition. The results indicate that all variables affect attrition bias. To make the results a little more intuitive, we can also look at the predicted probabilities. This will create an indicator of the attrition risk for each individual in the dataset, based on their characteristics. We can then use this indicator to explore how individual characteristics relate to the likelihood of attrition. ``` us1234$attrit_pred <- predict(m1, type = "response", newdata = us1234) ``` For example, we can look at the predicted probabilities of attrition by age using a graph: ``` ggplot(us1234, aes(age, attrit_pred)) + geom_point(alpha = 0.1) ``` ![attrition bias by age in a longitudinal study](https://longitudinalanalysis.com/wp-content/uploads/2026/02/image-2-1024x731.webp) The relationship between age and attrition is now clearer. As another example, we could examine the predicted attrition probabilities by degree. This allows us to see how the chance of dropping out depends on education: ``` us1234 |> group_by(degree) |> summarise(pred_attrition = mean(attrit_pred)) ``` ``` ## # A tibble: 3 × 2 ## degree pred_attrition ## ## 1 Degree 0.433 ## 2 No degree 0.495 ## 3 NA ``` We see that people with a degree have a predicted attrition rate of 43%, compared with 49% for those without a degree. The predicted attrition probabilities can also be used to create weights that correct for attrition bias in our analyses. This is a more advanced topic that we will cover in a future post. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions on attrition and attrition bias Attrition is a common problem in longitudinal studies, and it can lead to smaller samples and biased results if the people who drop out are systematically different from those who remain in the study. As a result, it is essential to calculate attrition rates and estimate the extent of attrition bias. This can be done by comparing the characteristics of people who dropped out with those who remained in the study, either through simple comparisons or by running regression models. By understanding attrition and its potential bias, we can take steps to mitigate its effects and improve the validity of our longitudinal research. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management, statistics **Tags:** data cleaning, data management, r --- ### [Dynamic documents: a smarter way to share results](https://longitudinalanalysis.com/using-dynamic-documents-to-present-results-in-r/) **Published:** April 25, 2025 **Author:** Alex Cernat **Excerpt:** Learn how to use R Markdown to create a dynamic document for reproducible reports, automate updates, and seamlessly integrate code, text, and results in R. **Content:** A dynamic document is a powerful way to combine text, code, and results in a single, integrated file. Unlike static reports, dynamic documents allow you to generate outputs directly from your code, such as tables, figures, and analysis summaries. This ensures that your results are always up to date, as any change in your data or analysis is reflected in the document. The output of dynamic documents can take different shapes, such as HTML, PDF, Word, or slides and can be used to create research papers, presentations, websites and even books. ## Motivation and tools for dynamic documents Dynamic documents are especially useful for longitudinal data analysis because they: 1. **Enhance reproducibility**: By embedding code directly in the document, anyone reviewing your work can see exactly how the results were generated. 2. **Simplify updates**: If you adjust your dataset or rerun models, the document automatically updates to reflect these changes, saving time and avoiding errors. 3. **Support collaboration**: Dynamic documents provide a clear, transparent workflow that is easy for collaborators to follow and reproduce. 4. **Improve communication**: By combining narrative text with visuals and tables, dynamic documents make it easier to tell the story of your analysis. There are several tools for creating dynamic documents, with R Markdown being one of the most popular options in R. Here are some common types: - **R Markdown**: A versatile tool for creating HTML, PDF, Word documents and presentations. It integrates seamlessly with R and allows you to include code chunks that produce tables, graphs, and other outputs. - **Quarto**: An emerging alternative to R Markdown that supports multiple programming languages and outputs. - **Shiny**: While technically not a “document,” Shiny apps provide an interactive way to present analysis results. ## How to create dynamic documents in R To create a basic R Markdown file: 1. Click **File > New File > R Markdown** in RStudio. 2. Choose the document type (e.g., HTML, PDF, or Word) and add a title. 3. A template file will appear with example content. You can modify it to include the content that you want. Dynamic documents are ideal for presenting results in a clear and engaging way. Here’s a simple workflow for writing reports: 1. **Start with a clear outline**: Organize your report into logical sections, such as Introduction, Methods, Results, and Discussion. 2. **Embed code chunks for results**: Dynamic documents are organized around “code chunks”. These are pieces of R code that are integrated in the document. You can decide if the code is run or not or if it will appear in the output. For example, if you work with other people that understand R code you can show how your results were generated. If, on the other hand, the results are for a more general audience the code could be hidden. In this way you can use code to generate tables, figures, and key outputs. For example, to include a table summarizing model results you could use something like: ``` library(knitr) kable(summary(my_model)$coefficients, caption = "Model Coefficients") ``` 3. **Add narrative text**: Around your results or code chunks include text to explain your findings. For example: *“The table above shows that age has a positive effect on income, while gender is associated with significant differences.”* 4. **Incorporate visualizations**: Use packages like `ggplot2` to create graphs that illustrate your findings. 5. **Render the document**: Use the “Knit” button in RStudio to compile the document into your desired output format (e.g., HTML, PDF, or Word). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Example: creating a summary report using a dynamic document Here’s an example of a minimal R Markdown file structure for a longitudinal data analysis report: ![example of dynamic document using rmarkdown to presents results from a longitudinal model](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-4.png)![example of output from rmarkdown dynamic document presenting longitudinal results](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-3.png) ## Conclusions By combining code, text, and visuals in one place, dynamic documents ensure that your results are always accurate, reproducible, and easy to share. Whether you’re presenting to colleagues or preparing a final report, this approach simplifies the process and enhances the clarity of your analysis. Dynamic documents are an essential part of a reproducible workflow. They bridge the gap between data analysis and reporting, making it easier to communicate your findings in a reproducible way. You can lean more about how this fits into reproducible workflows and longitudinal data analysis [here](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/). You can also see how to include results from longitudinal data analysis [here](https://longitudinalanalysis.com/how-to-present-results-from-longitudinal-analysis/). More generally, you can learn about RMarkdown from [this free online book](https://bookdown.org/yihui/rmarkdown/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data management, r, visualization --- ### [Including time constant controls in Latent Growth Models](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/) **Published:** October 1, 2024 **Author:** Alex Cernat **Excerpt:** This post discusses incorporating time-constant predictors in Latent Growth Models (LGM) using R to better understand changes over time. It details coding in R using real data. It compares strategies for including these predictors and interpreting their effects on intercept and slope in LGMs. **Content:** In a previous post, we looked at [Latent Growth Models](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) (LGM) and how to estimate them in R. We used LGM to investigate both linear and [non-linear change](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/) in time and to concurrently examine average change and individual-level change. Once we understand the overall change in time, we typically want to include predictors to explain those changes. For example, individual characteristics might explain why some people start with a larger income and have different trajectories than others. Here, we will focus on including [time-constant](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) predictors in LGM to better understand the change in time. Time-constant variables do not change in time but might influence the change in the variables of interest. For example, we might want to use characteristics such as age or education at the start of the study to explain the change in income over time. ## Preparing the data You can follow this guide by running the code in `R` on your computer. Our examples will use synthetic (simulated) data modelled after [Understanding Society](https://www.understandingsociety.ac.uk/), a comprehensive panel study from the UK. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! In a previous blog, we cleaned the data, and have both the long and the wide formats. We will use that cleaned data here. Before we start, make sure you have the `tidyverse` and `lavaan` packages installed and loaded by running the following code: ``` library(tidyverse) library(lavaan) ``` We will mainly use the `lavaan` package to run LGMs and `tidyverse` for light data cleaning. Next, we will load the data prepared in the previous post. This contains long and wide format data in an “RData” file. We will load the long-format data and have a quick look at it: ``` load("./data/us_clean_syn.RData") ``` Before we get into the LGM, let’s examine the data we want to analyze. Imagine we are interested in how income changes over time and the main predictors of that change. We explored the basic LGM before in [this blog post](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/). Here, we want to build on that knowledge and include some predictors. We will use two predictors from our data that are coded as time-constant. These are the sex and age at the start of the study. We coded the first one as a factor variable, while the latter is continuous. We will centre the age variable to make the results easier to interpret. This means that the average age will become 0. This is a common practice in LGMs and makes interpreting the intercept easier. Also, the `lavaan` package does not work very well with factors, and when using categorical variables, it is better to use dummy variables (coded as 0 and 1). Here, we will create a new variable, “female”, that will take the value 1 for females and 0 otherwise. Here is the code to create these new control variables: ``` usw <- usw |> mutate(female = ifelse(gndr.fct == "Male", 0, 1), age_center = age - mean(age, na.rm = T)) ``` ## LGM with time-constant predictors We can expand the basic LGM model to investigate how time-constant predictors impact change estimates. This is relatively easy, given that we use the SEM framework. We simply include the predictor in the model and estimate two new regressions, explaining the intercept and slope of the growth model. We can represent this visually: ![SEM figure of latent growth model (LGM) with one hypotehtical time consant predictor](https://longitudinalanalysis.com/wp-content/uploads/2024/10/Untitled-1-1024x775.png)  Here, the regression coefficient 𝛽01 (“beta 01”) will show how 𝑥1 changes the expected score at the start of the study while 𝛽11 indicates how the rates of change differ by the values of 𝑥1. This is the equivalent of [introducing a main effect and an interaction with time in a multilevel model](https://longitudinalanalysis.com/explaining-change-using-multilevel-and-time-constant-predictors/). Note that the two latent variables are now the outcomes of a regression. As a result, they have residuals (𝜁1 (“zeta 1”) and 𝜁2). Also, the correlation between the intercept and slope, which tells us about the convergence or divergence in the data, is now between the residuals. Let’s see how sex and age impact the change in time of log income. We will use the two new variables we created. We expand the LGM to include two regressions with these two variables explaining the latent variables “i” and “s”: ``` model <- ' i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 i ~ female + age_center s ~ female + age_center' fit1 <- growth(model, data = usw) summary(fit1, standardized = TRUE) ``` ``` ## lavaan 0.6.17 ended normally after 45 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 13 ## ## Used Total ## Number of observations 24653 78159 ## ## Model Test User Model: ## ## Test statistic 1054.228 ## Degrees of freedom 9 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.220 0.867 ## logincome_2 1.000 1.220 0.908 ## logincome_3 1.000 1.220 0.981 ## logincome_4 1.000 1.220 1.044 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.303 0.226 ## logincome_3 2.000 0.606 0.487 ## logincome_4 3.000 0.909 0.778 ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~ ## female -0.399 0.017 -23.204 0.000 -0.327 -0.162 ## age_center 0.010 0.000 20.422 0.000 0.008 0.143 ## s ~ ## female 0.002 0.006 0.381 0.703 0.007 0.004 ## age_center -0.003 0.000 -18.472 0.000 -0.010 -0.173 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .i ~~ ## .s -0.244 0.005 -45.056 0.000 -0.687 -0.687 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .i 6.980 0.013 537.425 0.000 5.722 5.722 ## .s 0.096 0.004 22.271 0.000 0.317 0.317 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.493 0.011 43.628 0.000 0.493 0.249 ## .logincome_2 0.732 0.009 85.740 0.000 0.732 0.406 ## .logincome_3 0.704 0.008 89.210 0.000 0.704 0.456 ## .logincome_4 0.572 0.010 55.931 0.000 0.572 0.419 ## .i 1.417 0.017 81.170 0.000 0.952 0.952 ## .s 0.089 0.002 37.036 0.000 0.970 0.970 ``` We can see the new coefficients under the “Regressions” section of the output. They are interpreted as standard regression coefficients. For example, based on the model, females have lower log income at the start of the study (by 0.399), but their rate of change is slightly higher (by 0.002 but not significantly different from 0). On the other hand, if age is higher by one, the expected log income at the start of the study is larger by 0.01, but the rate of change is slightly lower (by 0.003). The interpretation of the intercepts now also changes because “i” and “s” are outcomes of a regression. Now, they refer to the expected value at the start of the study and the expected rate of change **when all the predictors are 0** (similar to a regular regression). So, for males with average age, the expected log income at the start of the study is 6.98, and the rate of change is 0.096. We can also represent the results using a SEM graph. This has the same information as the output but may be easier to understand. ![Graph showing predicted income growth over time for males and females based on latent growth model using time-constant predictors.](https://longitudinalanalysis.com/wp-content/uploads/2024/10/image-1-1024x780.png) Alternatively, we can write the regression equation and calculate the expected value at the start of the study and the rate of change under different scenarios. For the intercept, the regression model is: \\\[i = 6.98 -0.399 \* famale + 0.01 \* age\\\_center\\\] While for the slope it is: \\\[s = 0.096 + 0.002 \* famale -0.003 \* age\\\_center\\\] We saw that the expected intercept and slope for males with average age (~46 years old) are 6.98 and 0.096. Let’s see what the expected value would be for females aged 16. Because age is centred, age 16 takes the value -30 for “age\_centered” while the “females” variable takes the value 1. If we add these values to the above formulas, we have: \\\[i\_{female\\\_16} = 6.98 -0.399 \* 1 – 0.01 \* -30 = 6.281 \\\] \\\[s\_{female\\\_16} = 0.096 + 0.002 \* 1 -0.003 \* -30 = 0.188\\\] Based on these results, females aged 16 start with a lower expected log income (6.281 vs 6.98) but increase faster (0.188 vs 0.096) than males with average age. These results also impact the expected values of log income. For example, the predicted log income in wave 2 for males with an average age will be: \\\[logincome\\\_2 = 6.98 + 0.096= 7.076\\\] While for a female aged 16, it will be: \\\[logincome\\\_2\_{female\\\_16} = 6.281 + 0.188= 6.469\\\] ## An alternative way to include time-constant predictors This approach of introducing time-constant predictors in LGM is widely used, but it does come with an important assumption. We assume the impact of the predictors on the slope is constant. This is not always the case. For example, the effect of age on income might be different at the start of the study compared to the end. To account for this, we can use the predictors to explain observed variables in the model (instead of the latent ones). We could represent this in a new SEM graph as follows: ![Alternative way to inculde time constant predictors in LGM ](https://longitudinalanalysis.com/wp-content/uploads/2024/10/image-1024x778.png) Instead of two coefficients (on the intercept and slope), we have four different ones, one for each wave. This allows us to see if the effect of the predictors is constant in time. Returning to our example with log income, we can include female and age\_center as predictors of log income at each wave. The syntax is similar to the one above, but we change the outcome variables: ``` model <- ' i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 logincome_1 ~ female + age_center logincome_2 ~ female + age_center logincome_3 ~ female + age_center logincome_4 ~ female + age_center' fit2 <- growth(model, data = usw) summary(fit2, standardized = TRUE) ``` ``` ## lavaan 0.6.17 ended normally after 57 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 17 ## ## Used Total ## Number of observations 24653 78159 ## ## Model Test User Model: ## ## Test statistic 1018.627 ## Degrees of freedom 5 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.191 0.845 ## logincome_2 1.000 1.191 0.889 ## logincome_3 1.000 1.191 0.959 ## logincome_4 1.000 1.191 1.018 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.299 0.223 ## logincome_3 2.000 0.597 0.481 ## logincome_4 3.000 0.896 0.766 ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_1 ~ ## female -0.415 0.017 -23.819 0.000 -0.415 -0.146 ## age_center 0.011 0.001 20.447 0.000 0.011 0.128 ## logincome_2 ~ ## female -0.367 0.015 -23.795 0.000 -0.367 -0.136 ## age_center 0.006 0.000 13.159 0.000 0.006 0.082 ## logincome_3 ~ ## female -0.382 0.014 -26.983 0.000 -0.382 -0.153 ## age_center 0.004 0.000 8.721 0.000 0.004 0.055 ## logincome_4 ~ ## female -0.407 0.014 -28.473 0.000 -0.407 -0.173 ## age_center 0.001 0.000 2.888 0.004 0.001 0.018 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i ~~ ## s -0.244 0.005 -45.110 0.000 -0.687 -0.687 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i 6.980 0.013 537.413 0.000 5.861 5.861 ## s 0.096 0.004 22.273 0.000 0.322 0.322 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.492 0.011 43.584 0.000 0.492 0.248 ## .logincome_2 0.731 0.009 85.728 0.000 0.731 0.407 ## .logincome_3 0.704 0.008 89.220 0.000 0.704 0.456 ## .logincome_4 0.572 0.010 55.900 0.000 0.572 0.418 ## i 1.418 0.017 81.210 0.000 1.000 1.000 ## s 0.089 0.002 37.101 0.000 1.000 1.000 ``` The results regarding the first wave are slightly different from before, with females having lower incomes of 0.415 instead of 0.399 (compared to men), while the effect of age is the same. If we look at the impact on the other waves, we see that the effect of sex is not linear; for example, in wave 2, it is -0.367, while in wave 4, it is -0.407. This would indicate that the effect of females on income in the previous model might have been misleading. On the other hand, age’s effect seems to be approximately linear, decreasing with each wave. In this case, the results from the previous model may not have been a bad approximation. We could also use a mix of these two approaches. For example, we might allow for the effect of female to be different in time while for that of age to be constant. This would be done by explaining both the observed and latent variables. For example, we could allow for the effect of female to be different in time but for that of age to be constant using this code: ``` model <- ' i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 logincome_1 ~ female logincome_2 ~ female logincome_3 ~ female logincome_4 ~ female i + s ~ age_center' fit3 <- growth(model, data = usw) summary(fit3, standardized = TRUE) ``` ``` ## lavaan 0.6.17 ended normally after 49 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 15 ## ## Used Total ## Number of observations 24653 78159 ## ## Model Test User Model: ## ## Test statistic 1025.549 ## Degrees of freedom 7 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i =~ ## logincome_1 1.000 1.203 0.854 ## logincome_2 1.000 1.203 0.897 ## logincome_3 1.000 1.203 0.969 ## logincome_4 1.000 1.203 1.029 ## s =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.303 0.226 ## logincome_3 2.000 0.606 0.488 ## logincome_4 3.000 0.909 0.778 ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_1 ~ ## female -0.414 0.017 -23.764 0.000 -0.414 -0.146 ## logincome_2 ~ ## female -0.369 0.015 -23.982 0.000 -0.369 -0.137 ## logincome_3 ~ ## female -0.382 0.014 -27.061 0.000 -0.382 -0.153 ## logincome_4 ~ ## female -0.406 0.014 -28.435 0.000 -0.406 -0.172 ## i ~ ## age_center 0.010 0.000 20.422 0.000 0.008 0.145 ## s ~ ## age_center -0.003 0.000 -18.473 0.000 -0.010 -0.173 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .i ~~ ## .s -0.244 0.005 -45.100 0.000 -0.687 -0.687 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .i 6.980 0.013 537.415 0.000 5.800 5.800 ## .s 0.096 0.004 22.272 0.000 0.317 0.317 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.493 0.011 43.591 0.000 0.493 0.248 ## .logincome_2 0.731 0.009 85.732 0.000 0.731 0.407 ## .logincome_3 0.704 0.008 89.218 0.000 0.704 0.456 ## .logincome_4 0.572 0.010 55.904 0.000 0.572 0.418 ## .i 1.418 0.017 81.202 0.000 0.979 0.979 ## .s 0.089 0.002 37.091 0.000 0.970 0.970 ``` The coefficients for age are similar to those in the original model. We can compare the last two models to see if assuming linear change for age significantly decreases the fit of the model: ``` anova(fit2, fit3) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## fit2 5 292997 293135 1018.6 ## fit3 7 293000 293121 1025.5 6.9213 0.0099906 2 0.03141 * ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` If we look at the BIC (which tends to select simpler models), the results indicate that the model with a constant effect of age on income is better than the one that allows it to vary in time. This would indicate that the assumption of constant effects of age on the change of income is not too wrong in this case. We could also compare this model with the original one to see if the effect of female is constant in time. ``` anova(fit1, fit3) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## fit3 7 293000 293121 1025.5 ## fit1 9 293024 293130 1054.2 28.679 0.023262 2 5.921e-07 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` Here again, we see that the new model is better than the original one. This implies that assuming the effect of “female” to be equal in time might be problematic but reasonable for age. We can still calculate the expected values for the different scenarios in this model. Typically it is best to calculate the expected intercept and slope for different cases and then calculate the expected values for each wave. For example, the expected intercept and slope for someone who is 16 based on our model would be: \\\[i\_{age16} = 6.98 + 0.01 \\times (-30) = 6.68\\\] \\\[s\_{age16} = 0.096 – 0.003 \\times (-30) = 0.186\\\] We could use that information, for example, to calculate the expected log income for men and women at each wave. \\\[logincome\\\_{t}\_{male\\\_16} = i\_{age16} + s\_{age16} \* \\text{Time}\_t + \\beta\_{female, t} \* female = 6.68 + 0.186 \* \\text{Time}\_t\\\] \\\[logincome\\\_{t}\_{female\\\_16} = i\_{age16} + s\_{age16} \* \\text{Time}\_t + \\beta\_{female, t} \* female = 6.68 + 0.186 \* \\text{Time}\_t + \\beta\_{female, t} \* female \\\] Using this equation and the results from the model, we could calculate the expected values at wave 4 for males and females: \\\[logincome\\\_{4}\_{male\\\_16} = 6.68 + 0.186 \* 3 = 7.238\\\] \\\[logincome\\\_{4}\_{female\\\_16} = 6.68 + 0.186 \* 3 – 0.406 = 6.832\\\] You could calculate the expected values for each wave and each scenario. This would allow you to see how the expected values change over time and how they differ between people. The results could then be visualized or presented in a table to make them easier to interpret. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions Latent Growth Models provide a framework for studying change over time, and the inclusion of time-constant predictors helps better understand the predictors that explain both initial levels and the rate of change of key variables. In this post, we explored how to incorporate time-constant predictors into an LGM, modelling their effects on intercept (initial status) and slope (rate of change). We demonstrated how to estimate these models in R, extract key coefficients, and interpret their impact on the trajectory of the outcome variable. We also examined two different strategies for including time-constant predictors in the model. The first approach is more straightforward but assumes that the effects of change in time are constant. The second strategy creates a more complex model but allows for non-linear effects on the outcome. We also considered how to decide between the two approaches and even combine them. You can learn how to estimate non-linear LGM models [here](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/), and how to include time-varying predictors in [this post](https://longitudinalanalysis.com/how-to-include-time-varying-predictors-in-latent-growth-models-lgm-in-r/). Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** latent growth modelling, longitudinal data analysis, r, structural equation modelling --- ### [How to estimate and interpret parallel Latent Growth Models (LGM) in R: a step-by-step guide](https://longitudinalanalysis.com/how-to-estimate-and-interpret-parallel-latent-growth-models-lgm-in-r-a-step-by-step-guide/) **Published:** November 25, 2024 **Author:** Alex Cernat **Excerpt:** Learn how to estimate and interpret Parallel Latent Growth Models (LGM) in R and lavaan. This step-by-step guide explores modeling multiple trajectories, analyzing relationships over time, and visualizing results. Perfect for researchers in psychology, sociology, and public health using longitudinal data. **Content:** How does change in physical activity influence mental well-being trends? Do income and life satisfaction evolve in tandem during retirement? Can parenting stress and child behaviour patterns predict each other across the early years? These kinds of questions—spanning psychology, sociology, and public health—require a method that captures the simultaneous growth trajectories of two or more variables and examines their relationships over time. Parallel [latent growth models](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) (LGM) provide a robust framework for tackling these challenges. This post will explore how to estimate and interpret parallel LGMs using R, empowering you to answer complex longitudinal research questions. ## Preparing the data for analysis You can follow this guide by running the code in `R` on your computer. Our examples will use synthetic (simulated) data modelled after [Understanding Society](https://www.understandingsociety.ac.uk/), a comprehensive panel study from the UK. [In a previous blog](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/), we cleaned the data and have both the long and the wide formats. We will use that cleaned data here. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! Before we start, make sure you have the `tidyverse` and `lavaan` packages loaded by running the following code: ``` library(tidyverse) library(lavaan) ``` We will mainly use the `lavaan` package to run LGMs and `tidyverse` for light data cleaning. Next, we will load the data prepared in [the previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/). This contains long and wide format data in an “RData” file. We will load the long-format data and have a quick look at it: ``` load("./data/us_clean_syn.RData") ``` ## Parallel Latent Growth Models [Latent Growth Models](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) (LGM) are a type of structural equation model that estimates the growth trajectory of a variable over time. They are applied to longitudinal data, where the same cases are measured at multiple time points. LGMs can be used to estimate the average growth trajectory of a variable, as well as individual differences in growth rates. LGMs are estimated in the Structural Equation Modeling (SEM) framework, which allows the estimation of latent variables (unobserved constructs) and their relationships. This flexible framework can estimate many models, including parallel LGMs. Parallel LGMs are a type of LGM that simultaneously estimates the growth trajectories of two or more variables. This allows researchers to investigate how the growth trajectories of different variables are related to each other over time. For example, researchers might be interested in how income and life satisfaction change over time and whether these changes are associated. Parallel LGMs can be used to estimate the growth trajectories of both variables and the relationship between them. A visual representation of a parallel LGM is shown below. In this model, we have two latent variables representing the growth trajectories of two variables (e.g., income and life satisfaction). The arrows represent the relationships between the latent and observed variables (e.g., income and life satisfaction at each time point). The model estimates the growth trajectories of the two variables and the relationship between them over time. ![Diagram of a parallel latent growth model showing relationships between latent variables and observed variables over multiple time points.](https://longitudinalanalysis.com/wp-content/uploads/2024/11/image-3-814x1024.png) In this context, the key coefficient of interest is the relationship between the rate of change of one variable (*η*1) and the rate of change of another (*η*3) . In the simplest version, we can investigate this relationship using a correlation (as seen in the graph above). If, on the other hand, there is a clear expectation regarding the causal direction, the correlation can be replaced with a regression. To show how to estimate a parallel LGM in the real world, we will explore how a change in income is related to the change in satisfaction over four waves. To estimate the model, we need to specify the growth trajectories for both variables together. By default, `lavaan` includes correlations between latent variables, so we don’t need to add it explicitly. ``` model <- 'i_inc =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s_inc =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 i_sati =~ 1*sati_1 + 1*sati_2 + 1*sati_3 + 1*sati_4 s_sati =~ 0*sati_1 + 1*sati_2 + 2*sati_3 + 3*sati_4' fit <- growth(model, data = usw) summary(fit, standardized = T) ``` ``` ## lavaan 0.6-19 ended normally after 75 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 22 ## ## Used Total ## Number of observations 16360 51007 ## ## Model Test User Model: ## ## Test statistic 763.682 ## Degrees of freedom 22 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i_inc =~ ## logincome_1 1.000 1.163 0.871 ## logincome_2 1.000 1.163 0.907 ## logincome_3 1.000 1.163 0.986 ## logincome_4 1.000 1.163 1.039 ## s_inc =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.285 0.222 ## logincome_3 2.000 0.570 0.483 ## logincome_4 3.000 0.855 0.764 ## i_sati =~ ## sati_1 1.000 1.025 0.748 ## sati_2 1.000 1.025 0.739 ## sati_3 1.000 1.025 0.692 ## sati_4 1.000 1.025 0.695 ## s_sati =~ ## sati_1 0.000 0.000 0.000 ## sati_2 1.000 0.328 0.236 ## sati_3 2.000 0.655 0.442 ## sati_4 3.000 0.983 0.666 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i_inc ~~ ## s_inc -0.222 0.006 -36.902 0.000 -0.670 -0.670 ## i_sati 0.001 0.013 0.063 0.950 0.001 0.001 ## s_sati 0.021 0.006 3.742 0.000 0.056 0.056 ## s_inc ~~ ## i_sati 0.011 0.004 2.605 0.009 0.038 0.038 ## s_sati -0.003 0.002 -1.373 0.170 -0.027 -0.027 ## i_sati ~~ ## s_sati -0.186 0.009 -21.488 0.000 -0.554 -0.554 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i_inc 6.892 0.010 679.198 0.000 5.925 5.925 ## s_inc 0.075 0.003 22.691 0.000 0.262 0.262 ## i_sati 5.379 0.010 529.848 0.000 5.247 5.247 ## s_sati -0.081 0.004 -18.241 0.000 -0.246 -0.246 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.430 0.012 34.849 0.000 0.430 0.241 ## .logincome_2 0.655 0.009 69.936 0.000 0.655 0.398 ## .logincome_3 0.602 0.008 71.703 0.000 0.602 0.432 ## .logincome_4 0.502 0.011 45.130 0.000 0.502 0.400 ## .sati_1 0.826 0.020 41.008 0.000 0.826 0.440 ## .sati_2 1.137 0.016 72.278 0.000 1.137 0.591 ## .sati_3 1.460 0.019 75.688 0.000 1.460 0.665 ## .sati_4 1.278 0.025 50.977 0.000 1.278 0.587 ## i_inc 1.353 0.020 67.722 0.000 1.000 1.000 ## s_inc 0.081 0.003 30.919 0.000 1.000 1.000 ## i_sati 1.051 0.022 47.533 0.000 1.000 1.000 ## s_sati 0.107 0.005 22.356 0.000 1.000 1.000 ``` The coefficients of the parallel LGM can be interpreted as in the standard model. We discussed this in detail in [this blog post](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/). The key coefficient of interest in the parallel LGM is the correlation between the two rates of change, in this case “s\_inc” and “s\_sati”. In our model, the correlation between the two is -0.027. One way to interpret this is that an increase in satisfaction leads to a slight decrease in income. Given this is a correlation, we can also interpret it as an increase in income leads to a slight decrease in satisfaction. ### Visualizing the results To make things slightly easier to understand, we can consider what these latent variables represent and what the correlation implies. Based on our model, we can visualize the distribution of the latent variables. ``` # predict individual level values from model pred_fit <- predict(fit) # get means of the predicted values pred_fit_means <- map_df(as_tibble(pred_fit), mean) |> gather(key = key, value = value) # plot the distribution of the latent variables pred_fit |> as_tibble() |> gather(key = key, value = value) |> # reshape to long format ggplot(aes(value)) + geom_histogram() + geom_vline(data = pred_fit_means, aes(xintercept = value), color = "red") + facet_wrap(~key, scales = "free") + theme_bw() ``` ![Histogram of latent variable distributions for a parallel latent growth model, illustrating individual variations in income and life satisfaction at baseline and slope changes over time.](https://longitudinalanalysis.com/wp-content/uploads/2024/11/image-1-1024x731.png) The graph’s red lines represent the average values (equivalent to the values under “Intercepts” in the output), while the grey bars are a histogram of the predicted scores for different individuals. For example, “i\_inc” represents the expected log income at the start of the study. The average is close to 7. Some people have values above that at the beginning of the study (they are on the right of the graph), while some start lower. The interpretation of “i\_sati” is similar but refers to satisfaction at the start of the study. Looking at the slopes, we see that the average slope for income is slightly positive, while for satisfaction, it is somewhat negative. So, overall, income increases over time while satisfaction decreases. That being said, there is some variation around that average value, especially for satisfaction. When using the parallel LGM, we are interested in the relationship between these two slope latent variables. Our results show a slight negative correlation that can be visually represented using a scatter plot: ``` pred_fit |> as_tibble() |> ggplot(aes(s_inc, s_sati)) + geom_point(alpha = 0.05) + geom_smooth(method = "lm", se = F) + theme_bw() ``` ![Scatter plot showing the relationship between slopes of income growth and life satisfaction change in a parallel latent growth model, with trend line indicating a slight negative correlation](https://longitudinalanalysis.com/wp-content/uploads/2024/11/image-2-1024x731.png) The graph shows that someone who increases their income (on the right side of the graph) is expected to have a decreasing satisfaction (lower part of the graph). ### Adding regressions in parallel LGMs So far, we have not made any assumptions about the relationship between the two variables. We just estimated their correlation. If we have a clear expectation about the causal direction of the relationship, we can specify a regression instead of a correlation. For example, if we expect that changes in income lead to changes in satisfaction, we can specify a regression from income to satisfaction. This is done by adding a regression from the slope of income to the slope of satisfaction. The model new model would be: ``` model <- 'i_inc =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s_inc =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 i_sati =~ 1*sati_1 + 1*sati_2 + 1*sati_3 + 1*sati_4 s_sati =~ 0*sati_1 + 1*sati_2 + 2*sati_3 + 3*sati_4 s_sati ~ s_inc' fit2 <- growth(model, data = usw) summary(fit2, standardized = T) ``` ``` ## lavaan 0.6-19 ended normally after 63 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 20 ## ## Used Total ## Number of observations 16360 51007 ## ## Model Test User Model: ## ## Test statistic 1314.986 ## Degrees of freedom 24 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Latent Variables: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i_inc =~ ## logincome_1 1.000 1.163 0.871 ## logincome_2 1.000 1.163 0.907 ## logincome_3 1.000 1.163 0.986 ## logincome_4 1.000 1.163 1.038 ## s_inc =~ ## logincome_1 0.000 0.000 0.000 ## logincome_2 1.000 0.284 0.222 ## logincome_3 2.000 0.568 0.482 ## logincome_4 3.000 0.853 0.761 ## i_sati =~ ## sati_1 1.000 0.821 0.607 ## sati_2 1.000 0.821 0.600 ## sati_3 1.000 0.821 0.553 ## sati_4 1.000 0.821 0.538 ## s_sati =~ ## sati_1 0.000 0.000 0.000 ## sati_2 1.000 0.152 0.111 ## sati_3 2.000 0.304 0.205 ## sati_4 3.000 0.456 0.299 ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## s_sati ~ ## s_inc -0.074 0.021 -3.584 0.000 -0.139 -0.139 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i_inc ~~ ## s_inc -0.222 0.006 -36.853 0.000 -0.671 -0.671 ## i_sati 0.005 0.012 0.442 0.659 0.005 0.005 ## s_inc ~~ ## i_sati 0.017 0.004 4.265 0.000 0.073 0.073 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## i_inc 6.892 0.010 679.136 0.000 5.925 5.925 ## s_inc 0.075 0.003 22.705 0.000 0.262 0.262 ## i_sati 5.380 0.010 561.987 0.000 6.555 6.555 ## .s_sati -0.076 0.004 -17.063 0.000 -0.498 -0.498 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_1 0.431 0.012 34.930 0.000 0.431 0.241 ## .logincome_2 0.655 0.009 69.914 0.000 0.655 0.398 ## .logincome_3 0.601 0.008 71.694 0.000 0.601 0.433 ## .logincome_4 0.505 0.011 45.361 0.000 0.505 0.403 ## .sati_1 1.158 0.016 70.655 0.000 1.158 0.632 ## .sati_2 1.175 0.016 72.824 0.000 1.175 0.629 ## .sati_3 1.442 0.019 74.439 0.000 1.442 0.654 ## .sati_4 1.453 0.025 58.166 0.000 1.453 0.624 ## i_inc 1.353 0.020 67.700 0.000 1.000 1.000 ## s_inc 0.081 0.003 30.759 0.000 1.000 1.000 ## i_sati 0.674 0.012 54.513 0.000 1.000 1.000 ## .s_sati 0.023 0.003 8.021 0.000 0.981 0.981 ``` The model’s output is similar to the previous one, but now we have a regression from the slope of income to the slope of satisfaction. This regression is significant and negative, indicating that an increase in income leads to a decrease in satisfaction. More precisely, an increase of 1 log income leads to a decline of 0.07 in satisfaction. The model can be expanded in several ways. If, for example, we expect that some other variable mediates the relationship between income and satisfaction, we can include that in the model. We can also include non-linear effects, interactions, and other controls. The model can be expanded to include more than two variables. For example, we can include a third variable and investigate how the three variables are related over time. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusion Parallel latent growth models are a versatile and powerful tool for analysing the dynamic relationships between multiple trajectories over time. Whether you’re exploring how income and life satisfaction evolve together or investigating the interplay between physical activity and mental health, these models offer valuable insights into complex longitudinal data. As you apply these techniques, remember that the flexibility of parallel LGMs allows for further customisation—whether through adding mediators, exploring non-linear effects, or testing directional hypotheses. These extensions can help you tailor the model to your research questions and datasets. Learn more about LGMs by exploring our other blog posts on [estimating and visualising LGMs](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) and [including time-constant](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/) and [time-varying predictors](https://longitudinalanalysis.com/including-time-constant-controls-in-latent-growth-models/). If you want to learn how to model non-linear LGMs, check out [this post](https://longitudinalanalysis.com/estimating-non-linear-change-with-latent-growth-models-in-r/). To understand how LGM differs from the multilevel model for change, you can read more about it [here](https://longitudinalanalysis.com/comparing-the-multilevel-model-with-the-latent-growth-model/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** latent growth modelling, longitudinal data analysis, r, structural equation modelling, visualization --- ### [Cleaning longitudinal data in R: a step-by-step guide](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) **Published:** March 27, 2024 **Author:** alexcernat **Excerpt:** Explore key R commands for cleaning longitudinal data, including recoding variables and handling missing data effectively. **Content:** Cleaning longitudinal data is notoriously time-intensive, involving different steps, from importing data to merging and reshaping it. We covered this process in detail in [our previous blog post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/). The next phase focuses on data cleaning, which includes recoding variables, generating new ones, and addressing missing data. Utilizing the synthetic data from [our prior post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) based on [Understanding Society](https://www.understandingsociety.ac.uk/), we’ll explore key commands for longitudinal data cleaning, equipping you with the skills to prepare your own data effectively. ## Setting up the environment You can follow up with this guide by running the code in R. We will use synthetic data (i.e., simulated) based on [Understanding Society](https://www.understandingsociety.ac.uk/), a large panel study in the UK. [In a previous blog post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) we merged and reshaped the data in [the long format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). We will continue to work with this data here. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! Before we start, make sure you have the `tidyverse` and `haven` packages installed and loaded by running the following code: ``` install.packages("tidyverse") install.packages("haven") library(tidyverse) library(haven) ``` *Although the `haven` package is not required for importing data; it simplifies working with and recoding data originally imported using it.* Next, we will load the data that we prepared in [the previous post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/). The data was stored as an “rds” file. We can load it using the `read_rds()`: ``` usl <- read_rds("./data/usl_syn.rds") ``` And we can have a quick look at it to make sure all is in order: ``` glimpse(usl) ``` ``` ## Rows: 204,028 ## Columns: 15 ## $ pidp 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 10, 10, 10, 10, 11, 11, … ## $ wave "1", "2", "3", "4", "1", "2", "3", "4", "1", "2", "3", "4", … ## $ sex 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,… ## $ age 28, 28, 28, 28, 80, 80, 80, 80, 60, 60, 60, 60, 42, 42, … ## $ hiqual 1, 1, 1, 1, 9, 9, 9, 9, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1,… ## $ single 1, 1, 1, 0, 0, 0, 0, 0, 1, NA, NA, NA, 0, NA, … ## $ urban 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, 1, NA, … ## $ vote6 3, 4, 4, 4, 4, 4, 4, 3, 2, NA, NA, NA, 1, NA, … ## $ fimngrs 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 7… ## $ sclfsato -9, 6, 2, 1, 6, 6, -8, 3, 2, NA, NA, NA, -9, NA, … ## $ sf12pcs 54.51, 62.98, 56.97, 56.15, 53.93, 46.39, -8.00, 46.16, … ## $ sf12mcs 55.73, 36.22, 60.02, 59.04, 46.48, 45.39, -8.00, 37.02, … ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, … ## $ sf1 2, 2, 1, 3, 4, 3, 3, 3, 5, NA, NA, NA, 2, NA, … ## $ present TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, NA… ``` ## Cleaning categorical variables To get an intuition about how to clean data, we will start by exploring and recoding categorical variables. Let’s start with the sex variable. ``` count(usl, sex) ``` ``` ## # A tibble: 2 × 2 ## sex n ## ## 1 1 [male] 92364 ## 2 2 [female] 111664 ``` Because the data was imported from a Stata file with labels, we can check the variable measures and what each category means by using the attributes() command. You can check the data codebook or questionnaire if you do not have this information in your own data. ``` attributes(usl$sex) ``` ``` ## $label ## [1] "sex" ## ## $format.stata ## [1] "%8.0g" ## ## $labels ## missing inapplicable refusal don't know male female ## -9 -8 -2 -1 1 2 ## ## $class ## [1] "haven_labelled" "vctrs_vctr" "double" ``` When we have categorical variables, we typically want to code them as factors. This makes it much easier to use in statistical models and graphs. We see that the `sex` is numerical and not a factor (both in the `glimpse()` and the `count()` commands it `dbl` meaning double or a precise number). To make things easier to use later on, we can make a new variable called `gndr.fct` that is a factor with labels for “Man” and “Female”. We use the `mutate()` command together with `factor()` to do the recoding. We first input the original variable and then give the labels (should be added from the lowest value to the largest). ``` usl <- mutate(usl, gndr.fct = factor(sex, labels = c("Male", "Female"))) ``` After creating new variables, always check that the recoding is correct. We can use the `count()` command to compare the new variable with the old one: ``` count(usl, sex, gndr.fct) ``` ``` ## # A tibble: 2 × 3 ## sex gndr.fct n ## ## 1 1 [male] Male 92364 ## 2 2 [female] Female 111664 ``` We can use a similar approach for the single variable: ``` count(usl, single) ``` ``` ## # A tibble: 3 × 2 ## single n ## ## 1 0 [No] 96690 ## 2 1 [Yes] 55984 ## 3 NA 51354 ``` ``` usl <- mutate(usl, single.fct = factor(single, labels = c("In relationship", "Single"))) count(usl, single, single.fct) ``` ``` ## # A tibble: 3 × 3 ## single single.fct n ## ## 1 0 [No] In relationship 96690 ## 2 1 [Yes] Single 55984 ## 3 NA 51354 ``` Let’s next look at the “urban” variable: ``` count(usl, urban) ``` ``` ## # A tibble: 4 × 2 ## urban n ## ## 1 -9 [missing] 47 ## 2 1 [urban area] 119657 ## 3 2 [rural area] 32970 ## 4 NA 51354 ``` We see that we have some negative values. To understand what they stand for, we can again use the `attribute()` command. You might notice that the negative values are associated with missing data. This is the default in the Understanding Society data. Another useful command for recoding is case\_when(). For this function, we have to give some conditions and the values that the new variables should have if the condition is true (we put “~” between the condition and new values). We can have multiple conditions separated by commas. If some values are not included in any conditions, they will be coded as missing (which appears as `NA` in `R`). We use this command to make a new variable “urban.fct” that becomes “Urban” when the original variable was 1 and “Rural” when it was 2. We then make this new variable a factor using the `as.factor()` command (note that originally, it became a character or string variable): ``` usl <- mutate(usl, urban.fct = case_when(urban == 1 ~ "Urban", urban == 2 ~ "Rural"), urban.fct = as.factor(urban.fct)) count(usl, urban, urban.fct) ``` ``` ## # A tibble: 4 × 3 ## urban urban.fct n ## ## 1 -9 [missing] 47 ## 2 1 [urban area] Urban 119657 ## 3 2 [rural area] Rural 32970 ## 4 NA 51354 ``` Seems that it worked as expected. We can now move to the next variable, “hiqual”. ``` count(usl, hiqual) ``` ``` ## # A tibble: 7 × 2 ## hiqual n ## ## 1 -9 [missing] 444 ## 2 1 [Degree] 43932 ## 3 2 [Other higher] 22256 ## 4 3 [A level etc] 38896 ## 5 4 [GCSE etc] 41936 ## 6 5 [Other qual] 20816 ## 7 9 [No qual] 35748 ``` This can be recoded in several different ways. For now, we will create a dichotomous variable that codes people who have a degree versus everyone else. We can use a strategy similar to the one we used before. One difference now is that the condition needs to include multiple values. For this, we use the %in% command. This is used to check if elements of the vector on the left side are present on the right side. If this is true, it will give a TRUE value; if it’s not, it will give a FALSE. For example, if we want to check if “hiqual” has the values 3 to 9, we can use the following command: `hiqual %in% 3:9` *(`3:9` produces all the numbers between 3 and 9)*. We use this approach together with `case_when()` to make a factor variable that tells us if someone has a degree or not: ``` usl <- mutate(usl, degree.fct = case_when(hiqual %in% 1:2 ~ "Degree", hiqual %in% 3:9 ~ "No degree"), degree.fct = as.factor(degree.fct)) count(usl, hiqual, degree.fct) ``` ``` ## # A tibble: 7 × 3 ## hiqual degree.fct n ## ## 1 -9 [missing] 444 ## 2 1 [Degree] Degree 43932 ## 3 2 [Other higher] Degree 22256 ## 4 3 [A level etc] No degree 38896 ## 5 4 [GCSE etc] No degree 41936 ## 6 5 [Other qual] No degree 20816 ## 7 9 [No qual] No degree 35748 ``` It seems to have worked as expected. We can now move to the next variable, “vote6”. ``` count(usl, vote6) ``` ``` ## # A tibble: 9 × 2 ## vote6 n ## ## 1 -9 [missing] 264 ## 2 -7 [proxy] 9079 ## 3 -2 [refusal] 114 ## 4 -1 [don't know] 98 ## 5 1 [very] 14638 ## 6 2 [fairly] 49363 ## 7 3 [not very] 41082 ## 8 4 [or not at all interested?] 38036 ## 9 NA 51354 ``` It seems this variable also requires some work. We will use a slightly different strategy here to get the same result. Let’s start by coding first all the negative values as missing. We can use the ifelse() command for this. This takes a condition and then two values: the new value if the condition is true and the new value if the condition is false. We will make a condition that “vote6” is smaller than 0 (that covers all the missing codes). If this is true, we will code it as missing; if not, we will copy the original variable. We will then make a factor version of the variable using the `factor()` command and giving it the four labels that we saw in the table: ``` usl <- mutate(usl, vote6.rec = ifelse(vote6 < 0, NA, vote6), vote6.fct = factor(vote6.rec, labels = c("Very", "Fairly", "Not very", "Not at all"))) count(usl, vote6, vote6.fct) ``` ``` ## # A tibble: 9 × 3 ## vote6 vote6.fct n ## ## 1 -9 [missing] 264 ## 2 -7 [proxy] 9079 ## 3 -2 [refusal] 114 ## 4 -1 [don't know] 98 ## 5 1 [very] Very 14638 ## 6 2 [fairly] Fairly 49363 ## 7 3 [not very] Not very 41082 ## 8 4 [or not at all interested?] Not at all 38036 ## 9 NA 51354 ``` We can use a similar strategy for the “sclfsato” variable. This has a few negative values that we will code as missing. Also, this has seven categories, so it might be possible to use them either as continuous or categorical. We can have both versions ready for future use: ``` usl <- mutate(usl, sati = ifelse(sclfsato < 0, NA, sclfsato), sati.fct = factor(sati, labels = c("Completely dissatisfied", "Mostly dissatisfied", "Somewhat dissatisfied", "Neither sat nor dissat", "Somewhat satisfied", "Mostly satisfied", "Completely satisfied"))) count(usl, sclfsato, sati, sati.fct) ``` ``` ## # A tibble: 13 × 4 ## sclfsato sati sati.fct n ## ## 1 -9 [missing] NA 8371 ## 2 -8 [inapplicable] NA 11903 ## 3 -7 [proxy] NA 9079 ## 4 -2 [refusal] NA 25 ## 5 -1 [don't know] NA 599 ## 6 1 [completely dissatisfied] 1 Completely dissatisfied 3282 ## 7 2 [mostly dissatisfied] 2 Mostly dissatisfied 6642 ## 8 3 [somewhat dissatisfied] 3 Somewhat dissatisfied 9657 ## 9 4 [Neither Sat nor Dissat] 4 Neither sat nor dissat 11735 ## 10 5 [somewhat satisfied] 5 Somewhat satisfied 21619 ## 11 6 [mostly satisfied] 6 Mostly satisfied 55016 ## 12 7 [completely satisfied] 7 Completely satisfied 14746 ## 13 NA NA 51354 ``` ## Cleaning continuous variables Next, look at a continuous variable and see how we can clean it. We will focus on the “fimngrs” variable, the monthly income. We can explore it using a histogram and some summary statistics: ``` hist(usl$fimngrs) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-3.png) ``` summary(usl$fimngrs) ``` ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's ## -8851.8 640.3 1229.9 1594.6 2083.6 27587.5 51354 ``` It has a couple of issues, like negative values and some very high ones. If we think the negative values are not valid values, we can code them as missing using the `ifelse()` command. ``` usl <- mutate(usl, fimngrs = ifelse(fimngrs < 0, NA, fimngrs)) hist(usl$fimngrs) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-4.png) To improve the distribution, we can also cap very large values. This is a trade-off between precision and a more “normal” distribution. We can create a new variable and decide later which one to use depending on the analysis. The procedure is similar to before: ``` usl <- mutate(usl, fimngrs.cap = ifelse(fimngrs > 10000, 10000, fimngrs)) hist(usl$fimngrs.cap) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-1.png) Finally, we can create a logged version of the income. This is useful as income is usually skewed, and the logged version is more normally distributed. We can use the log() command for this. We add 10 to the variable to avoid issues with zero values that would be coded as missing otherwise. The constant value can be chosen by exploring the resulting distribution. ``` hist(log(usl$fimngrs.cap + 10)) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-5.png) Now we can create the new variable for later use: ``` usl <- mutate(usl, logincome = log(fimngrs.cap + 10)) ``` We should also check if our time variables are coded correctly. In this data, we have both the wave variable and the year of the interview (“intraday”). Let’s explore them using tables: ``` count(usl, wave) ``` ``` ## # A tibble: 4 × 2 ## wave n ## ## 1 1 51007 ## 2 2 51007 ## 3 3 51007 ## 4 4 51007 ``` ``` count(usl, istrtdaty) ``` ``` ## # A tibble: 10 × 2 ## istrtdaty n ## ## 1 -9 [missing] 27 ## 2 -8 [inapplicable] 965 ## 3 -1 [don't know] 1 ## 4 2009 24513 ## 5 2010 41941 ## 6 2011 36841 ## 7 2012 31585 ## 8 2013 15563 ## 9 2014 1238 ## 10 NA 51354 ``` The wave variable has no missing cases but is coded as a character (“chr” in the table). We should recode it as numeric. The “istrtdaty” variable has some missing cases and also is coded as numeric with labels “haven\_labelled”. We can recode them as missing using the `ifelse()` command. We can also recode both variables as numeric: ``` usl <- usl |> mutate(wave = as.numeric(wave), year = ifelse(istrtdaty < 0, NA, as.numeric(istrtdaty))) ``` ``` count(usl, wave) ``` ``` ## # A tibble: 4 × 2 ## wave n ## ## 1 1 51007 ## 2 2 51007 ## 3 3 51007 ## 4 4 51007 ``` ``` count(usl, istrtdaty, year) ``` ``` ## # A tibble: 10 × 3 ## istrtdaty year n ## ## 1 -9 [missing] NA 27 ## 2 -8 [inapplicable] NA 965 ## 3 -1 [don't know] NA 1 ## 4 2009 2009 24513 ## 5 2010 2010 41941 ## 6 2011 2011 36841 ## 7 2012 2012 31585 ## 8 2013 2013 15563 ## 9 2014 2014 1238 ## 10 NA NA 51354 ``` Now they look fine. ## Recoding multiple variables efficiently So far, we have recorded one variable at a time. Sometimes, we might want to recode multiple variables concurrently. Similar to what we saw [in the previous post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) with renaming variables using `rename_at()` we can also recode multiple variables. To see how to do this, we can check two variables that measure health: “sf12mcs” measures mental health, while “sf12pcs” measures physical health. Let’s see how they look: ``` hist(usl$sf12pcs) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-2.png) ``` hist(usl$sf12mcs) ``` ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-6.png) These variables are composites, and the values should be between 0 and 100, with averages of around 50. It seems we have negative values for missing categories. Let’s code them as `NA`. To be more efficient, we can use a special version of `mutate()` which can be used to apply a particular function to certain variables in the dataset. The command `mutate_at()` gets three inputs: - the data - the variables we want to apply the function to (`vars()`). Here, we use the helper function `matches()` to look up all variables that have “sf12” in the name - the function we want to apply to these variables. Here we use `ifelse()` with the condition that the variable is smaller than 0 (`. < 0`) then it should be recoded as `NA`, otherwise, it should keep the original values (`.`): ``` usl <- mutate_at(usl, vars(matches("sf12")), ~ ifelse(. < 0, NA, .)) summary(select(usl, sf12pcs, sf12mcs)) ``` ``` ## sf12pcs sf12mcs ## Min. : 4.41 Min. : 0.00 ## 1st Qu.:44.63 1st Qu.:44.72 ## Median :53.46 Median :51.98 ## Mean :49.63 Mean :49.90 ## 3rd Qu.:57.47 3rd Qu.:57.16 ## Max. :74.90 Max. :78.08 ## NA's :76039 NA's :76039 ``` ## Creating grouped and lagged statistics Many of the data-cleaning procedures we followed so far can also be used with cross-sectional data. However, longitudinal data has some unique features that require specific cleaning steps. For example, we might want to create individual averages for variables that are measured multiple times. Similarly, we might want to create lagged versions of the variables. We can use the `group_by()` and `mutate()` commands to create these new variables. Before that, let’s talk about the pipe operator `|>`. This operator is used to chain commands together. It takes the output of the command on the left side and uses it as the input for the command on the right side. This makes the code easier to read and write. We can use the pipe operator to chain multiple commands together. For example, we can use it to create a new variable and also make a table of it: ``` usl |> mutate(famale = sex - 1) |> count(famale, gndr.fct) ``` ``` ## # A tibble: 2 × 3 ## famale gndr.fct n ## ## 1 0 Male 92364 ## 2 1 Female 111664 ``` This is the same as the following code: ``` count(mutate(usl, female = sex - 1), female, gndr.fct) ``` ``` ## # A tibble: 2 × 3 ## female gndr.fct n ## ## 1 0 Male 92364 ## 2 1 Female 111664 ``` As you can see, the code with the pipe is much easier to read. We will use this approach quite a bit in the following steps. Sometimes, we want to create individual-level statistics. For example, we might want to create an individual-level average for the satisfaction variable. We can use the `group_by()` command to group the data by the person identifier pidp. Then, the `mutate()` command will create new variables that are the average of the original variable. We can also create a deviation variable, which is the difference between the original variable and the average. We can do this for the satisfaction variable and the two health variables: ``` usl <- usl %>% group_by(pidp) %>% mutate(sati.ind = mean(sati, na.rm = TRUE), sati.dev = sati - sati.ind, sf12pcs.ind = mean(sf12pcs, na.rm = TRUE), sf12pcs.dev = sf12pcs - sf12pcs.ind, sf12mcs.ind = mean(sf12mcs, na.rm = TRUE), sf12mcs.dev = sf12mcs - sf12mcs.ind) |> ungroup() ``` *Remember to `ungroup()` the data, otherwise future data cleaning actions will also be done separately for each group.* We can check how the new variables look for satisfaction: ``` usl |> select(pidp, wave, sati, sati.ind, sati.dev) |> head() ``` ``` ## # A tibble: 6 × 5 ## pidp wave sati sati.ind sati.dev ## ## 1 5 1 NA 3 NA ## 2 5 2 6 3 3 ## 3 5 3 2 3 -1 ## 4 5 4 1 3 -2 ## 5 6 1 6 5 1 ## 6 6 2 6 5 1 ``` We see that, for example, for an individual with “pidp” = 5, the average satisfaction is 3. We also see that the deviation score tells us if that particular wave was better or worse than the individual average. These variables can be useful in understanding complex relationships in the data. Let’s look at another example. We have worked with unbalanced data so far. Imagine you want to find out how many waves someone participated in. We can use the `sum(present)` command to count the number of waves someone was present and by combining that with the `group_by(pidp)` command, we can do this at the individual level. *This command works because even though “present” is coded as logical, R automatically converts `TRUE` to 1 in the background.* ``` usl <- usl %>% group_by(pidp) %>% mutate(waves = sum(present, na.rm = T)) |> ungroup() count(usl, waves) ``` ``` ## # A tibble: 4 × 2 ## waves n ## ## 1 1 40724 ## 2 2 26932 ## 3 3 29380 ## 4 4 106992 ``` If we wanted to create a balanced dataset, we could use the filter() command to keep only the cases present in all the waves, which now would be individuals with “wave” = 4. Another type of recoding we may want to do with longitudinal data is lagging. This means getting a value from a previous wave and adding it to the current wave. For example, this can be useful in investigating if health in the previous wave impacts productivity in the current wave. For this, we can use the `lag()` command. We can use the `group_by()` command to group the data by the person identifier `pidp` and then use the `mutate()` command to create lagged variables. We can do this for the satisfaction and the two health variables: ``` # Create lagged variables usl <- usl %>% group_by(pidp) %>% mutate(sati.lag = lag(sati), sf12pcs.lag = lag(sf12pcs), sf12mcs.lag = lag(sf12mcs)) |> ungroup() ``` We can check how the new variables look: ``` usl |> select(pidp, wave, sati, sati.lag, sf12pcs, sf12pcs.lag, sf12mcs, sf12mcs.lag) |> head() ``` ``` ## # A tibble: 6 × 8 ## pidp wave sati sati.lag sf12pcs sf12pcs.lag sf12mcs sf12mcs.lag ## ## 1 5 1 NA NA 54.5 NA 55.7 NA ## 2 5 2 6 NA 63.0 54.5 36.2 55.7 ## 3 5 3 2 6 57.0 63.0 60.0 36.2 ## 4 5 4 1 2 56.2 57.0 59.0 60.0 ## 5 6 1 6 NA 53.9 NA 46.5 NA ## 6 6 2 6 6 46.4 53.9 45.4 46.5 ``` As expected, the values have shifted down by one wave. This also means that the new values have missing information on the first wave. This is because there is no previous wave to take the information from. ### Clean up the data and reshape We have finished doing most of the data recoding we wanted to do. Now, we can remove the variables we do not need anymore using the `select()` command. We can use the “`-`” sign to exclude variables. ``` usl <- select(usl, -c(sex, urban, vote6, vote6.rec)) ``` We can also create a wide version of the data. This is useful for some types of analysis. You can see [the previous post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) for a discussion on how to use this command. ``` usw <- pivot_wider( usl, values_from = !c(pidp, gndr.fct, age, hiqual, wave, degree.fct, sati.ind, sf12pcs.ind, sf12mcs.ind, waves), names_sep = "_", names_from = wave ) ``` Finally, we can export both the long and wide data for future use: ``` save(usl, usw, file = "./data/us_clean_syn.RData") ``` ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions We have covered the most common commands used to clean longitudinal data. This included recoding categorical and continuous variables, creating individual-level statistics, and lagged variables. We have used the pipe operator to make the code more readable and efficient, and the `group_by()` and `mutate()` commands to create new variables at the individual level. ![cleaning longitudinal data in R common commands](https://longitudinalanalysis.com/wp-content/uploads/2024/03/long_process_cleaning-177x300.png) [Data transformation](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) and data cleaning are essential steps in the data analysis process. They can be time-consuming but are crucial for the quality of the analysis. We hope this guide has given you a good understanding of how to clean longitudinal data in R. You are now ready to move to the next stage, which is exploratory data analysis. You can check how to do that using tables and summary statistics [in this blog post](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) and how to do graphs in [this post](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/). You can adapt the process covered in this post and [the previous one](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) to your own data. Any questions or comments are welcome in the comment section below! --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data cleaning, data management, data restructuring, r --- ### [Preparing longitudinal data for analysis in R: a step-by-step guide](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) **Published:** March 25, 2024 **Author:** alexcernat **Excerpt:** Explore the crucial steps of data preparation for longitudinal analysis in R, from importing to reshaping data, in this step-by-step guide. **Content:** Longitudinal data is exciting as it can be used to explore individual-level change in time and to better understand causal relationships. Nevertheless, preparing data for longitudinal analysis is often complex and time-consuming. The process from raw data to analysis typically follows several steps: importing data, selecting and renaming variables, selecting cases, merging, and reshaping the data. ![](https://longitudinalanalysis.com/wp-content/uploads/2024/03/image-1024x176.png) In this guide, we simplify the task of preparing longitudinal data for analysis in R, breaking it down into smaller, manageable chunks to make the complex process more understandable. ## 0. Setting up what we need You can follow this guide on your own device by running the code in R. We will be using synthetic data (i.e., simulated) that is based on [Understanding Society](https://www.understandingsociety.ac.uk/), a large panel study in the UK. The data are synthetic and do not contain any sensitive information. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! I recommend setting up your working directory to the folder where you have the data. You can do this by running the following code: ``` setwd("path_to_your_folder") ``` *If you encounter issues, and assuming you’re using RStudio, navigate through the menu: “Session”->“Set Working Directory”->“Choose Directory” to select your data folder.* Before we start, make sure you have the following packages installed: “tidyverse” (for data cleaning) and “haven” (for importing data). You can install them by running the following code: ``` install.packages("tidyverse") install.packages("haven") ``` Once the packages are installed, we can load them: ``` library(tidyverse) library(haven) ``` ## 1. Importing the data We first need to import the data. For that, we will use the `read_dta()` function from the `haven` package as it is stored in the “.dta” format (created using Stata). We will import the data separately for each wave of the study. Here is the code for importing four waves of data: ``` us1_full <- read_dta("./data/a_indresp_syn.dta") us2_full <- read_dta("./data/b_indresp_syn.dta") us3_full <- read_dta("./data/c_indresp_syn.dta") us4_full <- read_dta("./data/d_indresp_syn.dta") ``` *Here,* I saved my data in a subfolder of the working directory called “data”. I am using a relative path where “.” represents the working directory and “data” is the subfolder. *If your data are directly in the working directory, you can use the name of the file as the input (e.g., read\_dta(“a\_indresp\_syn.dta”)). If you have issues importing the data, you can use the menu in RStudio: “File”->“Import Dataset”->“From Stata” and select the file you want to import.* ## 2. Selecting variables and renaming them The first steps when working with new data normally involve exploring it and selecting the variables of interest. A useful command for this is `glimpse()` which gives a quick overview of the data. Let’s look at the wave 1 data: ``` glimpse(us1_full) ``` ``` ## Rows: 51,007 ## Columns: 13 ## $ pidp 5, 6, 7, 10, 11, 13, 14, 16, 18, 19, 21, 22, 23, 24, 25, … ## $ a_sex 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2,… ## $ a_dvage 28, 80, 60, 42, 53, 51, 38, 27, 56, 31, 46, 30, 47, 3… ## $ a_hiqual_dv 1, 9, 3, 1, 1, 9, 4, 5, 2, 9, 1, 1, 9, 4, 1, 3, 3, 1,… ## $ a_single_dv 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0,… ## $ a_urban_dv 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1,… ## $ a_vote6 3, 4, 2, 1, -7, 3, 3, 4, 3, 4, 2, 4, 4, … ## $ a_fimngrs_dv 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13,… ## $ a_sclfsato -9, 6, 2, -9, -7, 3, 5, 6, -9, -9, 6, 3, 5, … ## $ a_sf12pcs_dv 54.51, 53.93, 33.18, 58.30, -7.00, 46.66, 49.93, 30.7… ## $ a_sf12mcs_dv 55.73, 46.48, 46.80, 49.41, -7.00, 37.17, 56.10, 45.2… ## $ a_istrtdaty 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 2010,… ## $ a_sf1 2, 4, 5, 2, 3, 5, 3, 2, 3, 2, 2, 2, 4, 3, 2, 4, 2, 2,… ``` We see that we have ~51,000 cases and 13 variables. I already selected a subset of the variables in the study, but in your own work, you would need to check the questionnaire, codebook and documentation to select the variables of interest (normally, there would be hundreds of variables). From wave 1, I want to keep all the variables. I will consider some variables to be time-constant and do not need to select them from future waves. For this example, I will treat “sex”, “age”, and “hiqual\_dv” (education) as time-constant variables. The rest of the variables will be treated as [time-varying](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (see [this blog post](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) for a discussion of the distinction). This means that for waves 2-4, we do not need to select these variables again. As such, we can select only the variables that are not time constant plus the id. Let’s check what variables we have in wave 2: ``` glimpse(us2_full) ``` ``` ## Rows: 54,462 ## Columns: 13 ## $ pidp 1, 2, 3, 4, 5, 6, 9, 11, 12, 13, 14, 16, 17, 18, 19, 20, … ## $ b_sex 2, 1, 2, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2,… ## $ b_dvage 49, 28, 65, 18, 29, 81, 47, 54, 16, 52, 39, 28, 18, 5… ## $ b_hiqual_dv 4, 3, 9, 9, 1, 9, 5, 1, 2, 9, 4, 5, 3, 1, 9, 5, 1, 1,… ## $ b_single_dv 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0,… ## $ b_urban_dv 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,… ## $ b_vote6 3, 3, 4, 4, 4, 4, 4, 2, 2, 4, 4, 4, -7, … ## $ b_fimngrs_dv 940.10, 1344.00, 514.66, 1111.65, 4002.50, 709.00,… ## $ b_sclfsato 6, -8, 5, 1, 6, 6, 6, 6, -8, 3, 5, 6, -7, … ## $ b_sf12pcs_dv 57.49, -8.00, 51.84, 36.36, 62.98, 46.39, -9.00, 54.8… ## $ b_sf12mcs_dv 54.20, -8.00, 54.96, 28.25, 36.22, 45.39, -9.00, 54.3… ## $ b_istrtdaty 2010, 2010, 2010, 2011, 2010, 2011, 2010, 2011, 2010,… ## $ b_sf1 2, 1, 3, 5, 2, 3, 2, 2, 2, 3, 2, 3, 4, 5, 3, 2, 3, 2,… ``` We can use the `select()` function to make smaller datasets with the variables we want. When we have a sequence of variables, we can use the “`:`” operator to select all the variables in a range. We will use this to make smaller versions of the data for waves 2 to 4. Note that in wave 4, we have another variable we do not want to keep, “ncars”, which we can exclude by putting a “-” in front of it. Here is the code for selecting the variables of interest in waves 2 to 4. ``` us2 <- select(us2_full, pidp, b_single_dv:b_sf1) us3 <- select(us3_full, pidp, c_single_dv:c_sf1) us4 <- select(us4_full, pidp, d_single_dv:d_sf1, -d_ncars) ``` We can also rename variables to make them easier to work with. The command is simply `rename()`. For example, we can rename the variable “`dvage`” to “`age`” and “`hiqual_dv`” to “`hiqual`” using the following code: ``` us1_full <- rename(us1_full, a_age = a_dvage, a_hiqual = a_hiqual_dv) ``` Before merging the data, we need to do two more types of renaming. It is generally easier to use prefixes instead of suffixes for time-varying variables as it facilitates data reshaping. Also, numbers are easier to work with than letters as wave number indicators. As a result, we will need to switch the naming convention from using letters as prefixes (the default in Understanding Society) to numbers as suffixes. Secondly, we do not need to keep the wave number in the variable name for variables we will treat as time-constant. We can use the `rename_all()` function to apply the renaming to all the variables. This takes as input the dataset and then a function that is applied to all the variables. In this case, we will use the str\_remove() function to remove the wave reference from the variable names. Here is the code: ``` us1_full <- rename_all(us1_full, ~str_remove(., "a_")) ``` *Two things to notice are that before the function, we need to add the “`~`” symbol and that we need to use the “`.`” to refer to the variable names.* We can use the same approach for the other waves of data, changing the letter used as the prefix accordingly using the code: ``` us2 <- rename_all(us2, ~str_remove(., "b_")) us3 <- rename_all(us3, ~str_remove(., "c_")) us4 <- rename_all(us4, ~str_remove(., "d_")) ``` Next, we need to add the new prefix, which will be the wave number. We can use the rename\_at() function. This function takes as input the dataset, the variables we want to rename and the function that will be applied to the variables. In this case, we will use the str\_c() function to add the wave number as a suffix. We also want to do this only for variables that are time-varying. For wave 1, the command would be: ``` us1_full <- rename_at(us1_full, vars(single_dv:sf1), ~str_c(., "_1")) ``` Let’s check if this worked as expected: ``` glimpse(us1_full) ``` ``` ## Rows: 51,007 ## Columns: 13 ## $ pidp 5, 6, 7, 10, 11, 13, 14, 16, 18, 19, 21, 22, 23, 24, 25, … ## $ sex 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2,… ## $ age 28, 80, 60, 42, 53, 51, 38, 27, 56, 31, 46, 30, 47, 3… ## $ hiqual 1, 9, 3, 1, 1, 9, 4, 5, 2, 9, 1, 1, 9, 4, 1, 3, 3, 1,… ## $ single_dv_1 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0,… ## $ urban_dv_1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1,… ## $ vote6_1 3, 4, 2, 1, -7, 3, 3, 4, 3, 4, 2, 4, 4, … ## $ fimngrs_dv_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13,… ## $ sclfsato_1 -9, 6, 2, -9, -7, 3, 5, 6, -9, -9, 6, 3, 5, … ## $ sf12pcs_dv_1 54.51, 53.93, 33.18, 58.30, -7.00, 46.66, 49.93, 30.7… ## $ sf12mcs_dv_1 55.73, 46.48, 46.80, 49.41, -7.00, 37.17, 56.10, 45.2… ## $ istrtdaty_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 2010,… ## $ sf1_1 2, 4, 5, 2, 3, 5, 3, 2, 3, 2, 2, 2, 4, 3, 2, 4, 2, 2,… ``` Let’s do the same for waves 2 to 4: ``` us2 <- rename_at(us2, vars(single_dv:sf1), ~str_c(., "_2")) us3 <- rename_at(us3, vars(single_dv:sf1), ~str_c(., "_3")) us4 <- rename_at(us4, vars(single_dv:sf1), ~str_c(., "_4")) glimpse(us2) ``` ``` ## Rows: 54,462 ## Columns: 10 ## $ pidp 1, 2, 3, 4, 5, 6, 9, 11, 12, 13, 14, 16, 17, 18, 19, 20, … ## $ single_dv_2 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0,… ## $ urban_dv_2 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,… ## $ vote6_2 3, 3, 4, 4, 4, 4, 4, 2, 2, 4, 4, 4, -7, … ## $ fimngrs_dv_2 940.10, 1344.00, 514.66, 1111.65, 4002.50, 709.00,… ## $ sclfsato_2 6, -8, 5, 1, 6, 6, 6, 6, -8, 3, 5, 6, -7, … ## $ sf12pcs_dv_2 57.49, -8.00, 51.84, 36.36, 62.98, 46.39, -9.00, 54.8… ## $ sf12mcs_dv_2 54.20, -8.00, 54.96, 28.25, 36.22, 45.39, -9.00, 54.3… ## $ istrtdaty_2 2010, 2010, 2010, 2011, 2010, 2011, 2010, 2011, 2010,… ## $ sf1_2 2, 1, 3, 5, 2, 3, 2, 2, 2, 3, 2, 3, 4, 5, 3, 2, 3, 2,… ``` We are almost done with the renaming. One thing you need to ensure before reshaping data is that the names of the variables are separated by a unique character from the wave number. If that is not the case, the data restructuring will not work properly. If we look at wave 2, we see that “\_” appears multiple times in the names of some of the variables (e.g., “fimngrs\_dv\_2”). We can remove the “\_dv” from the variable names to avoid this issue and make the names simpler (“\_dv” is used by Understanding Society to show which variables are derived after data collection). Here is the code for all four waves: ``` us1_full <- rename_all(us1_full, ~str_remove(., "_dv")) us2 <- rename_all(us2, ~str_remove(., "_dv")) us3 <- rename_all(us3, ~str_remove(., "_dv")) us4 <- rename_all(us4, ~str_remove(., "_dv")) ``` Let’s check the result: ``` glimpse(us2) ``` ``` ## Rows: 54,462 ## Columns: 10 ## $ pidp 1, 2, 3, 4, 5, 6, 9, 11, 12, 13, 14, 16, 17, 18, 19, 20, 2… ## $ single_2 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, … ## $ urban_2 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, … ## $ vote6_2 3, 3, 4, 4, 4, 4, 4, 2, 2, 4, 4, 4, -7, 4… ## $ fimngrs_2 940.10, 1344.00, 514.66, 1111.65, 4002.50, 709.00, … ## $ sclfsato_2 6, -8, 5, 1, 6, 6, 6, 6, -8, 3, 5, 6, -7, 5… ## $ sf12pcs_2 57.49, -8.00, 51.84, 36.36, 62.98, 46.39, -9.00, 54.80… ## $ sf12mcs_2 54.20, -8.00, 54.96, 28.25, 36.22, 45.39, -9.00, 54.37… ## $ istrtdaty_2 2010, 2010, 2010, 2011, 2010, 2011, 2010, 2011, 2010, … ## $ sf1_2 2, 1, 3, 5, 2, 3, 2, 2, 2, 3, 2, 3, 4, 5, 3, 2, 3, 2, … ``` We are now ready to move to the next stage. ## 3. Merging the data Before we merge the data, it is useful to create a variable that tells us if someone is present in each wave. This will be useful later on when exploring attrition patterns (i.e., people dropping out) and deciding whether to use a [balanced dataset](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) or not (more about this in [this blog post](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/)). We can create a simple variable that takes the value TRUE if the person is present in the data. When we merge the data, if someone is not present in that wave, they will coded as missing on the variable. We can use the `mutate()` function to create these variables. Here is the code for all four waves: ``` us1_full <- mutate(us1_full, present_1 = TRUE) us2 <- mutate(us2, present_2 = TRUE) us3 <- mutate(us3, present_3 = TRUE) us4 <- mutate(us4, present_4 = TRUE) ``` Now we have all we need to merge the data (always make sure you have a unique time constant identifier before you do this; in our case, we can use the `"pidp`” variable). We will do this in a sequence starting with waves 1 and 2 and then adding the other waves. We will use the `full_join()` function that takes the two datasets we want to merge and the variable we want to merge on as inputs. This command will keep all the cases even if some people are present in only one of the waves. We can later decide who we want to keep using the “present” variables. Here is the code needed to merge the four datasets: ``` us12 <- full_join(us1_full, us2, by = "pidp") us123 <- full_join(us12, us3, by = "pidp") us1234 <- full_join(us123, us4, by = "pidp") ``` Let’s check our new data: ``` glimpse(us1234) ``` ``` ## Rows: 73,101 ## Columns: 44 ## $ pidp 5, 6, 7, 10, 11, 13, 14, 16, 18, 19, 21, 22, 23, 24, 25, 2… ## $ sex 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, … ## $ age 28, 80, 60, 42, 53, 51, 38, 27, 56, 31, 46, 30, 47, 32… ## $ hiqual 1, 9, 3, 1, 1, 9, 4, 5, 2, 9, 1, 1, 9, 4, 1, 3, 3, 1, … ## $ single_1 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, … ## $ urban_1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, … ## $ vote6_1 3, 4, 2, 1, -7, 3, 3, 4, 3, 4, 2, 4, 4, 3… ## $ fimngrs_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13, … ## $ sclfsato_1 -9, 6, 2, -9, -7, 3, 5, 6, -9, -9, 6, 3, 5, 3… ## $ sf12pcs_1 54.51, 53.93, 33.18, 58.30, -7.00, 46.66, 49.93, 30.75… ## $ sf12mcs_1 55.73, 46.48, 46.80, 49.41, -7.00, 37.17, 56.10, 45.20… ## $ istrtdaty_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 2010, … ## $ sf1_1 2, 4, 5, 2, 3, 5, 3, 2, 3, 2, 2, 2, 4, 3, 2, 4, 2, 2, … ## $ present_1 TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE… ## $ single_2 1, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0… ## $ urban_2 1, 1, NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2… ## $ vote6_2 4, 4, NA, NA, 2, 4, 4, 4, 4, 3, 2, 4, 4, 2… ## $ fimngrs_2 4002.50, 709.00, NA, NA, 4010.01, 280.17, … ## $ sclfsato_2 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1… ## $ sf12pcs_2 62.98, 46.39, NA, NA, 54.80, 62.65, 56.10, 50.45… ## $ sf12mcs_2 36.22, 45.39, NA, NA, 54.37, 31.34, 57.16, 58.47… ## $ istrtdaty_2 2010, 2011, NA, NA, 2011, 2010, 2011, 2011, 2011, … ## $ sf1_2 2, 3, NA, NA, 2, 3, 2, 3, 5, 3, 3, 2, 5, 2… ## $ present_2 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TR… ## $ single_3 1, 0, NA, 0, 0, 0, 0, 1, 1, NA, 0, 0, 1, NA… ## $ urban_3 1, 1, NA, 1, 1, 1, 1, 1, 1, NA, 1, 1, 2, NA… ## $ vote6_3 4, 4, NA, 3, 3, 4, 3, 4, 4, NA, 2, 4, 4, NA… ## $ fimngrs_3 3616.67, 702.00, NA, 336.58, 2751.66, 666.67, … ## $ sclfsato_3 2, -8, NA, 5, 6, -8, 3, 6, 3, NA, 6, 6, 3, NA… ## $ sf12pcs_3 56.97, -8.00, NA, 56.15, 57.28, -8.00, 58.05, 58.57… ## $ sf12mcs_3 60.02, -8.00, NA, 49.12, 49.52, -8.00, 57.16, 55.17… ## $ istrtdaty_3 2011, 2012, NA, 2012, 2012, 2011, 2012, 2012, 2012, … ## $ sf1_3 1, 3, NA, 2, 3, 3, 2, 3, 3, NA, 2, 2, 4, NA… ## $ present_3 TRUE, TRUE, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, TR… ## $ single_4 0, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0… ## $ urban_4 1, 1, NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2… ## $ vote6_4 4, 3, NA, NA, 1, 4, 4, 4, 3, -7, 2, 4, 4, 3… ## $ fimngrs_4 850.50, 829.15, NA, NA, 4322.68, 423.58, … ## $ sclfsato_4 1, 3, NA, NA, 2, 6, 5, 5, 5, -7, 6, 4, 6, 4… ## $ sf12pcs_4 56.15, 46.16, NA, NA, 56.42, 42.78, 56.40, 52.24… ## $ sf12mcs_4 59.04, 37.02, NA, NA, 54.45, 46.40, 60.02, 52.40… ## $ istrtdaty_4 2012, 2013, NA, NA, 2013, 2012, 2013, 2013, 2014, … ## $ sf1_4 3, 3, NA, NA, 2, 4, 2, 3, 4, 3, 2, 2, 4, 2… ## $ present_4 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TR… ``` We have ~73,000 cases and 45 variables in this [“wide” data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). Before we reshape the data, let’s explore the participation in the study using the count() command and the “present” variables. Here, we make a table for participation in all four waves: ``` count(us1234, present_1, present_2, present_3, present_4) ``` ``` ## # A tibble: 15 × 5 ## present_1 present_2 present_3 present_4 n ## ## 1 TRUE TRUE TRUE TRUE 26748 ## 2 TRUE TRUE TRUE NA 4146 ## 3 TRUE TRUE NA TRUE 1618 ## 4 TRUE TRUE NA NA 5779 ## 5 TRUE NA TRUE TRUE 1581 ## 6 TRUE NA TRUE NA 622 ## 7 TRUE NA NA TRUE 332 ## 8 TRUE NA NA NA 10181 ## 9 NA TRUE TRUE TRUE 10805 ## 10 NA TRUE TRUE NA 2069 ## 11 NA TRUE NA TRUE 634 ## 12 NA TRUE NA NA 2663 ## 13 NA NA TRUE TRUE 2334 ## 14 NA NA TRUE NA 1039 ## 15 NA NA NA TRUE 2550 ``` We see that around 26,000 were present in all the waves, ~4,000 dropped out at wave 4, etc. We also see that some people joined later in the study. For example, around 12,000 people joined at wave 2. It is important to understand these patterns before deciding how to handle the missing data. For example, everyone who joined after wave 2 will be missing in the wave 1 data, including our time constant variables. We could choose to drop these people or get their time-constant information from wave 2. For now, we will keep all the people present in wave 1, even if they drop out later. This is still unbalanced data (some people drop out), but the reference population is the sample in wave 1 (more about balanced and unbalanced data can be found in [this post](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/)). The code for filtering the cases and describing the data are: ``` us <- filter(us1234, present_1 == TRUE) count(us, present_1, present_2, present_3, present_4) ``` ``` ## # A tibble: 8 × 5 ## present_1 present_2 present_3 present_4 n ## ## 1 TRUE TRUE TRUE TRUE 26748 ## 2 TRUE TRUE TRUE NA 4146 ## 3 TRUE TRUE NA TRUE 1618 ## 4 TRUE TRUE NA NA 5779 ## 5 TRUE NA TRUE TRUE 1581 ## 6 TRUE NA TRUE NA 622 ## 7 TRUE NA NA TRUE 332 ## 8 TRUE NA NA NA 10181 ``` Now, we have all the variables and cases we want and can move to the next step. ## 4. Reshaping the data In general, it is easier to clean data when it is in the long format as we need to recode variables just once, regardless of the number of time points. This does assume that the variables are coded consistently over time (i.e., values on the same variable mean the same thing). We will use the pivot\_longer() command to do this (see an overall introduction to pivoting here and an introduction to how to apply it to longitudinal data here). We will use the following inputs: - the data, - the columns that are time-varying (notice here that we select the time constant variables and put “!” to take the opposite, i.e., the other variables), - the separator that delimitates the name of the variables from the wave number, - the pattern in the name. Here, we say that the first part of the name is the variable name (defined as “.value”) and that the suffix should be a new variable called “wave”. This applied to our data results in the following code: ``` usl <- pivot_longer( us, cols = !c(pidp, sex, age, hiqual), names_sep = "_", names_to = c(".value", "wave") ) glimpse(usl) ``` ``` ## Rows: 204,028 ## Columns: 15 ## $ pidp 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 10, 10, 10, 10, 11, 11, … ## $ sex 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,… ## $ age 28, 28, 28, 28, 80, 80, 80, 80, 60, 60, 60, 60, 42, 42, … ## $ hiqual 1, 1, 1, 1, 9, 9, 9, 9, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1,… ## $ wave "1", "2", "3", "4", "1", "2", "3", "4", "1", "2", "3", "4", … ## $ single 1, 1, 1, 0, 0, 0, 0, 0, 1, NA, NA, NA, 0, NA, … ## $ urban 1, 1, 1, 1, 1, 1, 1, 1, 1, NA, NA, NA, 1, NA, … ## $ vote6 3, 4, 4, 4, 4, 4, 4, 3, 2, NA, NA, NA, 1, NA, … ## $ fimngrs 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 7… ## $ sclfsato -9, 6, 2, 1, 6, 6, -8, 3, 2, NA, NA, NA, -9, NA, … ## $ sf12pcs 54.51, 62.98, 56.97, 56.15, 53.93, 46.39, -8.00, 46.16, … ## $ sf12mcs 55.73, 36.22, 60.02, 59.04, 46.48, 45.39, -8.00, 37.02, … ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, … ## $ sf1 2, 2, 1, 3, 4, 3, 3, 3, 5, NA, NA, NA, 2, NA, … ## $ present TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, NA… ``` We now have many more rows, ~ 204,000, and fewer columns, 15. Now, each row is an individual measured at a particular point in time. To enhance the visibility of the data’s structure, let’s reorganize the columns and rows, positioning “pidp” and “wave” at the start and ordering the data by these two variables. This rearrangement allows us to observe each individual’s progression over time easily. For row sorting, we’ll employ the `arrange()` function. Here’s the code that executes these adjustments, subsequently displaying the initial lines of the data for review: ``` usl <- select(usl, pidp, wave, everything()) usl <- arrange(usl, pidp, wave) head(usl) ``` ``` ## # A tibble: 6 × 15 ## pidp wave sex age hiqual single urban vote6 fimngrs sclfsato ## ## 1 5 1 1 [male] 28 1 [Deg… 1 [Yes] 1 [urb… 3 [not… 3284. -9 [mis… ## 2 5 2 1 [male] 28 1 [Deg… 1 [Yes] 1 [urb… 4 [or … 4002. 6 [mos… ## 3 5 3 1 [male] 28 1 [Deg… 1 [Yes] 1 [urb… 4 [or … 3617. 2 [mos… ## 4 5 4 1 [male] 28 1 [Deg… 0 [No] 1 [urb… 4 [or … 850. 1 [com… ## 5 6 1 1 [male] 80 9 [No … 0 [No] 1 [urb… 4 [or … 896 6 [mos… ## 6 6 2 1 [male] 80 9 [No … 0 [No] 1 [urb… 4 [or … 709 6 [mos… ## # ℹ 5 more variables: sf12pcs , sf12mcs , ## # istrtdaty , sf1 , present ``` *Note that here `everything()` is a helper function that keeps all the other variables in their current order.* When we finish cleaning the data, we can also create [a wide version of the data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). This is useful for some types of analysis and descriptive statistics. We can use the `pivot_wider()` command with the following inputs: - long data - time-varying variables (`values_from`) - how to separate the suffix (`names_sep`) - where to take the suffix from (`names_from`) In our case, reshaping the data to wide format can be done using the following code: ``` usw <- pivot_wider( usl, values_from = !c(pidp, sex, age, hiqual, wave), names_sep = "_", names_from = wave ) glimpse(usw) ``` ``` ## Rows: 51,007 ## Columns: 44 ## $ pidp 5, 6, 7, 10, 11, 13, 14, 16, 18, 19, 21, 22, 23, 24, 25, 2… ## $ sex 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, … ## $ age 28, 80, 60, 42, 53, 51, 38, 27, 56, 31, 46, 30, 47, 32… ## $ hiqual 1, 9, 3, 1, 1, 9, 4, 5, 2, 9, 1, 1, 9, 4, 1, 3, 3, 1, … ## $ single_1 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, … ## $ single_2 1, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0… ## $ single_3 1, 0, NA, 0, 0, 0, 0, 1, 1, NA, 0, 0, 1, NA… ## $ single_4 0, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0… ## $ urban_1 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, … ## $ urban_2 1, 1, NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2… ## $ urban_3 1, 1, NA, 1, 1, 1, 1, 1, 1, NA, 1, 1, 2, NA… ## $ urban_4 1, 1, NA, NA, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2… ## $ vote6_1 3, 4, 2, 1, -7, 3, 3, 4, 3, 4, 2, 4, 4, 3… ## $ vote6_2 4, 4, NA, NA, 2, 4, 4, 4, 4, 3, 2, 4, 4, 2… ## $ vote6_3 4, 4, NA, 3, 3, 4, 3, 4, 4, NA, 2, 4, 4, NA… ## $ vote6_4 4, 3, NA, NA, 1, 4, 4, 4, 3, -7, 2, 4, 4, 3… ## $ fimngrs_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13, … ## $ fimngrs_2 4002.50, 709.00, NA, NA, 4010.01, 280.17, … ## $ fimngrs_3 3616.67, 702.00, NA, 336.58, 2751.66, 666.67, … ## $ fimngrs_4 850.50, 829.15, NA, NA, 4322.68, 423.58, … ## $ sclfsato_1 -9, 6, 2, -9, -7, 3, 5, 6, -9, -9, 6, 3, 5, 3… ## $ sclfsato_2 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1… ## $ sclfsato_3 2, -8, NA, 5, 6, -8, 3, 6, 3, NA, 6, 6, 3, NA… ## $ sclfsato_4 1, 3, NA, NA, 2, 6, 5, 5, 5, -7, 6, 4, 6, 4… ## $ sf12pcs_1 54.51, 53.93, 33.18, 58.30, -7.00, 46.66, 49.93, 30.75… ## $ sf12pcs_2 62.98, 46.39, NA, NA, 54.80, 62.65, 56.10, 50.45… ## $ sf12pcs_3 56.97, -8.00, NA, 56.15, 57.28, -8.00, 58.05, 58.57… ## $ sf12pcs_4 56.15, 46.16, NA, NA, 56.42, 42.78, 56.40, 52.24… ## $ sf12mcs_1 55.73, 46.48, 46.80, 49.41, -7.00, 37.17, 56.10, 45.20… ## $ sf12mcs_2 36.22, 45.39, NA, NA, 54.37, 31.34, 57.16, 58.47… ## $ sf12mcs_3 60.02, -8.00, NA, 49.12, 49.52, -8.00, 57.16, 55.17… ## $ sf12mcs_4 59.04, 37.02, NA, NA, 54.45, 46.40, 60.02, 52.40… ## $ istrtdaty_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 2010, … ## $ istrtdaty_2 2010, 2011, NA, NA, 2011, 2010, 2011, 2011, 2011, … ## $ istrtdaty_3 2011, 2012, NA, 2012, 2012, 2011, 2012, 2012, 2012, … ## $ istrtdaty_4 2012, 2013, NA, NA, 2013, 2012, 2013, 2013, 2014, … ## $ sf1_1 2, 4, 5, 2, 3, 5, 3, 2, 3, 2, 2, 2, 4, 3, 2, 4, 2, 2, … ## $ sf1_2 2, 3, NA, NA, 2, 3, 2, 3, 5, 3, 3, 2, 5, 2… ## $ sf1_3 1, 3, NA, 2, 3, 3, 2, 3, 3, NA, 2, 2, 4, NA… ## $ sf1_4 3, 3, NA, NA, 2, 4, 2, 3, 4, 3, 2, 2, 4, 2… ## $ present_1 TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE… ## $ present_2 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TR… ## $ present_3 TRUE, TRUE, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, TR… ## $ present_4 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TR… ``` ## 5. Save the data Now that we have the data in a long and wide format, we can save it for future use. For example, we could save the long data as a “rds” file using `write_rds()`: ``` write_rds(usl, "./data/usl_syn.rds") ``` ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions The process of preparing data for longitudinal analysis can be complex and time-consuming, yet it is the cornerstone of sound research. The journey begins with importing data, followed by selecting and renaming variables, merging datasets, choosing relevant cases, and reshaping the data. This step-by-step guide aimed to equip you with the necessary tools to prepare your own data for analysis efficiently. After following the guide on your computer, try adapting the code to your own data. Put any questions you might have in the comments below! ![Data preparation process for longitudinal analysis using R](http://longitudinalanalysis.com/wp-content/uploads/2024/03/data_prep_diag-1024x176.png) After transforming the data, the next stage is [to clean it](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) by recoding the variables. Then, it can be explored [using tables](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) and [visualization](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data cleaning, data management, data restructuring, r --- ### [Exploring longitudinal data in R: tables and summaries](https://longitudinalanalysis.com/exploring-longitudinal-data-in-r-tables-and-summaries/) **Published:** March 28, 2024 **Author:** Alex Cernat **Excerpt:** Unlock the power of R for longitudinal data analysis! Learn to navigate tables and summaries with ease in our latest guide. **Content:** Longitudinal data can be complex and difficult to understand. Exploring and describing it is an important part of working with this data type. This process is part of what’s known as Exploratory Data Analysis (EDA), a crucial step in understanding your data. In this blog post, we will see how to use tables and summary statistics to describe longitudinal data. In R, there are different specialized packages for this, but here we will focus on `base R` (i.e., the commands that come by default when you install `R`) and `tidyverse` (a popular package for cleaning and visualizing data) to cover the most common descriptives used with longitudinal data. ## Setting up the environment You can download the data we cleaned in [a previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) if you want to follow along. Remember to set up your working directory [as previously described](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/ "as previously described"). Next, let’s load the packages we need. Here, we will be mainly using the `tidyverse` package: ``` library(tidyverse) ``` With that out of the way, we can load the data. The data we will be using is the us\_clean\_syn dataset. We transformed and cleaned this dataset in two previous blog posts: [here](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) and [here](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ``` load("./data/us_clean_syn.RData") ``` This file includes both the data in [the wide format](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) and the long format. As we will see later, each format can be useful for different types of tables and summary statistics. ## Simple tables and descriptives Let’s start with the basics. We will first look at the structure of the data using the `glimpse()` function. This will give us an overview of the variables in the long dataset. ``` glimpse(usl) ``` ``` ## Rows: 204,028 ## Columns: 31 ## $ pidp 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 10, 10, 10, 10, 11, 11… ## $ wave "1", "2", "3", "4", "1", "2", "3", "4", "1", "2", "3", "4"… ## $ age 28, 28, 28, 28, 80, 80, 80, 80, 60, 60, 60, 60, 42, 42… ## $ hiqual 1, 1, 1, 1, 9, 9, 9, 9, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, … ## $ single 1, 1, 1, 0, 0, 0, 0, 0, 1, NA, NA, NA, 0, NA… ## $ fimngrs 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ sclfsato -9, 6, 2, 1, 6, 6, -8, 3, 2, NA, NA, NA, -9, NA… ## $ sf12pcs 54.51, 62.98, 56.97, 56.15, 53.93, 46.39, NA, 46.16, 33.18… ## $ sf12mcs 55.73, 36.22, 60.02, 59.04, 46.48, 45.39, NA, 37.02, 46.80… ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, … ## $ sf1 2, 2, 1, 3, 4, 3, 3, 3, 5, NA, NA, NA, 2, NA… ## $ present TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, … ## $ gndr.fct Male, Male, Male, Male, Male, Male, Male, Male, Male, Male… ## $ single.fct Single, Single, Single, In relationship, In relationship, … ## $ urban.fct Urban, Urban, Urban, Urban, Urban, Urban, Urban, Urban, Ur… ## $ degree.fct Degree, Degree, Degree, Degree, No degree, No degree, No d… ## $ vote6.fct Not very, Not at all, Not at all, Not at all, Not at all, … ## $ sati NA, 6, 2, 1, 6, 6, NA, 3, 2, NA, NA, NA, NA, NA, 5, NA, NA… ## $ sati.fct NA, Mostly satisfied, Mostly dissatisfied, Completely diss… ## $ fimngrs.cap 3283.87, 4002.50, 3616.67, 850.50, 896.00, 709.00, 702.00,… ## $ logincome 8.099818, 8.297170, 8.196070, 6.757514, 6.809039, 6.577861… ## $ sati.ind 3.000000, 3.000000, 3.000000, 3.000000, 5.000000, 5.000000… ## $ sati.dev NA, 3.000000, -1.000000, -2.000000, 1.000000, 1.000000, NA… ## $ sf12pcs.ind 57.65250, 57.65250, 57.65250, 57.65250, 48.82667, 48.82667… ## $ sf12pcs.dev -3.1425000, 5.3275000, -0.6825000, -1.5025000, 5.1033333, … ## $ sf12mcs.ind 52.75250, 52.75250, 52.75250, 52.75250, 42.96333, 42.96333… ## $ sf12mcs.dev 2.977500, -16.532500, 7.267500, 6.287500, 3.516667, 2.4266… ## $ waves 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4… ## $ sati.lag NA, NA, 6, 2, NA, 6, 6, NA, NA, 2, NA, NA, NA, NA, NA, 5, … ## $ sf12pcs.lag NA, 54.51, 62.98, 56.97, NA, 53.93, 46.39, NA, NA, 33.18, … ## $ sf12mcs.lag NA, 55.73, 36.22, 60.02, NA, 46.48, 45.39, NA, NA, 46.80, … ``` This list of all the variables in the data shows their type and the first few values. We see that we have 31 variables in the dataset and around 204,000 rows. The `wave` variable is the time variable, `pidp` is the unique identifier for each person. We can use the `count()` command to do a simple frequency table. For example, the distribution of the voting variable over all points in time is: ``` count(usl, vote6.fct) ``` ``` ## # A tibble: 5 × 2 ## vote6.fct n ## ## 1 Very 14638 ## 2 Fairly 49363 ## 3 Not very 41082 ## 4 Not at all 38036 ## 5 60909 ``` We can also calculate the proportions by creating a new column using `mutate()`. ``` count(usl, vote6.fct) |> mutate(prop = n / sum(n)) ``` ``` ## # A tibble: 5 × 3 ## vote6.fct n prop ## ## 1 Very 14638 0.0717 ## 2 Fairly 49363 0.242 ## 3 Not very 41082 0.201 ## 4 Not at all 38036 0.186 ## 5 60909 0.299 ``` *We introduced the `|>` (pipe) command in a previous post [here](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/).* The alternative approach is by using `Base R` is with the `table()` command: ``` table(usl$vote6.fct, useNA = "always") ``` ``` ## ## Very Fairly Not very Not at all ## 14638 49363 41082 38036 60909 ``` And if we want the proportions, we can use the `prop.table()` command: ``` table(usl$vote6.fct, useNA = "always") |> prop.table() |> round(2) ``` ``` ## ## Very Fairly Not very Not at all ## 0.07 0.24 0.20 0.19 0.30 ``` *Note that we used* round(2) to have just two decimal points printed to *make the table easier to read.* We can also quickly summarise the variables in the dataset using the summary() command. Here, we will select only the variables from `gndr.fct` to `fimngrs.cap` for brevity: ``` usl |> select(gndr.fct:fimngrs.cap) |> summary() ``` ``` ## gndr.fct single.fct urban.fct degree.fct ## Male : 92364 In relationship:96690 Rural: 32970 Degree : 66188 ## Female:111664 Single :55984 Urban:119657 No degree:137396 ## NA's :51354 NA's : 51401 NA's : 444 ## ## ## ## ## vote6.fct sati sati.fct ## Very :14638 Min. :1.00 Mostly satisfied :55016 ## Fairly :49363 1st Qu.:4.00 Somewhat satisfied :21619 ## Not very :41082 Median :6.00 Completely satisfied :14746 ## Not at all:38036 Mean :5.17 Neither sat nor dissat:11735 ## NA's :60909 3rd Qu.:6.00 Somewhat dissatisfied : 9657 ## Max. :7.00 (Other) : 9924 ## NA's :81331 NA's :81331 ## fimngrs.cap ## Min. : 0.0 ## 1st Qu.: 642.2 ## Median : 1231.7 ## Mean : 1591.3 ## 3rd Qu.: 2084.2 ## Max. :10000.0 ## NA's :51519 ``` We see that this command figures out what type of variable we have and shows the appropriate summary statistics. For example, for the `gndr.fct` variable, we see that it is a factor with two levels: `Female` and `Male`. For the `fimngrs.cap` variable, we see that it is a numeric variable with a mean of 1591 and a median of 1231. ## Grouped summary tables We can also calculate grouped statics. In the context of longitudinal data, this is most often used to describe change in time using [long data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). For example, we can calculate the mean income over time using a combination of `group_by()` and `summarise()` functions: ``` usl |> group_by(wave) |> summarise(income = mean(fimngrs, na.rm = T)) ``` ``` ## # A tibble: 4 × 2 ## wave income ## ## 1 1 1465. ## 2 2 1579. ## 3 3 1685. ## 4 4 1749. ``` We can do multiple summaries at once. For example, we can calculate the mean income, variance of income, proportion of cases missing on income, mean age, and proportion of singles over time: ``` usl |> group_by(wave) |> summarise(mean_income = mean(fimngrs, na.rm = T), var_income = var(fimngrs, na.rm = T), miss_income = mean(is.na(fimngrs)), mean_age = mean(age, na.rm = T), prop_single = mean(single, na.rm = T)) ``` ``` ## # A tibble: 4 × 6 ## wave mean_income var_income miss_income mean_age prop_single ## ## 1 1 1465. 2181203. 0.000823 45.5 0.386 ## 2 2 1579. 2182069. 0.250 45.5 0.363 ## 3 3 1685. 2404209. 0.351 45.5 0.357 ## 4 4 1749. 2481650. 0.407 45.5 0.349 ``` We see that the mean and variance of income are increasing over time, and the proportion of missing values is also increasing (probably due to dropouts in the study). The mean of the age variable does not change over time as we treat it as a time constant (i.e., the age at the start of the study). The proportion of singles is decreasing over time. We can also calculate similar statistics for different groups. For example, we can calculate the same statistics separately for people with and without degrees at each point in time. ``` usl |> group_by(wave, degree.fct) |> summarise(mean_income = mean(fimngrs, na.rm = T), var_income = var(fimngrs, na.rm = T), miss_income = mean(is.na(fimngrs))) ``` ``` ## # A tibble: 12 × 5 ## # Groups: wave [4] ## wave degree.fct mean_income var_income miss_income ## ## 1 1 Degree 2146. 3307885. 0.00127 ## 2 1 No degree 1137. 1309982. 0.000611 ## 3 1 1382. 1721212. 0 ## 4 2 Degree 2279. 3453524. 0.238 ## 5 2 No degree 1234. 1195328. 0.256 ## 6 2 1410. 1570990. 0.541 ## 7 3 Degree 2394. 3717992. 0.320 ## 8 3 No degree 1318. 1331952. 0.366 ## 9 3 1769. 1714929. 0.477 ## 10 4 Degree 2458. 3768458. 0.363 ## 11 4 No degree 1367. 1376334. 0.428 ## 12 4 1737. 1988781. 0.514 ``` We see that there is quite a large difference in the mean income between people with and without a degree. The variance of income is also higher for people with a degree. If we want to eliminate the cases that are missing on the grouping variable, we can first filter them out: ``` usl |> filter(!is.na(degree.fct)) |> group_by(wave, degree.fct) |> summarise(mean_income = mean(fimngrs, na.rm = T), var_income = var(fimngrs, na.rm = T), miss_income = mean(is.na(fimngrs))) ``` ``` ## # A tibble: 8 × 5 ## # Groups: wave [4] ## wave degree.fct mean_income var_income miss_income ## ## 1 1 Degree 2146. 3307885. 0.00127 ## 2 1 No degree 1137. 1309982. 0.000611 ## 3 2 Degree 2279. 3453524. 0.238 ## 4 2 No degree 1234. 1195328. 0.256 ## 5 3 Degree 2394. 3717992. 0.320 ## 6 3 No degree 1318. 1331952. 0.366 ## 7 4 Degree 2458. 3768458. 0.363 ## 8 4 No degree 1367. 1376334. 0.428 ``` ## Transition tables and correlation matrices There are two other types of tables that can be useful for longitudinal data exploration: **transition tables** and **correlation matrices**. These show the likelihood of people changing over time, which is often one of the main reasons we are interested in longitudinal studies. ### Correlation matrices For example, we can calculate the **correlation matrix** for the income over time using the [wide data](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/). We first select only the variables of interest (using `select()`), then do a correlation (using `cor()` with pairwise deletion), and round the results to two decimal points (using `round()`): ``` usw |> select(matches("fimngrs.cap")) |> cor(use = "pairwise.complete.obs") |> round(2) ``` ``` ## fimngrs.cap_1 fimngrs.cap_2 fimngrs.cap_3 fimngrs.cap_4 ## fimngrs.cap_1 1.00 0.78 0.73 0.70 ## fimngrs.cap_2 0.78 1.00 0.62 0.67 ## fimngrs.cap_3 0.73 0.62 1.00 0.73 ## fimngrs.cap_4 0.70 0.67 0.73 1.00 ``` The correlation between income in wave 1 and wave 2 is 0.78. This is a high positive correlation, implying that people with high income in wave 1 are also likely to have high income in wave 2. As time passes, the correlation becomes weaker, and this process often takes place in longitudinal data as more change can happen with the passing of time. ### Transition tables When we are interested in the transition between two categorical variables, we can use **transition tables**. For example, we can calculate the transition table for the voting variable “vote6.fct” from wave 1 to wave 2. There are different ways to do this. A simple one would be just using the `count()` function: ``` usw |> count(vote6.fct_1, vote6.fct_2) ``` ``` ## # A tibble: 25 × 3 ## vote6.fct_1 vote6.fct_2 n ## ## 1 Very Very 2171 ## 2 Very Fairly 1194 ## 3 Very Not very 171 ## 4 Very Not at all 95 ## 5 Very 1317 ## 6 Fairly Very 1187 ## 7 Fairly Fairly 7565 ## 8 Fairly Not very 2434 ## 9 Fairly Not at all 800 ## 10 Fairly 4121 ## # ℹ 15 more rows ``` This has the information we need but it is not very easy to read as it is in the “long format” with each possible combination presented on a different row. We can use the `spread()` function to make it more readable: ``` usw |> count(vote6.fct_1, vote6.fct_2) |> spread(vote6.fct_2, n) ``` ``` ## # A tibble: 5 × 6 ## vote6.fct_1 Very Fairly `Not very` `Not at all` `` ## ## 1 Very 2171 1194 171 95 1317 ## 2 Fairly 1187 7565 2434 800 4121 ## 3 Not very 195 2592 4804 2569 3808 ## 4 Not at all 117 806 2223 5280 4094 ## 5 154 575 529 590 28768 ``` *Note that the first input for the `spread()` command is the variable that should be spread (“vote6.fct\_2” here), and the second is the “value” (in this case “n”).* This is more in line with the way transition tables are typically presented. Here, we see that around 2,100 people are very likely to vote in both waves, and around 95 people switched from very likely to not at all likely. Using **absolute frequency** (i.e., just the number of cases in each cell) is not always the best way to present transition tables, as it is hard to compare transition likelihoods for different categories. We can instead calculate the **proportion** of cases in each cell. Usually, doing this by row (i.e., for each category in wave 1) is the most intuitive to read. We can do this by first calculating the total number of cases in each row and then dividing the number of cases in each cell by this total. We can do this using the `group_by()` and `mutate()` functions: ``` usw |> count(vote6.fct_1, vote6.fct_2) |> group_by(vote6.fct_1) |> mutate(prop = round(n / sum(n), 2)) |> select(-n) |> spread(vote6.fct_2, prop) ``` ``` ## # A tibble: 5 × 6 ## # Groups: vote6.fct_1 [5] ## vote6.fct_1 Very Fairly `Not very` `Not at all` `` ## ## 1 Very 0.44 0.24 0.03 0.02 0.27 ## 2 Fairly 0.07 0.47 0.15 0.05 0.26 ## 3 Not very 0.01 0.19 0.34 0.18 0.27 ## 4 Not at all 0.01 0.06 0.18 0.42 0.33 ## 5 0.01 0.02 0.02 0.02 0.94 ``` We see that around 47% of people who were “Fairly” likely to vote in wave 1 are also “Fairly” likely to vote in wave 2, while around 5% switched to “Not at all” likely. The diagonal shows the proportion of people who stayed in the same category, which is also known as stability, while the off-diagonal elements show the **change**. An alternative way to do this is with the commands `table()` and `prop.table()`. These functions calculate the proportion of cases in each cell of the table. We can use it like this: ``` table(usw$vote6.fct_1, usw$vote6.fct_2, useNA = "always") |> prop.table(margin = 1) |> round(2) ``` ``` ## ## Very Fairly Not very Not at all ## Very 0.44 0.24 0.03 0.02 0.27 ## Fairly 0.07 0.47 0.15 0.05 0.26 ## Not very 0.01 0.19 0.34 0.18 0.27 ## Not at all 0.01 0.06 0.18 0.42 0.33 ## 0.01 0.02 0.02 0.02 0.94 ``` *Note that `margin = 1` calculates the proportions by row.* This gives us the same result as before. Which strategy to use depends mostly on personal preferences. ## Describing relationships over time Another type of descriptive analysis that we might want to perform using longitudinal data is examining how relationships between variables change over time. Let’s imagine we are interested in the relationship between gender and voting behaviour. We can calculate a simple table to explore this over all the waves of the data: ``` usl |> count(vote6.fct, gndr.fct) ``` ``` ## # A tibble: 10 × 3 ## vote6.fct gndr.fct n ## ## 1 Very Male 8858 ## 2 Very Female 5780 ## 3 Fairly Male 23674 ## 4 Fairly Female 25689 ## 5 Not very Male 16497 ## 6 Not very Female 24585 ## 7 Not at all Male 13478 ## 8 Not at all Female 24558 ## 9 Male 29857 ## 10 Female 31052 ``` Let’s use a similar strategy as before and make this in the wide format using proportions by gender to make it easier to understand: ``` usl |> count(vote6.fct, gndr.fct) |> group_by(gndr.fct) |> mutate(prop = round(n / sum(n), 2)) |> select(-n) |> spread(vote6.fct, prop) ``` ``` ## # A tibble: 2 × 6 ## # Groups: gndr.fct [2] ## gndr.fct Very Fairly `Not very` `Not at all` `` ## ## 1 Male 0.1 0.26 0.18 0.15 0.32 ## 2 Female 0.05 0.23 0.22 0.22 0.28 ``` We see that males are more likely to vote, with around 36% saying they are “Very” or “Fairly” likely to vote compared to around 28% for females. Let’s now look at how this relationship changes over time. We can do this by adding the `wave` variable to the `count()` and `group_by()` functions: ``` usl |> count(wave, vote6.fct, gndr.fct) |> na.omit() |> group_by(wave, gndr.fct) |> mutate(prop = round(n / sum(n), 2)) |> select(-n) |> spread(vote6.fct, prop) ``` ``` ## # A tibble: 8 × 6 ## # Groups: wave, gndr.fct [8] ## wave gndr.fct Very Fairly `Not very` `Not at all` ## ## 1 1 Male 0.15 0.38 0.26 0.21 ## 2 1 Female 0.07 0.31 0.32 0.3 ## 3 2 Male 0.15 0.38 0.26 0.21 ## 4 2 Female 0.07 0.33 0.3 0.29 ## 5 3 Male 0.13 0.38 0.27 0.22 ## 6 3 Female 0.07 0.32 0.3 0.31 ## 7 4 Male 0.13 0.38 0.26 0.22 ## 8 4 Female 0.07 0.32 0.3 0.31 ``` *Note that we used `na.omit()`* to ignore the missing category and make the table easier to read. The same goes for *the `round()` command.* Now, we can explore how this relationship changed over time. For example in wave 1 the difference between men and women in the “Very” likely to vote category is around 8% while in wave 4 it is around 6%. We see that this is mostly because of a decrease in the likelihood of male voting. We can also look at the relationship between a categorical and a continuous variable and how this changes over time. For example, we can calculate the mean satisfaction for each degree level over time (using `summarise()`). We eliminate the missing category (using `na.omit()`) and reshape the table to wide (using `spread()`) to make it easier to read: ``` usl |> group_by(wave, degree.fct) |> summarise(mean_sati = mean(sati, na.rm = T) |> round(2)) |> na.omit() |> spread(degree.fct, mean_sati) ``` ``` ## # A tibble: 4 × 3 ## # Groups: wave [4] ## wave Degree `No degree` ## ## 1 1 5.34 5.2 ## 2 2 5.32 5.16 ## 3 3 5.22 5.06 ## 4 4 5.15 4.97 ``` We see that people with degrees are more satisfied with their lives than people without degrees. This difference increases slightly over time. Finally, we can examine the relationship between two continuous variables and how this changes over time. For example, we can calculate the correlation between income and satisfaction over time using some of the commands we covered already: ``` usl |> group_by(wave) |> summarise(mean_income = mean(fimngrs.cap, na.rm = T), mean_sati = mean(sati, na.rm = T), cor = cor(fimngrs.cap, sati, use = "pairwise.complete.obs")) |> mutate_at(vars(-wave), ~round(., 2)) ``` ``` ## # A tibble: 4 × 4 ## wave mean_income mean_sati cor ## ## 1 1 1460. 5.25 0.05 ## 2 2 1574. 5.21 0.04 ## 3 3 1677. 5.11 0.05 ## 4 4 1741. 5.04 0.05 ``` *Note that we round all the variables except “wave” using `mutate_at()`.* We see that the correlation between income and satisfaction is very low and positive, around 0.05. This means that higher-income people are not necessarily more likely to be satisfied with their life. We also see that this relationship is pretty stable over time. ## Exporting tables We covered the main types of tables and summary statistics that are useful for longitudinal data. There are two main strategies for exporting the tables from `R`. The first one is to save the tables to a file, like a `.csv` or excel format. We can save our tables as an object and write it to a file using the `write_csv()` function: ``` tab1 <- usl |> group_by(wave) |> summarise(mean_income = mean(fimngrs.cap, na.rm = T), mean_sati = mean(sati, na.rm = T), cor = cor(fimngrs.cap, sati, use = "pairwise.complete.obs")) write_csv(tab1, "usl_summary.csv") ``` The second strategy is to create **dynamic documents** that include the tables we want in a nice format. In `R` we can create such documents using [`Rmarkdown`](https://rmarkdown.rstudio.com/) or [`Quarto`](https://quarto.org/) documents. The tables we created above can be easily included in these documents. For example, we can use the `kable()` function from the `knitr` package to create a table in markdown format. This is useful if you are writing using this format: ``` library(knitr) tab2 <- usl |> group_by(wave) |> summarise(mean_income = mean(fimngrs.cap, na.rm = T), mean_sati = mean(sati, na.rm = T), cor = cor(fimngrs.cap, sati, use = "pairwise.complete.obs")) |> mutate_at(vars(-wave), ~round(., 2)) kable(tab2) ``` | wave | mean\_income | mean\_sati | cor | |---|---|---|---| | 1 | 1459.88 | 5.25 | 0.05 | | 2 | 1573.74 | 5.21 | 0.04 | | 3 | 1677.22 | 5.11 | 0.05 | | 4 | 1741.10 | 5.04 | 0.05 | The `kable()` command can adapt to the type of output you want. For example, if you are writing a `LaTeX` document, you can use the `format = "latex"` argument to get a table in `LaTeX` format. ``` kable(tab2, format = "latex") ``` ``` \begin{tabular}{l|r|r|r} \hline wave & mean\_income & mean\_sati & cor\\ \hline 1 & 1459.88 & 5.25 & 0.05\\ \hline 2 & 1573.74 & 5.21 & 0.04\\ \hline 3 & 1677.22 & 5.11 & 0.05\\ \hline 4 & 1741.10 & 5.04 & 0.05\\ \hline \end{tabular} ``` The same with HTML: ``` kable(tab2, format = "html") ``` ```
wave mean_income mean_sati cor
1 1459.88 5.25 0.05
2 1573.74 5.21 0.04
3 1677.22 5.11 0.05
4 1741.10 5.04 0.05
``` ![Data exploration of longitudinal data using R with tables and summaries.](https://longitudinalanalysis.com/wp-content/uploads/2024/03/long_process_describe-221x300.png) ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions Longitudinal data can be complex and difficult to understand. Describing this data is an important part of the longitudinal workflow. In this blog post, we covered the most common tables and summary statistics needed for longitudinal data using `base R` and `tidyverse`. We also saw how we can export these tables to files or reports. This is part of the Data Exploration stage of longitudinal data analysis and visualization. You can see some of the main commands we covered in the figure on the right. There are other specialized packages for creating tables in `R` like [`kableExtra`](https://bookdown.org/yihui/rmarkdown-cookbook/kableextra.html) or [`gt`](https://gt.rstudio.com/) that can help you create more complex tables, and they work well with dynamic documents. You can find a list of some of these packages [here](https://bookdown.org/yihui/rmarkdown-cookbook/table-other.html). Try creating some of these tables in your own data. Are there other types of tables or descriptives we missed? Let us know in the comments below. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data cleaning, data management, descriptive statistics, longitudinal data analysis, r, summaries, tables --- ### [How to include time-varying predictors in Latent Growth Models (LGM) in R](https://longitudinalanalysis.com/how-to-include-time-varying-predictors-in-latent-growth-models-lgm-in-r/) **Published:** November 4, 2024 **Author:** Alex Cernat **Excerpt:** This post explores how to incorporate time-varying predictors into Latent Growth Models (LGM) to analyse changes in variables over time. It discusses data preparation, using R code for modeling, and differentiating between concurrent and lagged effects. **Content:** ![](https://longitudinalanalysis.com/wp-content/plugins/jetpack/images/lock-paywall.svg) ## Subscribe to continue reading Subscribe to get access to the rest of this post and other subscriber-only content. Type your email… Subscribe [Already a subscriber?](https://subscribe.wordpress.com/memberships/jwt/?site_id=228879393&redirect_url=https%3A%2F%2Flongitudinalanalysis.com%2Fwp-json%2Fjetpack%2Fv4%2Fsubscribers%2Fauth%3Fredirect_url%3Dhttps%253A%252F%252Flongitudinalanalysis.com%252Fwp-cron.php%253Fdoing_wp_cron%253D1795437944.2557749748229980468750) **Categories:** data management, longitudinal data analysis **Tags:** data management, latent growth modelling, longitudinal data analysis, r, structural equation modelling --- ### [How to include control variables in a cross-lagged panel model](https://longitudinalanalysis.com/how-to-include-control-variables-in-a-cross-lagged-panel-model/) **Published:** March 3, 2025 **Author:** Alex Cernat **Excerpt:** Learn how to include control variables in a Cross-Lagged Panel Model (CLPM) in R, using time-constant and time-varying predictors to refine causal analysis. **Content:** The [cross-lagged panel model](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) (CLPM) is a powerful tool for studying reciprocal relationships over time, helping researchers disentangle causality in longitudinal data. If you’re new to CLPM, check out [this post](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/), where we introduce the model and explain its core assumptions. While [CLPM](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) accounts for temporal dependencies through autoregressive and cross-lagged paths, it does not inherently control for potential confounders that might bias these effects. To address this, we can include control variables—either [time-constant](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (e.g., demographic factors) or [time-varying](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) (e.g., changing life circumstances)—to improve the model’s validity. This post explores ways to include control variables in a CLPM using `lavaan` in R. ## Preparing the data We will use the wide version of the Understanding Society data (“usw”) to explore the different types of trajectories in satisfaction (more on how to prepare the data in [this previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/)). Here, mental and physical health are measured using the SF12 scale and calculated to take values between 0 and 100, with higher values indicating higher health levels. We will use the `lavaan` package to run the models and `tidyverse` to clean up some data. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! We start by loading the package (we assume they have already been installed). ``` library(lavaan) library(tidyverse) ``` We then load the cleaned data from the “data” subfolder in our working directory: ``` load("./data/us_clean_syn.RData") ``` Sometimes, centering variables (subtracting the mean from the variable) helps with interpretation and estimation. We can do this for the mental and physical health variables using the `mutate_at()` function from the `dplyr` package. First, we select just the variables of interest, and then we subtract the mean from each variable. ``` usw <- usw %>% mutate_at(vars(starts_with("sf12"), -matches("lag|dev|ind")), list("test" = ~ . - mean(., na.rm = T))) glimpse(usw) ``` ``` ## Rows: 51,007 ## Columns: 105 ## $ pidp 5, 6, 7, 10, 11, 13, 14, 16, 18, 19, 21, 22, 23, 24, 25… ## $ age 28, 80, 60, 42, 53, 51, 38, 27, 56, 31, 46, 30, 47… ## $ hiqual 1, 9, 3, 1, 1, 9, 4, 5, 2, 9, 1, 1, 9, 4, 1, 3, 3,… ## $ gndr.fct Male, Male, Male, Male, Male, Female, Female, Male, Mal… ## $ degree.fct Degree, No degree, No degree, Degree, Degree, No degree… ## $ sati.ind 3.000000, 5.000000, 2.000000, 5.000000, 4.666667, 4.000… ## $ sf12pcs.ind 57.65250, 48.82667, 33.18000, 57.22500, 56.16667, 50.69… ## $ sf12mcs.ind 52.75250, 42.96333, 46.80000, 49.26500, 52.78000, 38.30… ## $ waves 4, 4, 1, 2, 4, 4, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 3, 4, 1… ## $ single_1 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1,… ## $ single_2 1, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, … ## $ single_3 1, 0, NA, 0, 0, 0, 0, 1, 1, NA, 0, 0, 1, NA, 1, 1,… ## $ single_4 0, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, … ## $ fimngrs_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13, 68… ## $ fimngrs_2 4002.50, 709.00, NA, NA, 4010.01, 280.17, 1308.33, 1549… ## $ fimngrs_3 3616.67, 702.00, NA, 336.58, 2751.66, 666.67, 1000.00, … ## $ fimngrs_4 850.50, 829.15, NA, NA, 4322.68, 423.58, 988.01, 777.28… ## $ sclfsato_1 -9, 6, 2, -9, -7, 3, 5, 6, -9, -9, 6, 3, 5, 3, 7, … ## $ sclfsato_2 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1, 7, 6, … ## $ sclfsato_3 2, -8, NA, 5, 6, -8, 3, 6, 3, NA, 6, 6, 3, NA, 6, … ## $ sclfsato_4 1, 3, NA, NA, 2, 6, 5, 5, 5, -7, 6, 4, 6, 4, 6, 7,… ## $ sf12pcs_1 54.51, 53.93, 33.18, 58.30, NA, 46.66, 49.93, 30.75, 31… ## $ sf12pcs_2 62.98, 46.39, NA, NA, 54.80, 62.65, 56.10, 50.45, 12.41… ## $ sf12pcs_3 56.97, NA, NA, 56.15, 57.28, NA, 58.05, 58.57, 43.98, N… ## $ sf12pcs_4 56.15, 46.16, NA, NA, 56.42, 42.78, 56.40, 52.24, 42.52… ## $ sf12mcs_1 55.73, 46.48, 46.80, 49.41, NA, 37.17, 56.10, 45.20, 49… ## $ sf12mcs_2 36.22, 45.39, NA, NA, 54.37, 31.34, 57.16, 58.47, 52.93… ## $ sf12mcs_3 60.02, NA, NA, 49.12, 49.52, NA, 57.16, 55.17, 54.20, N… ## $ sf12mcs_4 59.04, 37.02, NA, NA, 54.45, 46.40, 60.02, 52.40, 36.56… ## $ istrtdaty_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 20… ## $ istrtdaty_2 2010, 2011, NA, NA, 2011, 2010, 2011, 2011, 2011, … ## $ istrtdaty_3 2011, 2012, NA, 2012, 2012, 2011, 2012, 2012, 2012… ## $ istrtdaty_4 2012, 2013, NA, NA, 2013, 2012, 2013, 2013, 2014, … ## $ sf1_1 2, 4, 5, 2, 3, 5, 3, 2, 3, 2, 2, 2, 4, 3, 2, 4, 2,… ## $ sf1_2 2, 3, NA, NA, 2, 3, 2, 3, 5, 3, 3, 2, 5, 2, 4, 3, … ## $ sf1_3 1, 3, NA, 2, 3, 3, 2, 3, 3, NA, 2, 2, 4, NA, 3, 3,… ## $ sf1_4 3, 3, NA, NA, 2, 4, 2, 3, 4, 3, 2, 2, 4, 2, 4, 3, … ## $ present_1 TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, T… ## $ present_2 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,… ## $ present_3 TRUE, TRUE, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA,… ## $ present_4 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,… ## $ single.fct_1 Single, In relationship, Single, In relationship, In re… ## $ single.fct_2 Single, In relationship, NA, NA, In relationship, In re… ## $ single.fct_3 Single, In relationship, NA, In relationship, In relati… ## $ single.fct_4 In relationship, In relationship, NA, NA, In relationsh… ## $ urban.fct_1 Urban, Urban, Urban, Urban, Urban, Urban, Urban, Urban,… ## $ urban.fct_2 Urban, Urban, NA, NA, Urban, Urban, Urban, Urban, Urban… ## $ urban.fct_3 Urban, Urban, NA, Urban, Urban, Urban, Urban, Urban, Ur… ## $ urban.fct_4 Urban, Urban, NA, NA, Urban, Urban, Urban, Urban, Urban… ## $ vote6.fct_1 Not very, Not at all, Fairly, Very, NA, Not very, Not v… ## $ vote6.fct_2 Not at all, Not at all, NA, NA, Fairly, Not at all, Not… ## $ vote6.fct_3 Not at all, Not at all, NA, Not very, Not very, Not at … ## $ vote6.fct_4 Not at all, Not very, NA, NA, Very, Not at all, Not at … ## $ sati_1 NA, 6, 2, NA, NA, 3, 5, 6, NA, NA, 6, 3, 5, 3, 7, 6, NA… ## $ sati_2 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1, 7, 6, NA, 7… ## $ sati_3 2, NA, NA, 5, 6, NA, 3, 6, 3, NA, 6, 6, 3, NA, 6, 6, NA… ## $ sati_4 1, 3, NA, NA, 2, 6, 5, 5, 5, NA, 6, 4, 6, 4, 6, 7, 5, 7… ## $ sati.fct_1 NA, Mostly satisfied, Mostly dissatisfied, NA, NA, Some… ## $ sati.fct_2 Mostly satisfied, Mostly satisfied, NA, NA, Mostly sati… ## $ sati.fct_3 Mostly dissatisfied, NA, NA, Somewhat satisfied, Mostly… ## $ sati.fct_4 Completely dissatisfied, Somewhat dissatisfied, NA, NA,… ## $ fimngrs.cap_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13, 68… ## $ fimngrs.cap_2 4002.50, 709.00, NA, NA, 4010.01, 280.17, 1308.33, 1549… ## $ fimngrs.cap_3 3616.67, 702.00, NA, 336.58, 2751.66, 666.67, 1000.00, … ## $ fimngrs.cap_4 850.50, 829.15, NA, NA, 4322.68, 423.58, 988.01, 777.28… ## $ logincome_1 8.099818, 6.809039, 7.291881, 7.981621, 8.370147, 7.030… ## $ logincome_2 8.297170, 6.577861, NA, NA, 8.299040, 5.670467, 7.18412… ## $ logincome_3 8.196070, 6.568078, NA, 5.848114, 7.923587, 6.517184, 6… ## $ logincome_4 6.757514, 6.732390, NA, NA, 8.373942, 6.072076, 6.90576… ## $ year_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 2010, 2… ## $ year_2 2010, 2011, NA, NA, 2011, 2010, 2011, 2011, 2011, 2011,… ## $ year_3 2011, 2012, NA, 2012, 2012, 2011, 2012, 2012, 2012, NA,… ## $ year_4 2012, 2013, NA, NA, 2013, 2012, 2013, 2013, 2014, 2013,… ## $ sati.dev_1 NA, 1.0000000, 0.0000000, NA, NA, -1.0000000, 0.5000000… ## $ sati.dev_2 3.0000000, 1.0000000, NA, NA, 1.3333333, -1.0000000, 0.… ## $ sati.dev_3 -1.000000, NA, NA, 0.000000, 1.333333, NA, -1.500000, 0… ## $ sati.dev_4 -2.0000000, -2.0000000, NA, NA, -2.6666667, 2.0000000, … ## $ sf12pcs.dev_1 -3.1425000, 5.1033333, 0.0000000, 1.0750000, NA, -4.036… ## $ sf12pcs.dev_2 5.327500, -2.436667, NA, NA, -1.366667, 11.953333, 0.98… ## $ sf12pcs.dev_3 -0.682500, NA, NA, -1.075000, 1.113333, NA, 2.930000, 1… ## $ sf12pcs.dev_4 -1.5025000, -2.6666667, NA, NA, 0.2533333, -7.9166667, … ## $ sf12mcs.dev_1 2.977500, 3.516667, 0.000000, 0.145000, NA, -1.133333, … ## $ sf12mcs.dev_2 -16.532500, 2.426667, NA, NA, 1.590000, -6.963333, -0.4… ## $ sf12mcs.dev_3 7.2675, NA, NA, -0.1450, -3.2600, NA, -0.4500, 2.3600, … ## $ sf12mcs.dev_4 6.2875000, -5.9433333, NA, NA, 1.6700000, 8.0966667, 2.… ## $ sati.lag_1 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… ## $ sati.lag_2 NA, 6, 2, NA, NA, 3, 5, 6, NA, NA, 6, 3, 5, 3, 7, 6, NA… ## $ sati.lag_3 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1, 7, 6, NA, 7… ## $ sati.lag_4 2, NA, NA, 5, 6, NA, 3, 6, 3, NA, 6, 6, 3, NA, 6, 6, NA… ## $ sf12pcs.lag_1 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… ## $ sf12pcs.lag_2 54.51, 53.93, 33.18, 58.30, NA, 46.66, 49.93, 30.75, 31… ## $ sf12pcs.lag_3 62.98, 46.39, NA, NA, 54.80, 62.65, 56.10, 50.45, 12.41… ## $ sf12pcs.lag_4 56.97, NA, NA, 56.15, 57.28, NA, 58.05, 58.57, 43.98, N… ## $ sf12mcs.lag_1 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,… ## $ sf12mcs.lag_2 55.73, 46.48, 46.80, 49.41, NA, 37.17, 56.10, 45.20, 49… ## $ sf12mcs.lag_3 36.22, 45.39, NA, NA, 54.37, 31.34, 57.16, 58.47, 52.93… ## $ sf12mcs.lag_4 60.02, NA, NA, 49.12, 49.52, NA, 57.16, 55.17, 54.20, N… ## $ sf12pcs_1_test 5.0158871, 4.4358871, -16.3141129, 8.8058871, NA, -2.83… ## $ sf12pcs_2_test 13.2249899, -3.3650101, NA, NA, 5.0449899, 12.8949899, … ## $ sf12pcs_3_test 7.226404, NA, NA, 6.406404, 7.536404, NA, 8.306404, 8.8… ## $ sf12pcs_4_test 6.5042404, -3.4857596, NA, NA, 6.7742404, -6.8657596, 6… ## $ sf12mcs_1_test 5.29055, -3.95945, -3.63945, -1.02945, NA, -13.26945, 5… ## $ sf12mcs_2_test -13.615662, -4.445662, NA, NA, 4.534338, -18.495662, 7.… ## $ sf12mcs_3_test 10.62854251, NA, NA, -0.27145749, 0.12854251, NA, 7.768… ## $ sf12mcs_4_test 9.550426, -12.469574, NA, NA, 4.960426, -3.089574, 10.5… ``` This will create new variables with the suffix “\_test” centered around the mean. We can rename the variables to make them easier to work with. This can be quickly done using the `rename_at()` function from the `dplyr` package. We select the variables with the suffix “\_test” and remove the suffix using the `str_remove_all()` function from the `stringr` package. ``` usw <- usw %>% rename_at(vars(ends_with("test")), ~str_remove_all(., "sf12|_test")) glimpse(usw) ``` ``` ## Rows: 51,007 ## Columns: 105 ## $ pidp 5, 6, 7, 10, 11, 13, 14, 16, 18, 19, 21, 22, 23, 24, 25,… ## $ age 28, 80, 60, 42, 53, 51, 38, 27, 56, 31, 46, 30, 47,… ## $ hiqual 1, 9, 3, 1, 1, 9, 4, 5, 2, 9, 1, 1, 9, 4, 1, 3, 3, … ## $ gndr.fct Male, Male, Male, Male, Male, Female, Female, Male, Male… ## $ degree.fct Degree, No degree, No degree, Degree, Degree, No degree,… ## $ sati.ind 3.000000, 5.000000, 2.000000, 5.000000, 4.666667, 4.0000… ## $ sf12pcs.ind 57.65250, 48.82667, 33.18000, 57.22500, 56.16667, 50.696… ## $ sf12mcs.ind 52.75250, 42.96333, 46.80000, 49.26500, 52.78000, 38.303… ## $ waves 4, 4, 1, 2, 4, 4, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 3, 4, 1,… ## $ single_1 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, … ## $ single_2 1, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, N… ## $ single_3 1, 0, NA, 0, 0, 0, 0, 1, 1, NA, 0, 0, 1, NA, 1, 1, … ## $ single_4 0, 0, NA, NA, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1… ## $ fimngrs_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13, 682… ## $ fimngrs_2 4002.50, 709.00, NA, NA, 4010.01, 280.17, 1308.33, 1549.… ## $ fimngrs_3 3616.67, 702.00, NA, 336.58, 2751.66, 666.67, 1000.00, 5… ## $ fimngrs_4 850.50, 829.15, NA, NA, 4322.68, 423.58, 988.01, 777.28,… ## $ sclfsato_1 -9, 6, 2, -9, -7, 3, 5, 6, -9, -9, 6, 3, 5, 3, 7, 6… ## $ sclfsato_2 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1, 7, 6, N… ## $ sclfsato_3 2, -8, NA, 5, 6, -8, 3, 6, 3, NA, 6, 6, 3, NA, 6, 6… ## $ sclfsato_4 1, 3, NA, NA, 2, 6, 5, 5, 5, -7, 6, 4, 6, 4, 6, 7, … ## $ sf12pcs_1 54.51, 53.93, 33.18, 58.30, NA, 46.66, 49.93, 30.75, 31.… ## $ sf12pcs_2 62.98, 46.39, NA, NA, 54.80, 62.65, 56.10, 50.45, 12.41,… ## $ sf12pcs_3 56.97, NA, NA, 56.15, 57.28, NA, 58.05, 58.57, 43.98, NA… ## $ sf12pcs_4 56.15, 46.16, NA, NA, 56.42, 42.78, 56.40, 52.24, 42.52,… ## $ sf12mcs_1 55.73, 46.48, 46.80, 49.41, NA, 37.17, 56.10, 45.20, 49.… ## $ sf12mcs_2 36.22, 45.39, NA, NA, 54.37, 31.34, 57.16, 58.47, 52.93,… ## $ sf12mcs_3 60.02, NA, NA, 49.12, 49.52, NA, 57.16, 55.17, 54.20, NA… ## $ sf12mcs_4 59.04, 37.02, NA, NA, 54.45, 46.40, 60.02, 52.40, 36.56,… ## $ istrtdaty_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 201… ## $ istrtdaty_2 2010, 2011, NA, NA, 2011, 2010, 2011, 2011, 2011, 2… ## $ istrtdaty_3 2011, 2012, NA, 2012, 2012, 2011, 2012, 2012, 2012,… ## $ istrtdaty_4 2012, 2013, NA, NA, 2013, 2012, 2013, 2013, 2014, 2… ## $ sf1_1 2, 4, 5, 2, 3, 5, 3, 2, 3, 2, 2, 2, 4, 3, 2, 4, 2, … ## $ sf1_2 2, 3, NA, NA, 2, 3, 2, 3, 5, 3, 3, 2, 5, 2, 4, 3, N… ## $ sf1_3 1, 3, NA, 2, 3, 3, 2, 3, 3, NA, 2, 2, 4, NA, 3, 3, … ## $ sf1_4 3, 3, NA, NA, 2, 4, 2, 3, 4, 3, 2, 2, 4, 2, 4, 3, 3… ## $ present_1 TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TR… ## $ present_2 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, … ## $ present_3 TRUE, TRUE, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, … ## $ present_4 TRUE, TRUE, NA, NA, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, … ## $ single.fct_1 Single, In relationship, Single, In relationship, In rel… ## $ single.fct_2 Single, In relationship, NA, NA, In relationship, In rel… ## $ single.fct_3 Single, In relationship, NA, In relationship, In relatio… ## $ single.fct_4 In relationship, In relationship, NA, NA, In relationshi… ## $ urban.fct_1 Urban, Urban, Urban, Urban, Urban, Urban, Urban, Urban, … ## $ urban.fct_2 Urban, Urban, NA, NA, Urban, Urban, Urban, Urban, Urban,… ## $ urban.fct_3 Urban, Urban, NA, Urban, Urban, Urban, Urban, Urban, Urb… ## $ urban.fct_4 Urban, Urban, NA, NA, Urban, Urban, Urban, Urban, Urban,… ## $ vote6.fct_1 Not very, Not at all, Fairly, Very, NA, Not very, Not ve… ## $ vote6.fct_2 Not at all, Not at all, NA, NA, Fairly, Not at all, Not … ## $ vote6.fct_3 Not at all, Not at all, NA, Not very, Not very, Not at a… ## $ vote6.fct_4 Not at all, Not very, NA, NA, Very, Not at all, Not at a… ## $ sati_1 NA, 6, 2, NA, NA, 3, 5, 6, NA, NA, 6, 3, 5, 3, 7, 6, NA,… ## $ sati_2 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1, 7, 6, NA, 7,… ## $ sati_3 2, NA, NA, 5, 6, NA, 3, 6, 3, NA, 6, 6, 3, NA, 6, 6, NA,… ## $ sati_4 1, 3, NA, NA, 2, 6, 5, 5, 5, NA, 6, 4, 6, 4, 6, 7, 5, 7,… ## $ sati.fct_1 NA, Mostly satisfied, Mostly dissatisfied, NA, NA, Somew… ## $ sati.fct_2 Mostly satisfied, Mostly satisfied, NA, NA, Mostly satis… ## $ sati.fct_3 Mostly dissatisfied, NA, NA, Somewhat satisfied, Mostly … ## $ sati.fct_4 Completely dissatisfied, Somewhat dissatisfied, NA, NA, … ## $ fimngrs.cap_1 3283.87, 896.00, 1458.33, 2916.67, 4306.27, 1121.13, 682… ## $ fimngrs.cap_2 4002.50, 709.00, NA, NA, 4010.01, 280.17, 1308.33, 1549.… ## $ fimngrs.cap_3 3616.67, 702.00, NA, 336.58, 2751.66, 666.67, 1000.00, 5… ## $ fimngrs.cap_4 850.50, 829.15, NA, NA, 4322.68, 423.58, 988.01, 777.28,… ## $ logincome_1 8.099818, 6.809039, 7.291881, 7.981621, 8.370147, 7.0309… ## $ logincome_2 8.297170, 6.577861, NA, NA, 8.299040, 5.670467, 7.184121… ## $ logincome_3 8.196070, 6.568078, NA, 5.848114, 7.923587, 6.517184, 6.… ## $ logincome_4 6.757514, 6.732390, NA, NA, 8.373942, 6.072076, 6.905763… ## $ year_1 2009, 2010, 2009, 2009, 2010, 2009, 2010, 2010, 2010, 20… ## $ year_2 2010, 2011, NA, NA, 2011, 2010, 2011, 2011, 2011, 2011, … ## $ year_3 2011, 2012, NA, 2012, 2012, 2011, 2012, 2012, 2012, NA, … ## $ year_4 2012, 2013, NA, NA, 2013, 2012, 2013, 2013, 2014, 2013, … ## $ sati.dev_1 NA, 1.0000000, 0.0000000, NA, NA, -1.0000000, 0.5000000,… ## $ sati.dev_2 3.0000000, 1.0000000, NA, NA, 1.3333333, -1.0000000, 0.5… ## $ sati.dev_3 -1.000000, NA, NA, 0.000000, 1.333333, NA, -1.500000, 0.… ## $ sati.dev_4 -2.0000000, -2.0000000, NA, NA, -2.6666667, 2.0000000, 0… ## $ sf12pcs.dev_1 -3.1425000, 5.1033333, 0.0000000, 1.0750000, NA, -4.0366… ## $ sf12pcs.dev_2 5.327500, -2.436667, NA, NA, -1.366667, 11.953333, 0.980… ## $ sf12pcs.dev_3 -0.682500, NA, NA, -1.075000, 1.113333, NA, 2.930000, 10… ## $ sf12pcs.dev_4 -1.5025000, -2.6666667, NA, NA, 0.2533333, -7.9166667, 1… ## $ sf12mcs.dev_1 2.977500, 3.516667, 0.000000, 0.145000, NA, -1.133333, -… ## $ sf12mcs.dev_2 -16.532500, 2.426667, NA, NA, 1.590000, -6.963333, -0.45… ## $ sf12mcs.dev_3 7.2675, NA, NA, -0.1450, -3.2600, NA, -0.4500, 2.3600, 5… ## $ sf12mcs.dev_4 6.2875000, -5.9433333, NA, NA, 1.6700000, 8.0966667, 2.4… ## $ sati.lag_1 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, … ## $ sati.lag_2 NA, 6, 2, NA, NA, 3, 5, 6, NA, NA, 6, 3, 5, 3, 7, 6, NA,… ## $ sati.lag_3 6, 6, NA, NA, 6, 3, 5, 6, 5, 5, 4, 6, 6, 1, 7, 6, NA, 7,… ## $ sati.lag_4 2, NA, NA, 5, 6, NA, 3, 6, 3, NA, 6, 6, 3, NA, 6, 6, NA,… ## $ sf12pcs.lag_1 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, … ## $ sf12pcs.lag_2 54.51, 53.93, 33.18, 58.30, NA, 46.66, 49.93, 30.75, 31.… ## $ sf12pcs.lag_3 62.98, 46.39, NA, NA, 54.80, 62.65, 56.10, 50.45, 12.41,… ## $ sf12pcs.lag_4 56.97, NA, NA, 56.15, 57.28, NA, 58.05, 58.57, 43.98, NA… ## $ sf12mcs.lag_1 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, … ## $ sf12mcs.lag_2 55.73, 46.48, 46.80, 49.41, NA, 37.17, 56.10, 45.20, 49.… ## $ sf12mcs.lag_3 36.22, 45.39, NA, NA, 54.37, 31.34, 57.16, 58.47, 52.93,… ## $ sf12mcs.lag_4 60.02, NA, NA, 49.12, 49.52, NA, 57.16, 55.17, 54.20, NA… ## $ pcs_1 5.0158871, 4.4358871, -16.3141129, 8.8058871, NA, -2.834… ## $ pcs_2 13.2249899, -3.3650101, NA, NA, 5.0449899, 12.8949899, 6… ## $ pcs_3 7.226404, NA, NA, 6.406404, 7.536404, NA, 8.306404, 8.82… ## $ pcs_4 6.5042404, -3.4857596, NA, NA, 6.7742404, -6.8657596, 6.… ## $ mcs_1 5.29055, -3.95945, -3.63945, -1.02945, NA, -13.26945, 5.… ## $ mcs_2 -13.615662, -4.445662, NA, NA, 4.534338, -18.495662, 7.3… ## $ mcs_3 10.62854251, NA, NA, -0.27145749, 0.12854251, NA, 7.7685… ## $ mcs_4 9.550426, -12.469574, NA, NA, 4.960426, -3.089574, 10.53… ``` ## Including time-constant controls in the cross-lagged panel model Although the model partially controls for possible confounders by including the auto-regressive estimates and the time-specific correlations, it is still possible that some confounders might explain or bias the cross-lagged effects. If we believe that to be the case and have measurements of the confounders, we can include them in the model. If the confounders are time constant, they can be included in the model by explaining one or all of the variables present. Such a model, with one time constant confounder, could be presented in this way: ![cross-lagged panel model with time constant predictor](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-1024x764.png) *Note that we excluded the correlations to simplify the graph (they should still be estimated). Also, because we are now explaining the variables of interest at wave 1, they also have residuals there.* We can see how we would do this in practice by including some time constant predictors in the model discussed in our [previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/) that investigated the causal direction of physical and mental health. Here, we include gender and age at the start of the study as predictors. ``` model <- 'pcs_1 ~ 1 + gndr.fct + age pcs_2 ~ 1 + pcs_1 + mcs_1 + gndr.fct + age pcs_3 ~ 1 + pcs_2 + mcs_2 + gndr.fct + age mcs_1 ~ 1 + gndr.fct + age mcs_2 ~ 1 + mcs_1 + pcs_1 + gndr.fct + age mcs_3 ~ 1 + mcs_2 + pcs_2 + gndr.fct + age pcs_1 ~~ mcs_1 pcs_2 ~~ mcs_2 pcs_3 ~~ mcs_3' m2 <- sem(model, data = usw, missing = "ML") summary(m2) ``` ``` ## lavaan 0.6-19 ended normally after 149 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 35 ## ## Number of observations 51007 ## Number of missing patterns 8 ## ## Model Test User Model: ## ## Test statistic 4554.969 ## Degrees of freedom 4 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Observed ## Observed information based on Hessian ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) ## pcs_1 ~ ## gndr.fct -0.920 0.097 -9.450 0.000 ## age -0.253 0.003 -94.255 0.000 ## pcs_2 ~ ## pcs_1 0.527 0.005 106.287 0.000 ## mcs_1 0.124 0.005 23.432 0.000 ## gndr.fct 0.120 0.103 1.173 0.241 ## age -0.131 0.003 -41.535 0.000 ## pcs_3 ~ ## pcs_2 0.496 0.006 87.409 0.000 ## mcs_2 0.095 0.006 15.181 0.000 ## gndr.fct -0.363 0.110 -3.287 0.001 ## age -0.121 0.003 -34.764 0.000 ## mcs_1 ~ ## gndr.fct -1.701 0.093 -18.248 0.000 ## age 0.030 0.003 11.775 0.000 ## mcs_2 ~ ## mcs_1 0.278 0.006 49.037 0.000 ## pcs_1 0.067 0.005 12.404 0.000 ## gndr.fct -0.598 0.111 -5.401 0.000 ## age 0.051 0.003 15.189 0.000 ## mcs_3 ~ ## mcs_2 0.438 0.006 73.566 0.000 ## pcs_2 0.117 0.006 20.634 0.000 ## gndr.fct -0.606 0.106 -5.694 0.000 ## age 0.078 0.003 23.181 0.000 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 ~~ ## .mcs_1 2.939 0.489 6.015 0.000 ## .pcs_2 ~~ ## .mcs_2 -8.202 0.479 -17.136 0.000 ## .pcs_3 ~~ ## .mcs_3 -13.047 0.478 -27.271 0.000 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 12.974 0.202 64.243 0.000 ## .pcs_2 5.488 0.226 24.265 0.000 ## .pcs_3 6.082 0.247 24.671 0.000 ## .mcs_1 1.263 0.193 6.530 0.000 ## .mcs_2 -1.724 0.244 -7.072 0.000 ## .mcs_3 -2.679 0.238 -11.243 0.000 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 111.220 0.723 153.830 0.000 ## .pcs_2 73.304 0.625 117.281 0.000 ## .pcs_3 77.019 0.692 111.340 0.000 ## .mcs_1 101.596 0.660 153.972 0.000 ## .mcs_2 85.485 0.727 117.572 0.000 ## .mcs_3 71.654 0.648 110.581 0.000 ``` The interpretation is similar to a standard regression. For example, females have lower levels of physical health in wave 1 than males (by **-0.920**). This is also true for older respondents. With an increase in age by 1, we expect a decrease in physical health in wave 1 of **0.253**. The interpretation of the intercept is also similar to that in a regression. Our primary interest is still in the cross-lagged effects. As such, it is interesting to investigate if the coefficients have changed with the inclusion of the new variables. We see that the impact of mental health on physical health from wave 1 to 2 is now **0.124**, while the opposite cross-lagged effect is **0.067**. The difference between the two appears slightly larger after including the controls compared to our original model (in [this post](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/)). ## Including time-varying controls in the cross-lagged panel model We can also include time-varying predictors in the model as controls. These can be included in a few different ways, but if we expect concurrent effects, we could build a model similar to this one: ![cross-lagged panel model with time varying predictor](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-1-1024x637.png) We can look at an example where we include being “single” and “logincome” as controls. As an illustration, let’s assume that the effects are concurrent (as in the graph above), and a change in each wave for these variables will lead to an immediate change in health. The model in `lavaan` would look like this: ``` model <- 'pcs_1 ~ 1 + single_1 + logincome_1 pcs_2 ~ 1 + pcs_1 + mcs_1 + single_2 + logincome_2 pcs_3 ~ 1 + pcs_2 + mcs_2 + single_3 + logincome_3 mcs_1 ~ 1 + single_1 + logincome_1 mcs_2 ~ 1 + mcs_1 + pcs_1 + single_2 + logincome_2 mcs_3 ~ 1 + mcs_2 + pcs_2 + single_3 + logincome_3 pcs_1 ~~ mcs_1 pcs_2 ~~ mcs_2 pcs_3 ~~ mcs_3' m3 <- sem(model, data = usw, missing = "ML") summary(m3) ``` ``` ## lavaan 0.6-19 ended normally after 156 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 35 ## ## Used Total ## Number of observations 30813 51007 ## Number of missing patterns 8 ## ## Model Test User Model: ## ## Test statistic 5156.575 ## Degrees of freedom 28 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Observed ## Observed information based on Hessian ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) ## pcs_1 ~ ## single_1 -0.883 0.139 -6.351 0.000 ## logincome_1 0.441 0.046 9.582 0.000 ## pcs_2 ~ ## pcs_1 0.603 0.005 116.994 0.000 ## mcs_1 0.098 0.006 16.622 0.000 ## single_2 -0.410 0.119 -3.435 0.001 ## logincome_2 0.271 0.045 6.047 0.000 ## pcs_3 ~ ## pcs_2 0.564 0.005 102.717 0.000 ## mcs_2 0.077 0.006 11.892 0.000 ## single_3 -0.362 0.122 -2.961 0.003 ## logincome_3 0.291 0.048 6.024 0.000 ## mcs_1 ~ ## single_1 -1.549 0.122 -12.744 0.000 ## logincome_1 0.229 0.040 5.692 0.000 ## mcs_2 ~ ## mcs_1 0.292 0.006 46.638 0.000 ## pcs_1 0.025 0.006 4.585 0.000 ## single_2 -0.621 0.127 -4.892 0.000 ## logincome_2 0.319 0.048 6.702 0.000 ## mcs_3 ~ ## mcs_2 0.447 0.006 73.608 0.000 ## pcs_2 0.064 0.005 11.823 0.000 ## single_3 -0.552 0.116 -4.766 0.000 ## logincome_3 0.168 0.046 3.669 0.000 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 ~~ ## .mcs_1 0.944 0.654 1.443 0.149 ## .pcs_2 ~~ ## .mcs_2 -11.055 0.533 -20.751 0.000 ## .pcs_3 ~~ ## .mcs_3 -15.347 0.512 -29.992 0.000 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 -2.671 0.328 -8.151 0.000 ## .pcs_2 -2.026 0.323 -6.270 0.000 ## .pcs_3 -2.052 0.349 -5.878 0.000 ## .mcs_1 -0.759 0.287 -2.646 0.008 ## .mcs_2 -2.178 0.343 -6.342 0.000 ## .mcs_3 -0.939 0.331 -2.838 0.005 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 128.305 1.060 121.005 0.000 ## .pcs_2 75.378 0.704 107.098 0.000 ## .pcs_3 80.935 0.746 108.427 0.000 ## .mcs_1 97.618 0.806 121.155 0.000 ## .mcs_2 84.986 0.793 107.204 0.000 ## .mcs_3 73.466 0.677 108.441 0.000 ``` The results show that being single tends to decrease mental and physical health, while income seems to have a positive effect. Again, the cross-lagged effects are slightly different to what we saw before. When including time-varying predictors, it is important to consider if the effects are concurrent or lagged. So far, we assumed that being single and income immediately affected health. If we think there is a lag effect, or if we are concerned about reverse causality (e.g., health is impacting income and not the other way around), we can consider using lagged effects. The simplest version of this would be a lag of one (e.g., income in wave 1 impacting health in wave 2). We can easily include more prolonged lag effects if we have good reasons. Let’s explore the previous model using a lag of 1 instead of concurrent effects. ``` model <- 'pcs_2 ~ 1 + pcs_1 + mcs_1 + single_1 + logincome_1 pcs_3 ~ 1 + pcs_2 + mcs_2 + single_2 + logincome_2 mcs_2 ~ 1 + mcs_1 + pcs_1 + single_1 + logincome_1 mcs_3 ~ 1 + mcs_2 + pcs_2 + single_2 + logincome_2 pcs_1 ~~ mcs_1 pcs_2 ~~ mcs_2 pcs_3 ~~ mcs_3' m4 <- sem(model, data = usw, missing = "ML") summary(m4) ``` ``` ## lavaan 0.6-19 ended normally after 153 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 31 ## ## Used Total ## Number of observations 38213 51007 ## Number of missing patterns 8 ## ## Model Test User Model: ## ## Test statistic 5392.873 ## Degrees of freedom 20 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Observed ## Observed information based on Hessian ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) ## pcs_2 ~ ## pcs_1 0.600 0.005 126.199 0.000 ## mcs_1 0.099 0.005 18.260 0.000 ## single_1 -0.268 0.111 -2.407 0.016 ## logincome_1 0.280 0.037 7.656 0.000 ## pcs_3 ~ ## pcs_2 0.564 0.005 103.001 0.000 ## mcs_2 0.077 0.006 11.910 0.000 ## single_2 -0.236 0.122 -1.932 0.053 ## logincome_2 0.256 0.046 5.534 0.000 ## mcs_2 ~ ## mcs_1 0.283 0.006 49.535 0.000 ## pcs_1 0.032 0.005 6.316 0.000 ## single_1 -0.735 0.117 -6.285 0.000 ## logincome_1 0.170 0.038 4.426 0.000 ## mcs_3 ~ ## mcs_2 0.447 0.006 73.742 0.000 ## pcs_2 0.064 0.005 11.851 0.000 ## single_2 -0.685 0.116 -5.915 0.000 ## logincome_2 0.109 0.044 2.478 0.013 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) ## pcs_1 ~~ ## mcs_1 1.104 0.609 1.814 0.070 ## .pcs_2 ~~ ## .mcs_2 -10.218 0.497 -20.545 0.000 ## .pcs_3 ~~ ## .mcs_3 -15.371 0.512 -30.046 0.000 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) ## .pcs_2 -2.188 0.262 -8.355 0.000 ## .pcs_3 -1.823 0.334 -5.466 0.000 ## .mcs_2 -1.131 0.275 -4.108 0.000 ## .mcs_3 -0.466 0.316 -1.475 0.140 ## pcs_1 -0.112 0.060 -1.854 0.064 ## mcs_1 0.129 0.053 2.430 0.015 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_2 77.862 0.665 117.111 0.000 ## .pcs_3 80.886 0.746 108.389 0.000 ## .mcs_2 86.147 0.734 117.360 0.000 ## .mcs_3 73.437 0.677 108.432 0.000 ## pcs_1 131.612 0.981 134.180 0.000 ## mcs_1 101.265 0.754 134.331 0.000 ``` The results differ from those in the previous model. For example, the effect of being single on physical health in wave 2 is now **-0.268** (compared to **-0.410** in the previous model). There are also some small differences in the cross-lagged coefficients. The decision to include concurrent or lagged effects should be based on theoretical considerations. If we believe the effects are immediate, we should include them concurrently. On the other hand, if we are not sure about the causal direction or think some time needs to pass to see an effect, we should include the predictors as a lagged effect. ## Mixing time-constant and time-varying controls Of course, the model can be expanded to include a combination of time-varying and time-constant predictors. As an example, we combine the previous models to include sex and age at the start of the study, the concurrent effect of single and the lagged effect of income. ``` model <- 'pcs_1 ~ 1 + single_1 + gndr.fct + age pcs_2 ~ 1 + pcs_1 + mcs_1 + single_2 + logincome_1 + gndr.fct + age pcs_3 ~ 1 + pcs_2 + mcs_2 + single_3 + logincome_2 + gndr.fct + age mcs_1 ~ 1 + single_1 + gndr.fct + age mcs_2 ~ 1 + mcs_1 + pcs_1 + single_2 + logincome_1 + gndr.fct + age mcs_3 ~ 1 + mcs_2 + pcs_2 + single_3 + logincome_2 + gndr.fct + age pcs_1 ~~ mcs_1 pcs_2 ~~ mcs_2 pcs_3 ~~ mcs_3' m5 <- sem(model, data = usw, missing = "ML") summary(m5) ``` ``` ## lavaan 0.6-19 ended normally after 213 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 45 ## ## Used Total ## Number of observations 30829 51007 ## Number of missing patterns 8 ## ## Model Test User Model: ## ## Test statistic 4862.544 ## Degrees of freedom 24 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Observed ## Observed information based on Hessian ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) ## pcs_1 ~ ## single_1 -2.128 0.129 -16.508 0.000 ## gndr.fct -0.729 0.124 -5.900 0.000 ## age -0.247 0.004 -70.163 0.000 ## pcs_2 ~ ## pcs_1 0.515 0.005 95.490 0.000 ## mcs_1 0.120 0.006 20.870 0.000 ## single_2 -0.951 0.117 -8.113 0.000 ## logincome_1 0.546 0.040 13.826 0.000 ## gndr.fct 0.451 0.111 4.056 0.000 ## age -0.143 0.003 -41.399 0.000 ## pcs_3 ~ ## pcs_2 0.481 0.006 81.687 0.000 ## mcs_2 0.093 0.006 14.547 0.000 ## single_3 -0.882 0.120 -7.360 0.000 ## logincome_2 0.447 0.046 9.775 0.000 ## gndr.fct -0.158 0.115 -1.379 0.168 ## age -0.133 0.004 -36.534 0.000 ## mcs_1 ~ ## single_1 -1.370 0.121 -11.322 0.000 ## gndr.fct -1.584 0.116 -13.651 0.000 ## age 0.036 0.003 10.879 0.000 ## mcs_2 ~ ## mcs_1 0.282 0.006 44.897 0.000 ## pcs_1 0.058 0.006 9.829 0.000 ## single_2 -0.390 0.128 -3.043 0.002 ## logincome_1 0.075 0.043 1.745 0.081 ## gndr.fct -0.574 0.122 -4.720 0.000 ## age 0.052 0.004 13.640 0.000 ## mcs_3 ~ ## mcs_2 0.436 0.006 71.997 0.000 ## pcs_2 0.116 0.006 19.819 0.000 ## single_3 -0.197 0.116 -1.699 0.089 ## logincome_2 -0.047 0.044 -1.064 0.287 ## gndr.fct -0.607 0.111 -5.482 0.000 ## age 0.081 0.004 23.016 0.000 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 ~~ ## .mcs_1 3.580 0.603 5.935 0.000 ## .pcs_2 ~~ ## .mcs_2 -9.061 0.511 -17.743 0.000 ## .pcs_3 ~~ ## .mcs_3 -12.949 0.489 -26.483 0.000 ## ## Intercepts: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 13.600 0.270 50.385 0.000 ## .pcs_2 2.388 0.369 6.474 0.000 ## .pcs_3 3.524 0.417 8.458 0.000 ## .mcs_1 1.498 0.254 5.906 0.000 ## .mcs_2 -2.100 0.403 -5.208 0.000 ## .mcs_3 -2.409 0.403 -5.983 0.000 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) ## .pcs_1 110.139 0.910 121.012 0.000 ## .pcs_2 70.143 0.656 106.928 0.000 ## .pcs_3 77.155 0.706 109.341 0.000 ## .mcs_1 96.728 0.798 121.178 0.000 ## .mcs_2 84.291 0.786 107.234 0.000 ## .mcs_3 71.906 0.662 108.544 0.000 ``` Our primary interest in these models is still the cross-lagged effects (now after including the controls). We see that the impact of mental health on physical health from wave 1 to 2 is **0.120**, while the opposite cross-lagged effect is **0.058**. From wave 2 to wave 3, the effects are **0.093** and **0.116**. We see the direction is slightly different once we include the controls. As a next step, we can test if these differences are significant as we covered in [this post](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusion In this post, we have seen how to include control variables in a cross-lagged panel model. We have also explored how to include time-constant and time-varying predictors and discussed the issue of concurrent and lagged effects. The decision to include control variables (and how to do so) should be based on careful theoretical considerations. The model can be further extended to include separate within- and between-variation (also known as a Random Effect Cross-Lagged Panel Model). You can read more about it [here](https://pure.uva.nl/ws/files/2688454/168970_Hamaker_Kuiper_Grasman_2015_A_Critique_of_Cross_Lagged_Panel_Model.pdf). In a future post, we will explore how to estimate such a model. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management, longitudinal data analysis **Tags:** data management, longitudinal data analysis, r, structural equation modelling --- ### [How to present results from longitudinal analysis](https://longitudinalanalysis.com/how-to-present-results-from-longitudinal-analysis/) **Published:** May 30, 2025 **Author:** Alex Cernat **Excerpt:** Learn how to present results from longitudinal data analysis using R Markdown, stargazer, texreg, and visualization tools like tidySEM and semPlot. **Content:** Presenting results effectively is a crucial step in longitudinal data analysis. Traditionally this was done separately from the analysis by copying and pasting outputs. In this section, we will explore several tools and techniques to present results from longitudinal data analysis. These tools can be used together with [dynamic documents](https://longitudinalanalysis.com/using-dynamic-documents-to-present-results-in-r/) to create a [fully reproducible workflow](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/). ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Presenting results from regression based models To show how this can work, let’s begin by fitting several linear mixed models using the `lme4` package. These models examine how the mental component score (“sf12mcs”) changes over time and how it varies by sex: ``` library(lme4) m0 <- lmer(data = usl, sf12mcs ~ 1 + (1 | pidp)) m1 <- lmer(data = usl, sf12mcs ~ 1 + wave0 + (1 | pidp)) m3 <- lmer(data = usl, sf12mcs ~ 1 + wave0 + gndr.fct + (1 + wave0 | pidp)) m4 <- lmer(data = usl, sf12mcs ~ 1 + wave0 + gndr.fct + gndr.fct:wave0 + (1 + wave0 | pidp)) ``` These models incrementally build complexity, starting with a random intercept model (`m0`) and progressing to include time (“wave0”), gender (“gndr.fct”), and their interaction (`m4`). The `stargazer` package is an excellent tool for creating publication-quality tables summarizing regression results. By default, `stargazer` produces concise summaries of model coefficients and key statistics: ``` library(stargazer) stargazer(list(m0, m1, m3, m4), type = "text", title = "Regression Results") ``` ``` ## ## Regression Results ## ======================================================================== ## Dependent variable: ## --------------------------------------------------- ## sf12mcs ## (1) (2) (3) (4) ## ------------------------------------------------------------------------ ## wave0 -0.419*** -0.419*** -0.551*** ## (0.020) (0.022) (0.033) ## ## gndr.fctFemale -1.373*** -1.635*** ## (0.071) (0.086) ## ## wave0:gndr.fctFemale 0.236*** ## (0.044) ## ## Constant 49.813*** 50.285*** 51.054*** 51.201*** ## (0.035) (0.042) (0.059) (0.065) ## ## ------------------------------------------------------------------------ ## Observations 127,989 127,989 127,989 127,989 ## Log Likelihood -468,160.100 -467,954.300 -467,570.900 -467,558.600 ## Akaike Inf. Crit. 936,326.300 935,916.700 935,155.800 935,133.300 ## Bayesian Inf. Crit. 936,355.600 935,955.700 935,224.200 935,211.400 ## ======================================================================== ## Note: *p<0.1; **p<0.05; ***p<0.01 ``` This command generates a basic summary of the models, including fixed effects, random effects, and standard errors. The option `type` can be adjusted for pdf (`type = "latex"`) or HTML (`type = "html"`) and can be combined with dynamic documents, such as RMarkdown. While informative, the default table format can be further improved, with most of the table being editable. For example, to make the table more accessible, we can customize variable names, add column labels, and format output: ``` stargazer( m0, m1, m3, m4, type = "html", dep.var.labels = "Mental Component Score (MCS)", column.labels = c("Intercept Only", "Wave Effect", "Wave + Gender", "Wave x Gender Interaction"), covariate.labels = c("(Intercept)", "Wave", "Female", "Wave x Female"), omit.stat = c("LL", "ser", "f"), digits = 3, title = "Linear Mixed Models for MCS", align = TRUE ) ``` | | |---| | | *Dependent variable:* | | | | | | Mental Component Score (MCS) | | | Intercept Only | Wave Effect | Wave + Gender | Wave x Gender Interaction | | | (1) | (2) | (3) | (4) | | | | (Intercept) | | -0.419\*\*\* | -0.419\*\*\* | -0.551\*\*\* | | | | (0.020) | (0.022) | (0.033) | | | | | | | | Wave | | | -1.373\*\*\* | -1.635\*\*\* | | | | | (0.071) | (0.086) | | | | | | | | Female | | | | 0.236\*\*\* | | | | | | (0.044) | | | | | | | | Wave x Female | 49.813\*\*\* | 50.285\*\*\* | 51.054\*\*\* | 51.201\*\*\* | | | (0.035) | (0.042) | (0.059) | (0.065) | | | | | | | | | | Observations | 127,989 | 127,989 | 127,989 | 127,989 | | Akaike Inf. Crit. | 936,326.300 | 935,916.700 | 935,155.800 | 935,133.300 | | Bayesian Inf. Crit. | 936,355.600 | 935,955.700 | 935,224.200 | 935,211.400 | | | | *Note:* | *p<0.1; **p<0.05;*** p<0.01 | An alternative package to this is `texreg`. This package can also be used to create tables from regression models. For example, if we want to present the results from these models we can use the following code: ``` library(texreg) htmlreg(list(m0, m1, m3, m4), custom.model.names = c("Intercept Only", "Wave Effect", "Wave + Gender", "Wave x Gender Interaction"), custom.coef.names = c("(Intercept)", "Wave", "Female", "Wave x Female")) ``` | | Intercept Only | Wave Effect | Wave + Gender | Wave x Gender Interaction | |---|---|---|---|---| | (Intercept) | 49.81\*\*\* | 50.29\*\*\* | 51.05\*\*\* | 51.20\*\*\* | | | (0.04) | (0.04) | (0.06) | (0.06) | | Wave | | -0.42\*\*\* | -0.42\*\*\* | -0.55\*\*\* | | | | (0.02) | (0.02) | (0.03) | | Female | | | -1.37\*\*\* | -1.64\*\*\* | | | | | (0.07) | (0.09) | | Wave x Female | | | | 0.24\*\*\* | | | | | | (0.04) | | AIC | 936326.27 | 935916.68 | 935155.85 | 935133.28 | | BIC | 936355.55 | 935955.72 | 935224.17 | 935211.35 | | Log Likelihood | -468160.14 | -467954.34 | -467570.92 | -467558.64 | | Num. obs. | 127989 | 127989 | 127989 | 127989 | | Num. groups: pidp | 48630 | 48630 | 48630 | 48630 | | Var: pidp (Intercept) | 32.98 | 33.23 | 39.18 | 39.17 | | Var: Residual | 64.63 | 64.23 | 59.12 | 59.12 | | Var: pidp wave0 | | | 3.02 | 3.01 | | Cov: pidp (Intercept) wave0 | | | -4.02 | -4.01 | | \*\*\*p < 0.001; \*\*p < 0.01; \*p < 0.05 | ### Extracting results from regression based models An alternative strategy to using such models is to extract the coefficients of interest from the models and create our own tables. A useful package for extracting coefficients from regression models are `broom` and `broom.mixed` (for mixture models). ``` library(broom.mixed) library(knitr) model_results <- tidy(m3, effects = "fixed") ``` Once we extract the information we can present it using a simple command such as `kable()`. ``` kable(model_results, caption = "Fixed Effects Results") ``` | effect | term | estimate | std.error | statistic | |---|---|---|---|---| | fixed | (Intercept) | 51.0536371 | 0.0585164 | 872.46663 | | fixed | wave0 | -0.4187922 | 0.0217197 | -19.28169 | | fixed | gndr.fctFemale | -1.3729900 | 0.0712310 | -19.27518 | This could be further improved by cleaning the table, adding a caption and restricting the decimal points: ``` model_results |> select(-effect) |> setNames(c("Predictor", "Estimate", "SE", "t_value", "p_value")) |> kable(caption = "Fixed Effects Results", digits = 2) ``` | Predictor | Estimate | SE | t\_value | |---|---|---|---| | (Intercept) | 51.05 | 0.06 | 872.47 | | wave0 | -0.42 | 0.02 | -19.28 | | gndr.fctFemale | -1.37 | 0.07 | -19.28 | There are multiple packages that can be used to create tables from regression models, such as `gtsummary`, `flextable`, and `kableExtra`. Each package offers different features and customization options, so it’s worth exploring to find the one that best suits your needs. ## Presenting SEM-Based Models We also discussed using Structural Equation Modelling framework to analyse longitudinal data. Presenting SEM results tends to be more complicated as models can be complex and often researchers need to make decisions regarding what to present. Most of the packages mentioned above do not work in a straightforward way with SEM models. As a result, users often need to extract the model coefficients. Let’s look at an example. Imagine we run a Latent Growth Model and we want to present the results. ``` library(lavaan) model <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4' fit1 <- growth(model, data = usw) ``` ### Extracting fit indices Typically we want to extract both the goodness of fit indices as well as the key coefficients in the model. We can extract fit indices using the `fitmeasures()` command. Running the command leads to a large number of fit indices: ``` fitMeasures(fit1) ``` ``` ## npar fmin chisq ## 9.000 0.021 1102.403 ## df pvalue baseline.chisq ## 5.000 0.000 37441.623 ## baseline.df baseline.pvalue cfi ## 6.000 0.000 0.971 ## tli nnfi rfi ## 0.965 0.965 0.965 ## nfi pnfi ifi ## 0.971 0.809 0.971 ## rni logl unrestricted.logl ## 0.971 -159108.351 -158557.150 ## aic bic ntotal ## 318234.702 318308.412 26635.000 ## bic2 rmsea rmsea.ci.lower ## 318279.810 0.091 0.086 ## rmsea.ci.upper rmsea.ci.level rmsea.pvalue ## 0.095 0.900 0.000 ## rmsea.close.h0 rmsea.notclose.pvalue rmsea.notclose.h0 ## 0.050 1.000 0.080 ## rmr rmr_nomean srmr ## 0.086 0.100 0.054 ## srmr_bentler srmr_bentler_nomean crmr ## 0.054 0.062 0.034 ## crmr_nomean srmr_mplus srmr_mplus_nomean ## 0.041 0.110 0.052 ## cn_05 cn_01 gfi ## 268.473 365.497 0.999 ## agfi pgfi mfi ## 0.998 0.357 0.980 ## ecvi ## 0.042 ``` We can extract a subset of these indices to create a more concise summary table: ``` fit_select <- c("chisq", "df", "pvalue", "cfi", "rmsea", "aic", "bic") fitmeasures(fit1, fit_select) ``` ``` ## chisq df pvalue cfi rmsea aic bic ## 1102.403 5.000 0.000 0.971 0.091 318234.702 318308.412 ``` We can generalize this process to multiple models by using the `map_df()` command which loops our function and gathers the fit measures into a clean table: ``` model2 <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 logincome_1 ~~ a*logincome_1 logincome_2 ~~ a*logincome_2 logincome_3 ~~ a*logincome_3 logincome_4 ~~ a*logincome_4' fit2 <- growth(model2, data = usw) gof <- map_df(list(fit1, fit2), fitmeasures, fit_select) |> mutate(model = c("Model 1", "Model 2")) |> select(model, everything()) gof ``` ``` ## # A tibble: 2 × 8 ## model chisq df pvalue cfi rmsea aic bic ## ## 1 Model 1 1102.403 5 0 0.9706856 0.09077613 318234.7 318308.4 ## 2 Model 2 1420.270 8 0 0.9622747 0.08141184 318546.6 318595.7 ``` This table could then be presented in a dynamic report using a command such as `kable()` ``` gof |> setNames(str_to_title(names(gof))) |> kable(caption = "Fit Measures for Latent Growth Models", digits = 3) ``` | Model | Chisq | Df | Pvalue | Cfi | Rmsea | Aic | Bic | |---|---|---|---|---|---|---|---| | Model 1 | 1102.403 | 5 | 0 | 0.9706856 | 0.09077613 | 318234.7 | 318308.4 | | Model 2 | 1420.270 | 8 | 0 | 0.9622747 | 0.08141184 | 318546.6 | 318595.7 | Alternatively, we can use a package such as `tidySEM` to create a table with fit indices. This also works with multiple models: ``` library(tidySEM) table_fit(list(fit1, fit2)) |> kable(digits = 2) ``` | Name | Parameters | fmin | chisq | df | pvalue | baseline.chisq | baseline.df | baseline.pvalue | cfi | tli | nnfi | rfi | nfi | pnfi | ifi | rni | LL | unrestricted.logl | aic | bic | n | bic2 | rmsea | rmsea.ci.lower | rmsea.ci.upper | rmsea.ci.level | rmsea.pvalue | rmsea.close.h0 | rmsea.notclose.pvalue | rmsea.notclose.h0 | rmr | rmr\_nomean | srmr | srmr\_bentler | srmr\_bentler\_nomean | crmr | crmr\_nomean | srmr\_mplus | srmr\_mplus\_nomean | cn\_05 | cn\_01 | gfi | agfi | pgfi | mfi | ecvi | |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| | i | 9 | 0.02 | 1102.40 | 5 | 0 | 37441.62 | 6 | 0 | 0.97 | 0.96 | 0.96 | 0.96 | 0.97 | 0.81 | 0.97 | 0.97 | -159108.4 | -158557.1 | 318234.7 | 318308.4 | 26635 | 318279.8 | 0.09 | 0.09 | 0.10 | 0.9 | 0 | 0.05 | 1.00 | 0.08 | 0.09 | 0.10 | 0.05 | 0.05 | 0.06 | 0.03 | 0.04 | 0.11 | 0.05 | 268.47 | 365.50 | 1 | 1 | 0.36 | 0.98 | 0.04 | | i | 6 | 0.03 | 1420.27 | 8 | 0 | 37441.62 | 6 | 0 | 0.96 | 0.97 | 0.97 | NA | NA | 1.28 | 0.96 | 0.96 | -159267.3 | -158557.1 | 318546.6 | 318595.7 | 26635 | 318576.6 | 0.08 | 0.08 | 0.09 | 0.9 | 0 | 0.05 | 0.75 | 0.08 | 0.06 | 0.07 | 0.04 | 0.04 | 0.05 | 0.04 | 0.05 | 0.05 | 0.04 | 291.82 | 377.76 | 1 | 1 | 0.57 | 0.97 | 0.05 | ### Extracting model coefficients The other type of information we often want to extract are model coefficients, such as regression slopes and intercepts. When we have a complex model such as the one below we need to decide what are the key coefficients to present. ``` model3 <- 'i =~ 1*logincome_1 + 1*logincome_2 + 1*logincome_3 + 1*logincome_4 s =~ 0*logincome_1 + 1*logincome_2 + 2*logincome_3 + 3*logincome_4 i ~ gndr.fct + age s ~ gndr.fct + age' fit3 <- growth(model3, data = usw) ``` Coefficients can be extracted using the `parameterEstimates()` function. ``` parameterEstimates(fit3) ``` ``` ## lhs op rhs est se z pvalue ci.lower ci.upper ## 1 i =~ logincome_1 1.000 0.000 NA NA 1.000 1.000 ## 2 i =~ logincome_2 1.000 0.000 NA NA 1.000 1.000 ## 3 i =~ logincome_3 1.000 0.000 NA NA 1.000 1.000 ## 4 i =~ logincome_4 1.000 0.000 NA NA 1.000 1.000 ## 5 s =~ logincome_1 0.000 0.000 NA NA 0.000 0.000 ## 6 s =~ logincome_2 1.000 0.000 NA NA 1.000 1.000 ## 7 s =~ logincome_3 2.000 0.000 NA NA 2.000 2.000 ## 8 s =~ logincome_4 3.000 0.000 NA NA 3.000 3.000 ## 9 i ~ gndr.fct -0.380 0.017 -22.944 0.000 -0.412 -0.347 ## 10 i ~ age 0.010 0.000 20.761 0.000 0.009 0.011 ## 11 s ~ gndr.fct 0.001 0.006 0.166 0.868 -0.010 0.012 ## 12 s ~ age -0.003 0.000 -18.949 0.000 -0.003 -0.003 ## 13 logincome_1 ~~ logincome_1 0.505 0.011 45.998 0.000 0.483 0.526 ## 14 logincome_2 ~~ logincome_2 0.732 0.008 88.993 0.000 0.716 0.748 ## 15 logincome_3 ~~ logincome_3 0.703 0.008 92.653 0.000 0.688 0.718 ## 16 logincome_4 ~~ logincome_4 0.573 0.010 58.180 0.000 0.554 0.593 ## 17 i ~~ i 1.412 0.017 84.015 0.000 1.379 1.445 ## 18 s ~~ s 0.090 0.002 38.548 0.000 0.085 0.094 ## 19 i ~~ s -0.245 0.005 -46.828 0.000 -0.255 -0.235 ## 20 gndr.fct ~~ gndr.fct 0.246 0.000 NA NA 0.246 0.246 ## 21 gndr.fct ~~ age -0.172 0.000 NA NA -0.172 -0.172 ## 22 age ~~ age 297.013 0.000 NA NA 297.013 297.013 ## 23 logincome_1 ~1 0.000 0.000 NA NA 0.000 0.000 ## 24 logincome_2 ~1 0.000 0.000 NA NA 0.000 0.000 ## 25 logincome_3 ~1 0.000 0.000 NA NA 0.000 0.000 ## 26 logincome_4 ~1 0.000 0.000 NA NA 0.000 0.000 ## 27 gndr.fct ~1 1.559 0.000 NA NA 1.559 1.559 ## 28 age ~1 47.520 0.000 NA NA 47.520 47.520 ## 29 i ~1 6.916 0.036 194.030 0.000 6.846 6.986 ## 30 s ~1 0.230 0.012 19.332 0.000 0.207 0.253 ``` The variables “lhs”, “op” and “rhs” can be used to identify the type of coefficient presented. For example, values of “=~” indicate a regression coefficient, while values of “~1” indicate an intercept and “~” a regression coefficient. We can filter the table to extract only the coefficients of interest and present them in a clean table. We use the `spread()` command to create a wide table and the `setNames()` command to rename the columns. ``` parameterEstimates(fit3) |> filter(op == "~" | op == "~1") |> filter(lhs %in% c("i", "s")) |> mutate(rhs = str_to_title(rhs), rhs = ifelse(op == "~1", "Intercept", rhs), coef = str_c(round(est, 3), " (", round(se, 3), ")")) |> select(lhs, rhs, coef) |> spread(lhs, coef) |> setNames(c("Predictor", "Intercept", "Slope")) |> kable() ``` | Predictor | Intercept | Slope | |---|---|---| | Age | 0.01 (0) | -0.003 (0) | | Gndr.fct | -0.38 (0.017) | 0.001 (0.006) | | Intercept | 6.916 (0.036) | 0.23 (0.012) | We can also use the `table_results()` function from the `tidySEM` package to create a table with the coefficients: ``` table_results(fit3) |> kable() ``` | label | est\_sig | se | pval | confint | |---|---|---|---|---| | i.BY.logincome\_1 | 1.00 | 0.00 | NA | \[1.00, 1.00\] | | i.BY.logincome\_2 | 1.00 | 0.00 | NA | \[1.00, 1.00\] | | i.BY.logincome\_3 | 1.00 | 0.00 | NA | \[1.00, 1.00\] | | i.BY.logincome\_4 | 1.00 | 0.00 | NA | \[1.00, 1.00\] | | s.BY.logincome\_1 | 0.00 | 0.00 | NA | \[0.00, 0.00\] | | s.BY.logincome\_2 | 1.00 | 0.00 | NA | \[1.00, 1.00\] | | s.BY.logincome\_3 | 2.00 | 0.00 | NA | \[2.00, 2.00\] | | s.BY.logincome\_4 | 3.00 | 0.00 | NA | \[3.00, 3.00\] | | i.ON.gndr.fct | -0.38\*\*\* | 0.02 | 0.00 | \[-0.41, -0.35\] | | i.ON.age | 0.01\*\*\* | 0.00 | 0.00 | \[0.01, 0.01\] | | s.ON.gndr.fct | 0.00 | 0.01 | 0.87 | \[-0.01, 0.01\] | | s.ON.age | -0.00\*\*\* | 0.00 | 0.00 | \[-0.00, -0.00\] | | Variances.logincome\_1 | 0.50\*\*\* | 0.01 | 0.00 | \[0.48, 0.53\] | | Variances.logincome\_2 | 0.73\*\*\* | 0.01 | 0.00 | \[0.72, 0.75\] | | Variances.logincome\_3 | 0.70\*\*\* | 0.01 | 0.00 | \[0.69, 0.72\] | | Variances.logincome\_4 | 0.57\*\*\* | 0.01 | 0.00 | \[0.55, 0.59\] | | Variances.i | 1.41\*\*\* | 0.02 | 0.00 | \[1.38, 1.45\] | | Variances.s | 0.09\*\*\* | 0.00 | 0.00 | \[0.09, 0.09\] | | i.WITH.s | -0.25\*\*\* | 0.01 | 0.00 | \[-0.26, -0.23\] | | Variances.gndr.fct | 0.25 | 0.00 | NA | \[0.25, 0.25\] | | gndr.fct.WITH.age | -0.17 | 0.00 | NA | \[-0.17, -0.17\] | | Variances.age | 297.01 | 0.00 | NA | \[297.01, 297.01\] | | Means.logincome\_1 | 0.00 | 0.00 | NA | \[0.00, 0.00\] | | Means.logincome\_2 | 0.00 | 0.00 | NA | \[0.00, 0.00\] | | Means.logincome\_3 | 0.00 | 0.00 | NA | \[0.00, 0.00\] | | Means.logincome\_4 | 0.00 | 0.00 | NA | \[0.00, 0.00\] | | Means.gndr.fct | 1.56 | 0.00 | NA | \[1.56, 1.56\] | | Means.age | 47.52 | 0.00 | NA | \[47.52, 47.52\] | | Means.i | 6.92\*\*\* | 0.04 | 0.00 | \[6.85, 6.99\] | | Means.s | 0.23\*\*\* | 0.01 | 0.00 | \[0.21, 0.25\] | And again, with some cleaning it be presented in a nicer way ``` table_results(fit3) |> filter(str_detect(label, "Means.i|Means.s|ON")) |> kable() ``` | label | est\_sig | se | pval | confint | |---|---|---|---|---| | i.ON.gndr.fct | -0.38\*\*\* | 0.02 | 0.00 | \[-0.41, -0.35\] | | i.ON.age | 0.01\*\*\* | 0.00 | 0.00 | \[0.01, 0.01\] | | s.ON.gndr.fct | 0.00 | 0.01 | 0.87 | \[-0.01, 0.01\] | | s.ON.age | -0.00\*\*\* | 0.00 | 0.00 | \[-0.00, -0.00\] | | Means.i | 6.92\*\*\* | 0.04 | 0.00 | \[6.85, 6.99\] | | Means.s | 0.23\*\*\* | 0.01 | 0.00 | \[0.21, 0.25\] | ### Visualizing SEM models An alternative way to present results from SEM models is to use visualizations. Packages such as, `tidySEM`, `semPlot` and `lavaanPlot` can be used to create diagrams that show the model structure and estimated coefficients. For example, the `graph_sem()` function from the `tidySEM` package can be used to create a path diagram of the model: ``` graph_sem(fit3) ``` ![presenting results from latent growth models using the tidySEM package](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-6-1024x731.png) This could be further customized as discussed [here](https://cjvanlissa.github.io/tidySEM/articles/Plotting_graphs.html). Another option is to use the `semPlot` package to create diagrams that show model structure and estimated coefficients: ``` library(semPlot) semPaths(fit3) ``` ![presenting results from latent growth models using the semPlot package](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-5-1024x731.png) We can further enhance the graph by adding labels and changing the layout: ``` semPlot::semPaths( fit3, layout = "tree", sizeMan = 8, residuals = FALSE, rotation = 1, whatLabels = "est", nCharNodes = 5, normalize = TRUE, width = 12, height = 6 ) ``` ![presenting results from latent growth models using the semPlot package. Improved presentation](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-7-1024x731.png) You can also explore other packages, such as `lavaanPlot` to see which one fits best what you want to present. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions Presenting results from longitudinal data analysis is a critical step in the research process. By using tools like `stargazer`, `texreg`, `broom`, and `tidySEM`, you can create clear, concise tables that summarize your findings. These tables can be further customized to include variable names, column labels, and formatting options. Additionally, packages like `semPlot` and `lavaanPlot` can help you create visualizations that illustrate the structure of your models and the relationships between variables. By combining these approaches with dynamic documents (as discussed [here](https://longitudinalanalysis.com/using-dynamic-documents-to-present-results-in-r/)) and integrating them in reproducible workflows (as presented [here](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/)) you can create reports that are transparent, reproducible, and easy to share with others. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** communication **Tags:** communication, latent growth modelling, longitudinal data analysis, multilevel modeling, r, visualization --- ### [A Guide to Moderated Mediation and Mediated Moderation](https://longitudinalanalysis.com/a-guide-to-moderated-mediation-and-mediated-moderation/) **Published:** December 18, 2025 **Author:** Alex Cernat **Excerpt:** A practical guide to moderated mediation, explaining how indirect effects vary across contexts, with clear examples and applied modeling strategies. **Content:** Developing a better understanding of the processes we observe in the world around us often involves gaining insight into the causal pathways through which effects operate ([mediation](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/)) and the contexts or conditions under which these processes occur ([moderation](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/)). For example, education may improve health partly by increasing income, which in turn enables access to better living conditions and healthcare. This is an example of a mediated process. At the same time, the strength of the relationships may differ across groups ([moderation](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/)): the income gains associated with education may be larger for men than for women, or may translate into health improvements only at certain ages. Such complex processes can be described as **moderated mediation** or **mediated moderation**. In this guide, we will explore how to use multi-group structural equation modelling (SEM) in R to estimate and interpret concurrent processes of mediation and moderation. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## What are moderated mediation and mediated moderation? Moderated mediation refers to situations in which a mediation effect varies across contexts or cases. In other words, the question is not only if the effect of *X* on *Y* goes through a mediator, but also in what context does the effect appear (the mediator). Using the figure below as a guide, we can start with the basic mediated model (Panel A), where *X* affects *Y* partly through a mediator *M*. Panels B–D then introduce moderation at different stages of this process. For example, in **first-stage mediated moderation** (Panel B), the moderator Z changes the strength of the *X*–*M* relationship. This means that the indirect effect of *X* on *Y* via *M* depends on *Z*. Conceptually, *Z* does not act directly on the outcome, but instead shapes how strongly the mediator is activated by *X*. Similarly, in **second-stage mediated moderation** (Panel C), *Z* moderates the *M* to *Y* path, implying that the mediator matters more (or less) for specific values of *Z*. More complex cases (Panels D–H) allow moderation at multiple stages, including the direct effect, but the unifying idea remains the same: **the mediation process depends on a moderator**. ![visual representation of mediated moderation or moderated mediation](https://longitudinalanalysis.com/wp-content/uploads/2025/12/image-2-1024x1012.webp) Although the terms are often used interchangeably, they emphasise different starting points. **Mediated moderation** begins with a moderation effect and asks whether a mediator can explain that effect — that is, *what mechanism accounts for the interaction?* **Moderated mediation**, by contrast, begins with a mediation process and asks whether the indirect effect varies across levels of a moderator — that is, *for whom or under what conditions does the mediation operate?* Statistically, the models overlap, although conceptually the processes are different. When choosing between these two concepts, it is best to use theory and prior research to guide the interpretation’s focus. ## Estimating moderated mediation using path analysis In [a previous guide](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/), we saw that path analysis, or SEM, is an excellent framework for investigating mediation effects. We also [explored moderation](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/) using two strategies: interactions and multi-group analysis. Here, we will combine these ideas to estimate mediated moderation using multi-group SEM. To illustrate mediated moderation in practice, we estimate a simple mediation model to examine how the effect of education (degree) on mental health is mediated by income. We will also explore whether this mediation process differs by gender. Specifically, we will test whether the paths in the mediation model differ between men and women, indicating mediated moderation. The set-up of the mediation model is similar to the one [we discussed before](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/). We will also analyse this separately for men and women by adding the option `group = "gndr.fct"`. This will run the model separately for men and women: ``` library(lavaan) model <- 'sf12mcs_1 ~ degree.fct + logincome_1 logincome_1 ~ degree.fct' fit <- sem(model, data = usw, group = "gndr.fct") summary(fit, standardized = TRUE) ``` ``` ## Group 1 [Male]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree.fct -0.270 0.145 -1.860 0.063 -0.270 -0.013 ## logincome_1 0.338 0.043 7.869 0.000 0.338 0.056 ## logincome_1 ~ ## degree.fct -0.767 0.023 -33.636 0.000 -0.767 -0.227 ## ## Group 2 [Female]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree.fct -1.651 0.140 -11.825 0.000 -1.651 -0.074 ## logincome_1 -0.111 0.045 -2.491 0.013 -0.111 -0.016 ## logincome_1 ~ ## degree.fct -0.711 0.019 -38.136 0.000 -0.711 -0.228 ``` For both men and women, higher educational attainment is associated with lower income, and the magnitude of this relationship is very similar across groups. Where the models differ is in how income and education relate to mental health. Among men, income is positively associated with mental health, while the direct effect of education on mental health is close to zero. Among women, by contrast, income is weakly negatively related to mental health, and education has a substantially stronger direct negative association with mental health. Taken together, these patterns indicate that the overall effect of education on mental health differs by gender, not only in size but also in mechanism, with income acting as a positive mediator for men but not for women. To better understand the relationships we have found, we can put the results in a SEM diagram: ![example of mediated moderation or moderated mediation](https://longitudinalanalysis.com/wp-content/uploads/2025/12/image-1024x249.webp) *Note that I present the standardised coefficients (the last column in the output) because they are easier to compare across groups. Also, the grey arrow indicates a relationship that is not statistically significant.* ### Testing the differencess across groups Using this framework, we can also test whether the mediation process is the same for men and women by fitting constrained models that force certain paths to be equal across groups, and then comparing them to the unconstrained model. For example, let’s examine whether the effect of logincome on mental health is statistically significant across groups (second-stage moderation model). We will run a model where we restrict the coefficient to be equal by giving it the same label in both groups (`c(b, b)`): ``` model <- 'sf12mcs_1 ~ degree.fct + c(b, b)*logincome_1 logincome_1 ~ degree.fct' fit2 <- sem(model, data = usw, group = "gndr.fct") summary(fit2, standardized = TRUE) ``` ``` ## Group 1 [Male]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree.fct -0.436 0.143 -3.038 0.002 -0.436 -0.021 ## logincom_1 (b) 0.122 0.031 3.944 0.000 0.122 0.020 ## logincome_1 ~ ## degree.fct -0.767 0.023 -33.636 0.000 -0.767 -0.227 ## ## Group 2 [Female]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree.fct -1.485 0.138 -10.775 0.000 -1.485 -0.067 ## logincom_1 (b) 0.122 0.031 3.944 0.000 0.122 0.017 ## logincome_1 ~ ## degree.fct -0.711 0.019 -38.136 0.000 -0.711 -0.228 ``` In the output, we see that the unstandardized coefficient for logincome is 0.12 in both groups. To formally test whether this constraint decreases the model fit, we can compare the two models: ``` anova(fit, fit2) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## fit 0 524463 524586 0.000 ## fit2 1 524513 524627 52.511 52.511 0.046645 1 4.279e-13 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` AIC and BIC are both higher in the constrained model, indicating a worse fit. The chi-square difference test is also statistically significant, indicating that the restricted model fits significantly worse than the unconstrained model. This is an indication that moderated mediation is present in the data. We could test each relationship separately, or we could do an overall test to see if the entire mediation process differs by group (total effect moderation model, panel H in the figure above). Below, we expand the model, restrict all paths, and then compare the model with no restriction to the new one. ``` model <- 'sf12mcs_1 ~ c(c, c)*degree.fct + c(b, b)*logincome_1 logincome_1 ~ c(a, a)*degree.fct' fit3 <- sem(model, data = usw, group = "gndr.fct") anova(fit, fit3) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## fit 0 524463 524586 0.000 ## fit3 3 524542 524638 84.696 84.696 0.033915 3 < 2.2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` As expected, the overall test also shows that the constrained model fits significantly worse than the unconstrained one, again implying the presence of moderated mediation. ### Estimating indirect and total effects Finally, now that we know that the relationships are significantly different across groups, we can estimate group-specific indirect and total effects by labelling the paths separately for men and women: ``` model <- 'sf12mcs_1 ~ c(cm, cf)*degree.fct + c(bm, bf)*logincome_1 logincome_1 ~ c(am, af)*degree.fct # indirect effect (a*b) abm := am*bm abf := af*bf # total effect totalm := cm + (am*bm) totalf := cf + (af*bf)' fit <- sem(model, data = usw, group = "gndr.fct") summary(fit, standardized = TRUE) ``` ``` Defined Parameters: Estimate Std.Err z-value P(>|z|) Std.lv Std.all abm -0.260 0.034 -7.662 0.000 -0.260 -0.013 abf 0.079 0.032 2.485 0.013 0.079 0.004 totalm -0.530 0.142 -3.740 0.000 -0.530 -0.026 totalf -1.572 0.136 -11.560 0.000 -1.572 -0.071 ``` The results show a clear process of mediated moderation. For men, the indirect effect of education on mental health via income is negative and statistically significant, while for women, the indirect effect is positive but much smaller. The total effect of education on mental health is substantially more negative for women than for men, indicating that both the size and the mechanism of the effect differ across groups. ## Want to learn more? Check [our on-demand course on moderation and mediation](https://leanpub.com/c/mediation-moderation-r). [Explore course](https://leanpub.com/c/mediation-moderation-r) ## Using continuous variables for moderated mediation So far, we have used gender as a moderator by fitting the mediation model separately for men and women. The same idea works when the moderator is continuous. There are multiple ways to do this in practice; here, we turn age into three groups (young, middle, old), then fit a multi-group mediation model with age as the grouping variable. ``` # make three age groups usw <- usw |> mutate(age_grp = case_when( age < 35 ~ "young", age >= 35 & age < 55 ~ "middle", age >= 55 ~ "old" )) |> mutate(age_grp = factor(age_grp, levels = c("young", "middle", "old"))) ``` The mediation model will examine the effect of living in an urban area on satisfaction with life, with income as the mediating variable. The hypothesis is that the effect of urban residence on satisfaction is mediated by income and that the process varies by age. ``` model <- 'sati_1 ~ urban.fct_1 + logincome_1 logincome_1 ~ urban.fct_1' fit_sati <- sem(model, data = usw, group = "age_grp") summary(fit_sati, standardized = TRUE) ``` ``` ## Group 1 [young]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sati_1 ~ ## urban.fct_1 -0.081 0.035 -2.332 0.020 -0.081 -0.021 ## logincome_1 -0.022 0.007 -3.251 0.001 -0.022 -0.030 ## logincome_1 ~ ## urban.fct_1 -0.093 0.046 -1.995 0.046 -0.093 -0.018 ## ## Group 2 [old]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sati_1 ~ ## urban.fct_1 -0.070 0.029 -2.445 0.015 -0.070 -0.022 ## logincome_1 0.023 0.011 2.012 0.044 0.023 0.018 ## logincome_1 ~ ## urban.fct_1 -0.055 0.022 -2.441 0.015 -0.055 -0.022 ## ## Group 3 [middle]: ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sati_1 ~ ## urban.fct_1 -0.219 0.030 -7.207 0.000 -0.219 -0.059 ## logincome_1 0.081 0.010 8.431 0.000 0.081 0.069 ## logincome_1 ~ ## urban.fct_1 -0.023 0.026 -0.860 0.390 -0.023 -0.007 ``` Again, we can visualise the results to understand better the processes involved: ![example of mediated moderation or moderated mediation](https://longitudinalanalysis.com/wp-content/uploads/2025/12/image-1-1024x190.webp) In all three groups, urban residence is negatively associated with life satisfaction. Still, the magnitude of this direct effect varies substantially across the life course, being strongest among the middle-aged group. The role of income as a mediator also differs by age. For younger respondents, higher income is associated with slightly lower life satisfaction, whereas for older respondents, especially middle-aged respondents, income is positively related to satisfaction. At the same time, the association between urban residence and income is weak and statistically non-significant for the middle-aged group, indicating that income does not meaningfully mediate the urban–satisfaction relationship at midlife. Overall, the figure shows that age moderates both the direct and indirect pathways (i.e., moderated mediation), with the strength and even the direction of the mediation process changing across age groups. ### Testing differences across groups Based on these results, we could investigate further whether the mediation process differs statistically across age groups by fitting constrained models. We could do this for each path by including restrictions across two or three groups at a time. This would enable testing specific hypotheses. Here, to make things simple, we will do another overall test to see if the entire mediation process is the same across groups: ``` model <- 'sati_1 ~ c(c, c, c)*urban.fct_1 + c(b, b, b)*logincome_1 logincome_1 ~ c(a, a, a)*urban.fct_1' fit_sati2 <- sem(model, data = usw, group = "age_grp") anova(fit_sati, fit_sati2) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## fit_sati 0 278422 278602 0.000 ## fit_sati2 6 278504 278633 94.399 94.399 0.033495 6 < 2.2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` The results show that the constrained model fits significantly worse than the unconstrained model, indicating that the mediation process differs across age groups (i.e., moderated mediation). ### Calculating indirect and total effects across groups To better understand how the mediation process differs across groups, we can calculate the direct and indirect effects for each group: ``` model <- 'sati_1 ~ c(cy, co, cm)*urban.fct_1 + c(by, bo, bm)*logincome_1 logincome_1 ~ c(ay, ao, am)*urban.fct_1 # indirect effect (a*b) aby := ay*by abo := ao*bo abm := am*bm # total effect totaly := cy + (ay*by) totalo := co + (ao*bo) totalm := cm + (am*bm)' fit_sati <- sem(model, data = usw, group = "age_grp") ``` ``` Defined Parameters: Estimate Std.Err z-value P(>|z|) Std.lv Std.all aby 0.002 0.001 1.700 0.089 0.002 0.001 abo -0.001 0.001 -1.553 0.121 -0.001 -0.000 abm -0.002 0.002 -0.855 0.392 -0.002 -0.000 totaly -0.079 0.035 -2.272 0.023 -0.079 -0.021 totalo -0.071 0.029 -2.488 0.013 -0.071 -0.022 totalm -0.221 0.030 -7.249 0.000 -0.221 -0.060 ``` The results show that the indirect effects of urban residence on life satisfaction via income are small and statistically non-significant across all age groups. However, the total effects differ substantially, with the strongest negative effect observed among the middle-aged group. This suggests that while income does not meaningfully mediate the urban–satisfaction relationship at any age, the overall impact of urban residence on life satisfaction is most pronounced in midlife. When including continuous moderators, it is essential to remember that the multi-group approach requires categorising the moderator, which can lead to loss of information and statistical power. Alternative methods, such as using interaction terms within a single-group SEM framework, may be more appropriate when the moderator is continuous and the sample size is large enough. Alternatively, we could run sensitivity analyses with different codings of the moderator to ensure robust results. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions Moderated mediation provides a powerful way to move beyond simply documenting that “effects differ by group” toward understanding **how and where those differences arise within a causal system**. Multi-group SEM offers a flexible framework for investigating mediation and moderation concurrently. It also enables fine-grained hypothesis testing and facilitates interpretation. Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) --- **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, mediation, moderation, r, structural equation modelling --- ### [Hands-On Introduction to Moderation Analysis](https://longitudinalanalysis.com/hands-on-introduction-to-moderation-analysis/) **Published:** November 28, 2025 **Author:** Alex Cernat **Excerpt:** Learn how moderation analysis reveals when and for whom effects change in longitudinal data, with clear examples and practical modelling guidance. **Content:** In real-world research, relationships between variables are rarely uniform. An intervention might work well for one group but barely move the needle for another; a strong association in one context may vanish when conditions change. Moderation analysis helps uncover these patterns by testing whether the effect of one variable on another depends on a third variable. Without it, analysts risk reporting averaged effects that mask meaningful heterogeneity—leading to misleading conclusions, poor policy decisions, and weak theoretical insights. In practice, moderation is essential for understanding subgroup differences, contextual influences, and conditional effects. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Introduction to moderation analysis Moderation analysis helps us understand when and for whom an effect holds. The link between a predictor (*X*) and an outcome (*Y*) is often not constant—its strength may depend on a third variable, the moderator (*M*). Examples include whether stress affects health differently by gender, whether life events predict illness depending on perceived control, or whether sleep benefits cognition more for active individuals. These context-dependent patterns reveal important nuance that average effects hide. The figure below illustrates the basic idea. *X* predicts *Y* through the main path (*c*). Here, *M* modifies this relationship. The dashed arrow represents the interaction effect (*cxm*): the slope of *X→Y* changes depending on the level of *M*. Moderation is therefore about identifying the conditions that strengthen, weaken, or reverse the association between *X* and *Y*. ![conceptual representation of moderation analysis](https://longitudinalanalysis.com/wp-content/uploads/2025/11/image-1024x497.webp) Conceptually, moderation clarifies the conditions under which an effect is present. When researchers suspect that the *X→Y* relationship varies across subgroups or situations, moderation provides a formal way to test this. Predictors and moderators sit at the same causal level, and we typically use moderation when results appear inconsistent or unexpectedly small. It tells us not how *X* produces *Y*, but under what circumstances the effect is stronger, weaker, or absent. Several modelling tools are available for testing moderation. The most common is including an interaction term between *X* and *M* in a regression model. In SEM frameworks, multiple-group analysis examines whether paths differ across groups, and Johnson–Neyman intervals indicate the specific values of the moderator where the effect of *X* on *Y* becomes significant. These approaches make it straightforward to estimate and visualise moderation effects in R. ## How is moderation different from mediation? Although the terms sound similar, [mediation](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/) and moderation answer very different research questions. [Mediation](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/) focuses on how or why an effect occurs. A mediator sits in the causal chain between the predictor and the outcome, capturing the mechanism through which *X* influences *Y*. Mediation is most useful when theory or data suggest a strong relationship between the predictor of interest and the mediator, and when the goal is to uncover the underlying process leading to *Y*. Moderation, in contrast, asks when, for whom, or under what conditions an effect is present. A moderator does not lie along the causal pathway between 𝑋 and 𝑌; instead, it alters the strength or direction of their relationship. Moderation is typically explored when results are inconsistent, unexpectedly weak, or vary across contexts. Importantly, predictors and moderators sit at the same causal level—neither causes the other—making moderation a tool for identifying conditional effects rather than mechanisms. In short, mediation explains **why** an effect happens, while moderation shows **when** it happens. ## Regression models in R To explore moderation effects, we begin with a simple longitudinal regression model that predicts wave two (log)income using a set of baseline characteristics. ``` m1 <- lm(logincome_2 ~ age + degree.fct + single_1 + urban.fct_1 + sf12mcs_1, data = usw) summary(m1) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age + degree.fct + single_1 + urban.fct_1 + ## sf12mcs_1, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.3363 -0.3662 0.2613 0.7536 2.9219 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 6.9715046 0.0423587 164.583 <2e-16 *** ## age 0.0082467 0.0003794 21.739 <2e-16 *** ## degree.fctNo degree -0.6900677 0.0140985 -48.946 <2e-16 *** ## single_1 -0.1858810 0.0139242 -13.349 <2e-16 *** ## urban.fct_1Urban -0.0120416 0.0161408 -0.746 0.456 ## sf12mcs_1 0.0008782 0.0006594 1.332 0.183 ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.252 on 36085 degrees of freedom ## (14916 observations deleted due to missingness) ## Multiple R-squared: 0.08089, Adjusted R-squared: 0.08077 ## F-statistic: 635.2 on 5 and 36085 DF, p-value: < 2.2e-16 ``` The results indicate that older individuals report higher income at wave 2, and those without a degree earn substantially less, even after adjusting for other factors. Being single is also associated with lower income, while living in an urban area and mental health do not show a meaningful difference. We can also write down the regression equation based on the estimated coefficients from the model: log(income)2i = 6.97 + 0.008·agei – 0.69·degreeNoDegreei – 0.186·single1i – 0.012·urban1i + 0.001·sf12mcs1i This type of notation can be useful when interpreting more complex models (as we will see below). One thing to note about these results is that they are additive. We can say what the effect of a variable on the outcome is while holding the other predictors constant. For example, we can say that for each additional year of age, logged income at wave two increases by 0.008 units, controlling for education, partnership status, urban residence, and mental health. But these effects are assumed to be the same across levels of other predictors. For instance, the impact of age on income is assumed to be the same for both those who have a partner and those who are single. ## Moderation analysis with two continuous variables For now, we will use the strategy of including interaction terms between pairs of predictors to explore moderation effects. This allows us to see how the effect of one predictor varies with the level of another predictor. We will start by exploring the interaction between two continuous variables: age and mental health. An interaction can be created by multiplying two variables. This interaction term is then included in the regression model alongside the main effects of the two original variables. By doing this, we can assess whether the relationship between a predictor and the outcome varies across levels of the other predictor. For example, if we want to find out whether the effect of age on logged income at wave 2 depends on mental health, we would create an interaction term between age and mental health. This variable captures how the slope of age changes across different levels of mental health. Including this interaction in the regression model allows us to test whether the association between age and income is stronger or weaker for individuals with better or worse mental health. Here is how we can create the new variable: ``` usw <- mutate(usw, age_mcs = age * sf12mcs_1) ``` We can explore a few values of the new variable to see what it looks like. ``` ## # A tibble: 10 × 4 ## age sf12mcs_1 age_mcs n ## ## 1 16 54.2 867. 1 ## 2 43 26.6 1146. 1 ## 3 48 60.3 2895. 1 ## 4 49 49.5 2424. 1 ## 5 51 39.8 2031. 1 ## 6 54 51.8 2796. 1 ## 7 62 54.8 3396. 1 ## 8 65 55.2 3585. 1 ## 9 77 39.4 3036. 1 ## 10 77 58.9 4536. 1 ``` We see that the new variable is simply the product of age and mental health. We can now build a model that includes this interaction term alongside the main effects. ``` m2 <- lm(logincome_2 ~ age + sf12mcs_1 + age_mcs, data = usw) summary(m2) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age + sf12mcs_1 + age_mcs, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -4.9524 -0.4163 0.2437 0.7898 2.5485 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 6.51325967 0.10210298 63.791 <0.0000000000000002 *** ## age 0.00374905 0.00203224 1.845 0.0651 . ## sf12mcs_1 0.00018642 0.00197429 0.094 0.9248 ## age_mcs 0.00007057 0.00003889 1.815 0.0696 . ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.298 on 36104 degrees of freedom ## (14899 observations deleted due to missingness) ## Multiple R-squared: 0.01127, Adjusted R-squared: 0.01119 ## F-statistic: 137.2 on 3 and 36104 DF, p-value: < 0.00000000000000022 ``` Alternatively, if we use the `*` operator between two variables in the regression formula, R automatically includes both main effects and their interaction term. This is a more concise way to specify the same model without creating a new variable. ``` m2 <- lm(logincome_2 ~ age*sf12mcs_1, data = usw) summary(m2) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age * sf12mcs_1, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -4.9524 -0.4163 0.2437 0.7898 2.5485 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 6.51325967 0.10210298 63.791 <0.0000000000000002 *** ## age 0.00374905 0.00203224 1.845 0.0651 . ## sf12mcs_1 0.00018642 0.00197429 0.094 0.9248 ## age:sf12mcs_1 0.00007057 0.00003889 1.815 0.0696 . ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.298 on 36104 degrees of freedom ## (14899 observations deleted due to missingness) ## Multiple R-squared: 0.01127, Adjusted R-squared: 0.01119 ## F-statistic: 137.2 on 3 and 36104 DF, p-value: < 0.00000000000000022 ``` The model includes an interaction between age and mental health, allowing the effect of age on income to vary by mental health level. The coefficient for age (0.0037) represents the effect of age when mental health is 0. The coefficient for “sf12mcs\_1” (0.00019) represents the effect of mental health when age is 0. In this latter case, the main effect on its own is not meaningful as we don’t have any participants with age 0. The interaction term age\_mcs (0.00007) indicates that the effect of age on income becomes slightly stronger as mental health increases. While small and only marginally significant, this suggests that older individuals with better mental health may experience somewhat higher income compared to those with lower mental health. We can also write down the regression equation based on the estimated coefficients from the model: log(income)2i = 6.513 + 0.004·agei + 0.001·sf12mcs1i + 0.001·(agei × sf12mcs1i) Based on this, let’s compute the predicted log income for two example individuals: someone who is 30 years old and has a mental health score of 40 (below the average of 50), and someone who is 60 years old and has a mental health score of 70. ŷ30,40 = 6.513 + 0.004·(30) + 0.001·(40) + 0.001·(30×40) ≈ 6.633 ŷ60,70 = 6.513 + 0.004·(60) + 0.001·(70) + 0.001·(60×70) ≈ 6.753 The second individual (older, better mental health) has a slightly higher predicted logged income. Because the interaction term is small, the differences are modest. Still, the pattern is consistent with the model: income increases with age, and this increase becomes marginally stronger when mental health is higher. Instead of calculating predicted values by hand, we can use R. We can create a new data frame with hypothetical age and mental health values, and then use the `predict()` function to obtain the predicted log income for these scenarios. ``` mylist <- data.frame(age = seq(16, 100, by = 20), sf12mcs_1 = seq(20, 80, by = 15)) mylist ``` ``` ## age sf12mcs_1 ## 1 16 20 ## 2 36 35 ## 3 56 50 ## 4 76 65 ## 5 96 80 ``` ``` cbind(mylist, predicted_mcs = predict(m2, mylist)) ``` ``` ## age sf12mcs_1 predicted_mcs ## 1 16 20 6.599556 ## 2 36 35 6.743673 ## 3 56 50 6.930134 ## 4 76 65 7.158939 ## 5 96 80 7.430089 ``` We see, for example, that someone who is 16 and has 20 on the mental health scale has a predicted logged income of 6.59, while someone who is 96 and has 80 on the mental health scale has a predicted logged income of 7.43. This shows how both age and mental health contribute to higher predicted income. To better understand how the interaction effect impacts the results, we can also visualise these patterns. We could do this by hand or use the `emmeans` package, which has some helpful functions. One of these allows us to create interaction plots that show how the effect of one predictor varies across levels of another variable. In this case, we can plot the predicted log income by age for several fixed values of mental health. ``` library(emmeans) emmip(m2, sf12mcs_1 ~ age, at = mylist, CIs = TRUE) ``` ![moderation analysis for mental health and age on income](https://longitudinalanalysis.com/wp-content/uploads/2025/11/image-2-1024x731.webp) The upward-sloping lines indicate that income increases with age for all groups. The separation between the lines shows how this relationship varies by mental health: individuals with higher scores have slightly higher predicted income at every age. The lines also fan out gradually, indicating that the age–income relationship becomes slightly stronger at higher levels of mental health. Although the differences are modest, the pattern is consistent: better mental health is associated with somewhat higher income, and this gap widens as people get older. ## Moderation analysis with two categorical variables So far, we have explored moderation effects between two continuous variables. Another common scenario is when both the predictor and the moderator are categorical variables. In this case, we can create interaction terms by combining the categories of the two variables. This allows us to see how the effect of one categorical variable varies across levels of another categorical variable. As an example, we will explore how being single and having a degree moderate each other. We will create a single interaction variable combining the two categorical variables into four categories: “No degree, partnered”, “No degree, single”, “Degree, partnered”, and “Degree, single”. ``` usw <- usw %>% mutate(degree_single = case_when( degree.fct == "No degree" & single_1 == 0 ~ "No degree, partnered", degree.fct == "No degree" & single_1 == 1 ~ "No degree, single", degree.fct == "Degree" & single_1 == 0 ~ "Degree, partnered", degree.fct == "Degree" & single_1 == 1 ~ "Degree, single" )) count(usw, degree.fct, single_1, degree_single) ``` ``` ## # A tibble: 6 × 4 ## degree.fct single_1 degree_single n ## ## 1 Degree 0 [No] Degree, partnered 11156 ## 2 Degree 1 [Yes] Degree, single 5391 ## 3 No degree 0 [No] No degree, partnered 20074 ## 4 No degree 1 [Yes] No degree, single 14275 ## 5 0 [No] 67 ## 6 1 [Yes] 44 ``` We can now include the new variable in the regression model to see how the effect of education on logged income at wave 2 varies by partnership status. ``` m3 <- lm(logincome_2 ~ degree_single - 1, data = usw) summary(m3) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ degree_single - 1, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.0590 -0.3427 0.2862 0.7497 2.7749 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## degree_singleDegree, partnered 7.36160 0.01354 543.5 <2e-16 *** ## degree_singleDegree, single 7.21539 0.02066 349.3 <2e-16 *** ## degree_singleNo degree, partnered 6.76051 0.01024 659.9 <2e-16 *** ## degree_singleNo degree, single 6.43646 0.01263 509.6 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.272 on 38178 degrees of freedom ## (12825 observations deleted due to missingness) ## Multiple R-squared: 0.9668, Adjusted R-squared: 0.9668 ## F-statistic: 2.782e+05 on 4 and 38178 DF, p-value: < 2.2e-16 ``` *Note that here `- 1` tells R to remove the intercept, or constant, enabling us to estimate all the regression coefficients.* We can interpret the regression coefficients as the expected log income for that group. Based on this, the highest income is for individuals with a degree who are partnered, while the lowest income is for those without a degree who are single. The other two groups fall in between, with individuals with a degree earning more regardless of their relationship status. The fact that the differences between groups are not constant suggests a moderation effect as well. An alternative way to run this model is to use the `*` operator between the two categorical variables. This automatically includes both main effects and their interaction term in the regression model. ``` m4 <- lm(logincome_2 ~ degree.fct*single_1, data = usw) summary(m4) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ degree.fct * single_1, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.0590 -0.3427 0.2862 0.7497 2.7749 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.36160 0.01354 543.544 < 2e-16 *** ## degree.fctNo degree -0.60109 0.01698 -35.396 < 2e-16 *** ## single_1 -0.14621 0.02470 -5.919 3.26e-09 *** ## degree.fctNo degree:single_1 -0.17784 0.02957 -6.014 1.83e-09 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.272 on 38178 degrees of freedom ## (12825 observations deleted due to missingness) ## Multiple R-squared: 0.07029, Adjusted R-squared: 0.07022 ## F-statistic: 962.1 on 3 and 38178 DF, p-value: < 2.2e-16 ``` The results show that both having a degree and being in a relationship are associated with higher logged income at wave 2. The interaction term between degree and partnership status is also significant, indicating that the effect of having a degree on income differs depending on whether the individual is single. Specifically, the income advantage of having a degree is larger for partnered individuals compared to singles. To see that this model is the same as the previous one and represents an alternative way to write it, we can look at the equation. log(income)2i = 7.362 − 0.601·NoDegreei − 0.146·Singlei − 0.178·(NoDegreei × Singlei) If we compute the expected score for someone who has a degree and is single, we get the following value: ŷdegree, not single = 7.362 − 0.601(0) − 0.146(0) − 0.178(0×0) = 7.362 On the other hand, if we look at someone who does not have a degree and is single, we get: ŷno degree, single = 7.362 − 0.601(1) − 0.146(1) − 0.178(1×1) = 6.437 We can automate this process using the `emmeans` package to compute the estimated marginal means for each combination of degree and partnership status. ``` emmeans(m4, ~ degree.fct * single_1) ``` ``` ## degree.fct single_1 emmean SE df lower.CL upper.CL ## Degree 0 7.362 0.0135 38178 7.335 7.388 ## No degree 0 6.761 0.0102 38178 6.740 6.781 ## Degree 1 7.215 0.0207 38178 7.175 7.256 ## No degree 1 6.436 0.0126 38178 6.412 6.461 ## ## Confidence level used: 0.95 ``` The results are the same as in our previous model, confirming that both approaches yield identical estimates for the interaction between education and partnership status. The decision between the two methods often comes down to personal preference. Including an interaction in the model yields a statistical test and an estimate of the moderation effect. That being said, it is also harder to interpret. A good approach is to use the interaction and then the `emmeans()` function to get the predicted values for easier interpretation. We can also visualise the interaction effect using `emmip()`. This plot shows how the predicted logged income at wave 2 varies across education levels for those who are single and those who are not. ``` emmip(m4, degree.fct ~ single_1 , CIs = TRUE) ``` ![moderation analysis for being single and degree on income](https://longitudinalanalysis.com/wp-content/uploads/2025/11/image-1-1024x731.webp) We now see more clearly that for those without a degree, being single has a more negative effect. ## Moderation analysis with categorical and continuous variables When we want to investigate moderation effects between a continuous predictor and a categorical moderator, we can use the same strategy. For example, if we want to see whether there is a moderation effect between age and being single, we can create a new variable equal to the product of age and “single\_1”. ``` usw <- mutate(usw, age_single = age * single_1) set.seed(1234) sample_n(usw, 10) %>% count(age, single_1, age_single) ``` ``` ## # A tibble: 10 × 4 ## age single_1 age_single n ## ## 1 16 0 [No] 0 1 ## 2 43 0 [No] 0 1 ## 3 48 1 [Yes] 48 1 ## 4 49 1 [Yes] 49 1 ## 5 51 1 [Yes] 51 1 ## 6 54 0 [No] 0 1 ## 7 62 0 [No] 0 1 ## 8 65 0 [No] 0 1 ## 9 77 0 [No] 0 1 ## 10 77 1 [Yes] 77 1 ``` We can now run the model with the interaction and the main effects. ``` m5 <- lm(logincome_2 ~ age + single_1 + age_single, data = usw) summary(m5) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age + single_1 + age_single, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.3118 -0.4345 0.2299 0.7852 3.0118 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.3215468 0.0277520 263.82 <2e-16 *** ## age -0.0070225 0.0005441 -12.91 <2e-16 *** ## single_1 -1.5096438 0.0370353 -40.76 <2e-16 *** ## age_single 0.0264041 0.0007458 35.40 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.283 on 38229 degrees of freedom ## (12774 observations deleted due to missingness) ## Multiple R-squared: 0.05451, Adjusted R-squared: 0.05444 ## F-statistic: 734.7 on 3 and 38229 DF, p-value: < 2.2e-16 ``` Again, this is equivalent to using the `*` operator between age and “single\_1”, which automatically includes both main effects and their interaction term in the regression model. ``` m5 <- lm(logincome_2 ~ age *single_1, data = usw) summary(m5) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age * single_1, data = usw) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.3118 -0.4345 0.2299 0.7852 3.0118 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.3215468 0.0277520 263.82 <2e-16 *** ## age -0.0070225 0.0005441 -12.91 <2e-16 *** ## single_1 -1.5096438 0.0370353 -40.76 <2e-16 *** ## age:single_1 0.0264041 0.0007458 35.40 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.283 on 38229 degrees of freedom ## (12774 observations deleted due to missingness) ## Multiple R-squared: 0.05451, Adjusted R-squared: 0.05444 ## F-statistic: 734.7 on 3 and 38229 DF, p-value: < 2.2e-16 ``` The model shows that the relationship between age and income differs substantially between single participants and those with a partner. For people with a partner, age has a negative effect on logged income (–0.007), indicating that income decreases slightly with age in this group. The main effect of being single is difficult to interpret, as it refers to the expected effect at age 0. The positive interaction term (+0.026) indicates that the effect of age is positive for those who are single. To better understand this interaction, we can visualise it using an interaction plot. ``` emmip(m5, single_1 ~ age, at = list(age = seq(16, 100, by = 20), single = c(1, 0) ), CIs = TRUE) ``` ![moderation analysis for being single and age on income](https://longitudinalanalysis.com/wp-content/uploads/2025/11/image-3-1024x731.webp) This shows that the effect of age on income for single and non-single individuals goes in opposite directions. For people who have a partner, predicted income starts higher but gradually declines as people get older. For single individuals, income begins noticeably lower but increases with age. The two lines cross around mid-life, meaning that while single individuals earn less when young, their income eventually surpasses that of non-single individuals later in life. ## Want to learn more? Check [our on-demand course on moderation and mediation](https://leanpub.com/c/mediation-moderation-r). [Explore course](https://leanpub.com/c/mediation-moderation-r) ## Using multiple models to investigate moderation So far, we explored moderation effects using a single regression model that includes both the main effects and interaction terms. Another approach to investigate moderation is to run separate regression models for each level of the moderator variable. This allows us to see how the predictor’s effect on the outcome differs across groups defined by the moderator. If we look at our previous example of degree and logged income, we can run two separate models: one for single individuals and another for those with a partner. In this way, we can see how the effect of degree on logged income differs between these two groups. ``` m4a <- lm(logincome_2 ~ degree.fct, data = usw, subset = single_1 == 1) m4b <- lm(logincome_2 ~ degree.fct, data = usw, subset = single_1 == 0) summary(m4a) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ degree.fct, data = usw, subset = single_1 == ## 1) ## ## Residuals: ## Min 1Q Median 3Q Max ## -4.9128 -0.2623 0.3627 0.7996 2.7749 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.21539 0.02218 325.25 <2e-16 *** ## degree.fctNo degree -0.77893 0.02600 -29.96 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.366 on 13936 degrees of freedom ## (5772 observations deleted due to missingness) ## Multiple R-squared: 0.06049, Adjusted R-squared: 0.06043 ## F-statistic: 897.3 on 1 and 13936 DF, p-value: < 2.2e-16 ``` ``` summary(m4b) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ degree.fct, data = usw, subset = single_1 == ## 0) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.0590 -0.3814 0.2443 0.7149 2.4508 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.36160 0.01293 569.22 <2e-16 *** ## degree.fctNo degree -0.60109 0.01622 -37.07 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.215 on 24242 degrees of freedom ## (7053 observations deleted due to missingness) ## Multiple R-squared: 0.05364, Adjusted R-squared: 0.0536 ## F-statistic: 1374 on 1 and 24242 DF, p-value: < 2.2e-16 ``` We see that the degree has a larger effect on logged income for single individuals (–0.78) compared to individuals with a partner (–0.60). This suggests that the income advantage of having a degree is more pronounced for single people. We could use a similar approach for the age and single interaction by running separate models. ``` m5a <- lm(logincome_2 ~ age, data = usw, subset = single_1 == 0) summary(m5a) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age, data = usw, subset = single_1 == ## 0) ## ## Residuals: ## Min 1Q Median 3Q Max ## -4.9066 -0.4061 0.2222 0.7332 2.4165 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 7.3215468 0.0269068 272.11 <2e-16 *** ## age -0.0070225 0.0005275 -13.31 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.244 on 24270 degrees of freedom ## (7025 observations deleted due to missingness) ## Multiple R-squared: 0.007249, Adjusted R-squared: 0.007208 ## F-statistic: 177.2 on 1 and 24270 DF, p-value: < 2.2e-16 ``` ``` m5b <- lm(logincome_2 ~ age, data = usw, subset = single_1 == 1) summary(m5b) ``` ``` ## ## Call: ## lm(formula = logincome_2 ~ age, data = usw, subset = single_1 == ## 1) ## ## Residuals: ## Min 1Q Median 3Q Max ## -5.3118 -0.4796 0.2452 0.8814 3.0118 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 5.811903 0.025771 225.52 <2e-16 *** ## age 0.019382 0.000536 36.16 <2e-16 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 1.348 on 13959 degrees of freedom ## (5749 observations deleted due to missingness) ## Multiple R-squared: 0.08564, Adjusted R-squared: 0.08558 ## F-statistic: 1307 on 1 and 13959 DF, p-value: < 2.2e-16 ``` Now it is easier to see that age has very different effects on income for the two groups. For those with a partner, age has a small negative effect on logged income (–0.007), while for single individuals, age has a positive impact (+0.019). This confirms our earlier finding that the relationship between age and income differs substantially based on partnership status. When we have a continuous moderator, we can also use a similar approach by splitting the data into groups based on the moderator’s levels. For example, we can create groups based on low, medium, and high levels of mental health, and then run separate regression models for each group to examine how age affects logged income. The advantage of this approach is that it allows us to see differences in effects more clearly and to have all coefficients differ across groups (e.g., residuals). However, it also has some limitations. Running separate models can lead to a smaller sample, thereby reducing statistical power. Additionally, it can be more cumbersome to compare results across multiple models compared to a single model with interaction terms. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusions regarding moderation analysis Moderation analysis allows us to move beyond simple average effects and examine how relationships vary across people, contexts, and time—an essential step in understanding heterogeneity in data. Regressions that include interactions, combined with tools such as marginal-effect plots, can make these patterns clearer, while alternative approaches, such as running group-specific models, can offer greater flexibility. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis, visualization **Tags:** longitudinal data analysis, moderation, r, visualization --- ### [Longitudinal Mediation in R: A Hands-On Guide](https://longitudinalanalysis.com/longitudinal-mediation-in-r-a-hands-on-guide/) **Published:** October 31, 2025 **Author:** Alex Cernat **Excerpt:** Learn how to run longitudinal mediation analysis in R using lavaan. Step-by-step guide to model indirect effects and causal pathways over time. **Content:** Mediation analysis has become one of the most popular tools in the social and behavioral sciences for understanding the pathways through which variables influence each other. For example, rather than simply asking whether income affects health, mediation models allow us to explore the mechanisms—such as whether higher income leads to greater life satisfaction, which in turn improves health outcomes. This ability to go beyond correlation and reveal potential causal pathways makes mediation indispensable in applied research, spanning psychology, sociology, public health, and economics. However, using cross-sectional data to investigate mediation processes can be problematic, as causal directions are often unclear and effects may not be concurrent in time. Longitudinal mediation can tackle these issues by combining the logic of mediation with repeated observations. This allows researchers to clarify causal direction and account for the time lag of effects. For example, rather than assuming that income and life satisfaction are related at a single point in time, a longitudinal mediation model can test whether income increases precede increases in satisfaction, which in turn translate into better health. By using the temporal order of the data, we can ensure the correct causal direction. Furthermore, if we believe there is a time lag between the increase in income and the change in satisfaction, this can be easily accounted for. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! In this guide, we will build on [path analysis](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/) as a method for estimating longitudinal mediation models using data from the [Understanding Society](https://www.understandingsociety.ac.uk/) survey. As an illustration, we will explore how income affects mental health through life satisfaction over three waves of data. ## Conceptual presentation of longitudinal mediation The figure below shows the basic structure of a [**mediation model**](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/), a simple yet powerful framework often presented using structural equation model (SEM) diagrams. Here, a predictor variable *X* influences an outcome *Y* both directly (path *c*) and indirectly through a mediator *M* (paths *a* and *b*). The indirect effect, computed as the product *a*×*b*, represents the portion of the relationship between *X* and *Y* that operates through the mediator. For example, in social science research, *X* might represent income, *M* might represent life satisfaction, and *Y* might represent health. In this case, mediation analysis helps us understand whether higher income leads to better health *because* it improves satisfaction, which in turn enhances well-being. As discussed in [this earlier post](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/), mediation models can be estimated using path analysis or SEM, allowing researchers to decompose total effects into their direct and indirect components and test hypotheses about underlying mechanisms. ![cross-sectional mediation model using SEM diagram](https://longitudinalanalysis.com/wp-content/uploads/2025/10/image-1-1024x574.webp) While mediation analysis is a powerful framework for uncovering potential mechanisms, it also comes with important limitations. First, the assumed **causal direction** between variables—such as *X*→*M*→*Y*—is often theoretical rather than tested empirically. In many cases, it is equally plausible that the mediator influences the predictor or that the relationship is reciprocal. Second, mediation assumes that effects occur **instantaneously**, but in reality, the influence of *X* on *M* or *Y* may take time to manifest. Without longitudinal data, it is difficult to capture such delayed or dynamic processes. Finally, mediation models based on observational data rely on the strong assumption that there is **no unmeasured confounding**. This implies that there are no omitted variables that simultaneously affect both the mediator and the outcome. Violations of this assumption can bias estimates of the indirect effect and lead to misleading conclusions. Longitudinal mediation addresses some of the limitations of traditional, cross-sectional mediation models by explicitly modeling **change over time** and the **temporal order** of variables. Because data are collected at multiple time points, researchers can infer the causal direction between variables more accurately—testing, for example, whether changes in *X* precede changes in the mediator *M*, which in turn lead to later changes in *Y* . This temporal separation helps reduce the risk of reverse causality and provides a framework to study **delayed effects**, where the influence of a predictor may take time to manifest. Moreover, by controlling for prior levels of each variable, longitudinal models help to account for some of the **unobserved confounding**. The figure below shows how the simple mediation model can be extended to a **three-wave longitudinal design**. Each variable—*X*, *M*, and *Y*—is measured at three time points (subscripts 1–3). The horizontal arrows represent **stability paths**, showing how each construct at an earlier time predicts itself at a later time (e.g., *X*1→*X*2→*X*3). The diagonal arrows labeled *a* and *b* represent the **mediated effects** from *X* to *M* and from *M* to *Y* across waves, while the dashed arrow (*c*) captures the **direct effect** of earlier *X* values on later *Y* outcomes. The circles (*ϵ*) denote residuals or unexplained variance for each variable at each time point. ![longitudinal mediation model using SEM diagram](https://longitudinalanalysis.com/wp-content/uploads/2025/10/image-2-834x1024.webp) By combining the logic of mediation with the structure of longitudinal data, this model ensures the correct causal direction (e.g., *M* in time point 2 cannot cause *X* in time point 1). Furthermore, by controlling for past values of the variables, we can minimize the effect of confounding variables. ## Running longitudinal mediation in R To illustrate how longitudinal mediation can be estimated, we will use the `lavaan` package from R. The model below extends the traditional mediation framework to a three-wave panel, where *income* (`logincome`), *life satisfaction* (`sati`), and *mental health* (`sf12mcs`) are each measured at three points in time. The goal is to test whether earlier levels of income influence later mental health indirectly, through changes in life satisfaction. To do this, we include **autoregressive paths** (e.g., `logincome\_1 → logincome\_2 → logincome\_3`) to account for stability over time, and **cross-lagged paths** that represent the hypothesized mediation process (e.g., `logincome\_1 → sati\_2 → sf12mcs\_3`). The R code below specifies this longitudinal mediation model: ``` library(lavaan) model <- ' logincome_2 ~ logincome_1 sati_2 ~ logincome_1 + sati_1 sf12mcs_2 ~ sati_1 + sf12mcs_1 logincome_3 ~ logincome_2 sati_3 ~ logincome_2 + sati_2 sf12mcs_3 ~ sati_2 + logincome_1 + sf12mcs_2 ' med1 <- sem(model, data = usw) summary(med1, standardized = TRUE) ``` ``` ## lavaan 0.6-19 ended normally after 33 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 20 ## ## Used Total ## Number of observations 18008 51007 ## ## Model Test User Model: ## ## Test statistic 6977.809 ## Degrees of freedom 19 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_2 ~ ## logincome_1 0.583 0.005 117.620 0.000 0.583 0.659 ## sati_2 ~ ## logincome_1 0.013 0.007 1.952 0.051 0.013 0.013 ## sati_1 0.478 0.007 69.996 0.000 0.478 0.462 ## sf12mcs_2 ~ ## sati_1 1.620 0.052 31.407 0.000 1.620 0.236 ## sf12mcs_1 0.184 0.008 24.239 0.000 0.184 0.182 ## logincome_3 ~ ## logincome_2 0.454 0.006 72.364 0.000 0.454 0.475 ## sati_3 ~ ## logincome_2 0.026 0.008 3.076 0.002 0.026 0.021 ## sati_2 0.344 0.007 46.780 0.000 0.344 0.329 ## sf12mcs_3 ~ ## sati_2 1.095 0.044 24.742 0.000 1.095 0.170 ## logincome_1 0.105 0.044 2.387 0.017 0.105 0.016 ## sf12mcs_2 0.332 0.007 51.006 0.000 0.332 0.342 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_3 ~~ ## .sati_3 0.033 0.011 3.064 0.002 0.033 0.023 ## .sf12mcs_3 0.140 0.064 2.195 0.028 0.140 0.016 ## .sati_3 ~~ ## .sf12mcs_3 2.588 0.088 29.323 0.000 2.588 0.224 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_2 0.854 0.009 94.889 0.000 0.854 0.566 ## .sati_2 1.563 0.016 94.889 0.000 1.563 0.786 ## .sf12mcs_2 76.972 0.811 94.889 0.000 76.972 0.879 ## .logincome_3 1.070 0.011 94.889 0.000 1.070 0.775 ## .sati_3 1.940 0.020 94.889 0.000 1.940 0.891 ## .sf12mcs_3 68.831 0.725 94.889 0.000 68.831 0.837 ``` When interpreting longitudinal mediation results, it is good to focus on **standardized coefficients** (`Std.all` column), as they express relationships in comparable units across variables with different scales. The effect of income in wave 1 on satisfaction in wave 2 is 0.013. This implies that an increase in income is associated with a slightly higher well-being score. The “b” path, linking satisfaction to later mental health (0.170), is stronger, indicating that higher satisfaction predicts better mental health. The direct effect of income on mental health is 0.016, suggesting only a small effect after controlling for the indirect path and previous values of health. The horizontal paths—such as `logincome_1 → logincome_2` (0.659) or `sf12mcs_2 → sf12mcs_3` (0.342)—represent **stability**, or how much the ranking of individuals persists across waves. These paths serve as strong controls, indicating that a significant portion of the variation in each construct is explained by its previous level. We can visualize the main coefficients of interest using an SEM plot: ![results from longitudinal mediation using R](https://longitudinalanalysis.com/wp-content/uploads/2025/10/image-3-1024x988.webp) ### Calculating indirect and total effects To better understand how income influences health, it is beneficial to distinguish between its **direct** and **indirect effects**. The direct effect represents the portion of the relationship between income and health that is not explained by life satisfaction. In contrast, the indirect effect captures the pathway through which income affects satisfaction, which in turn influences mental health. Estimating both helps clarify whether the association between income and health is primarily due to material factors or operates through psychological mechanisms. In the updated model, we label the path from income to satisfaction as **a**, the path from satisfaction to health as **b**, and the direct path from income to health as **c**. These labels allow us to define new parameters that quantify the indirect and total effects: `indirect := a * b` computes the mediated pathway, and `total := c + (a * b)` sums both direct and indirect effects to capture the overall impact of income on mental health. ``` model <- ' logincome_2 ~ logincome_1 sati_2 ~ a*logincome_1 + sati_1 sf12mcs_2 ~ sati_1 + sf12mcs_1 logincome_3 ~ logincome_2 sati_3 ~ logincome_2 + sati_2 sf12mcs_3 ~ b*sati_2 + c*logincome_1 + sf12mcs_2 # Indirect effect indirect := a * b # Total effect total := c + (a * b) ' med1b <- sem(model, data = usw) summary(med1b, standardized = TRUE) ``` ``` ## lavaan 0.6-19 ended normally after 33 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 20 ## ## Used Total ## Number of observations 18008 51007 ## ## Model Test User Model: ## ## Test statistic 6977.809 ## Degrees of freedom 19 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_2 ~ ## logincom_1 0.583 0.005 117.620 0.000 0.583 0.659 ## sati_2 ~ ## logincom_1 (a) 0.013 0.007 1.952 0.051 0.013 0.013 ## sati_1 0.478 0.007 69.996 0.000 0.478 0.462 ## sf12mcs_2 ~ ## sati_1 1.620 0.052 31.407 0.000 1.620 0.236 ## sf12mcs_1 0.184 0.008 24.239 0.000 0.184 0.182 ## logincome_3 ~ ## logincom_2 0.454 0.006 72.364 0.000 0.454 0.475 ## sati_3 ~ ## logincom_2 0.026 0.008 3.076 0.002 0.026 0.021 ## sati_2 0.344 0.007 46.780 0.000 0.344 0.329 ## sf12mcs_3 ~ ## sati_2 (b) 1.095 0.044 24.742 0.000 1.095 0.170 ## logincom_1 (c) 0.105 0.044 2.387 0.017 0.105 0.016 ## sf12mcs_2 0.332 0.007 51.006 0.000 0.332 0.342 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_3 ~~ ## .sati_3 0.033 0.011 3.064 0.002 0.033 0.023 ## .sf12mcs_3 0.140 0.064 2.195 0.028 0.140 0.016 ## .sati_3 ~~ ## .sf12mcs_3 2.588 0.088 29.323 0.000 2.588 0.224 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_2 0.854 0.009 94.889 0.000 0.854 0.566 ## .sati_2 1.563 0.016 94.889 0.000 1.563 0.786 ## .sf12mcs_2 76.972 0.811 94.889 0.000 76.972 0.879 ## .logincome_3 1.070 0.011 94.889 0.000 1.070 0.775 ## .sati_3 1.940 0.020 94.889 0.000 1.940 0.891 ## .sf12mcs_3 68.831 0.725 94.889 0.000 68.831 0.837 ## ## Defined Parameters: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## indirect 0.014 0.007 1.946 0.052 0.014 0.002 ## total 0.119 0.044 2.677 0.007 0.119 0.018 ``` The results indicate that the indirect effect of income on later mental health, mediated by life satisfaction, is small (standardized coefficient= 0.002), suggesting a weak mediated pathway. In contrast, the **total effect** (standardized = 0.018) is larger and statistically significant, indicating that higher income at the earlier wave is associated with better overall mental health in the subsequent period. This pattern implies that while part of the relationship may operate through increased satisfaction, most of the effect is likely explained by the direct effect or other mechanisms. ## Including control variables Although the longitudinal mediation model controls for information from previous waves, it is still important to include **control variables** to account for potential confounders. Factors such as education, gender, and marital status are often correlated with income, satisfaction, and health outcomes. By including them as covariates, we ensure that the estimated paths reflect the unique relationships among the key variables of interest rather than spurious associations driven by background characteristics. As an example, we include three variables as controls: degree, gender, and relationship status (single). The first two are considered time constant, while the latter is time-varying. Their inclusion in the key equations means that the mediation coefficients will be “corrected” or “controlled” for their possible confounding effects. ``` model <- ' logincome_2 ~ logincome_1 sati_2 ~ a*logincome_1 + sati_1 + degree.fct + gndr.fct + single_2 sf12mcs_2 ~ sati_1 + sf12mcs_1 logincome_3 ~ logincome_2 sati_3 ~ logincome_2 + sati_2 sf12mcs_3 ~ b*sati_2 + c*logincome_1 + sf12mcs_2 + degree.fct + gndr.fct + single_3 # Indirect effect indirect := a * b # Total effect total := c + (a * b) ' med2 <- sem(model, data = usw) summary(med2, standardized = TRUE) ``` ``` ## lavaan 0.6-19 ended normally after 49 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 26 ## ## Used Total ## Number of observations 18005 51007 ## ## Model Test User Model: ## ## Test statistic 8015.186 ## Degrees of freedom 37 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_2 ~ ## logincom_1 0.582 0.005 117.593 0.000 0.582 0.659 ## sati_2 ~ ## logincom_1 (a) -0.001 0.007 -0.167 0.868 -0.001 -0.001 ## sati_1 0.474 0.007 69.021 0.000 0.474 0.459 ## degree.fct -0.075 0.020 -3.808 0.000 -0.075 -0.026 ## gndr.fct -0.052 0.019 -2.744 0.006 -0.052 -0.018 ## single_2 -0.093 0.020 -4.588 0.000 -0.093 -0.031 ## sf12mcs_2 ~ ## sati_1 1.620 0.052 31.409 0.000 1.620 0.236 ## sf12mcs_1 0.184 0.008 24.234 0.000 0.184 0.182 ## logincome_3 ~ ## logincom_2 0.454 0.006 72.364 0.000 0.454 0.475 ## sati_3 ~ ## logincom_2 0.026 0.008 3.127 0.002 0.026 0.022 ## sati_2 0.344 0.007 46.779 0.000 0.344 0.329 ## sf12mcs_3 ~ ## sati_2 (b) 1.094 0.044 24.655 0.000 1.094 0.170 ## logincom_1 (c) 0.082 0.046 1.791 0.073 0.082 0.013 ## sf12mcs_2 0.329 0.006 50.564 0.000 0.329 0.339 ## degree.fct 0.391 0.128 3.050 0.002 0.391 0.021 ## gndr.fct -0.639 0.123 -5.184 0.000 -0.639 -0.035 ## single_3 -0.478 0.131 -3.666 0.000 -0.478 -0.025 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_3 ~~ ## .sati_3 0.033 0.011 3.070 0.002 0.033 0.023 ## .sf12mcs_3 0.134 0.064 2.105 0.035 0.134 0.016 ## .sati_3 ~~ ## .sf12mcs_3 2.589 0.088 29.368 0.000 2.589 0.224 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_2 0.854 0.009 94.882 0.000 0.854 0.566 ## .sati_2 1.559 0.016 94.882 0.000 1.559 0.784 ## .sf12mcs_2 76.976 0.811 94.882 0.000 76.976 0.879 ## .logincome_3 1.070 0.011 94.882 0.000 1.070 0.775 ## .sati_3 1.940 0.020 94.882 0.000 1.940 0.891 ## .sf12mcs_3 68.657 0.724 94.882 0.000 68.657 0.836 ## ## Defined Parameters: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## indirect -0.001 0.008 -0.167 0.868 -0.001 -0.000 ## total 0.081 0.047 1.739 0.082 0.081 0.012 ``` After including the control variables for education, gender, and relationship status, the mediation effects changed noticeably. The “a” path from income to life satisfaction, which was previously small but positive, is now essentially zero, suggesting that once these background characteristics are accounted for, income no longer predicts satisfaction. The “b” path from satisfaction to later mental health remains large (0.170), indicating that satisfaction continues to be an important predictor of well-being. The “c” path, representing the direct effect of income on later health, is slightly smaller (0.013) and no longer statistically significant, implying that any remaining influence of income is weak once both satisfaction and sociodemographic factors are controlled. Correspondingly, the indirect and total effects decrease in size. Overall, this pattern suggests that much of the previously observed relationship between income, satisfaction, and health may be attributed to differences in education, gender, and relationship status, rather than to a genuine longitudinal mediation process. ## An alternative specification of longitudinal mediation An alternative approach to specifying longitudinal mediation, illustrated in the figure below, focuses on estimating wave-to-wave effects rather than decomposing them into a single pathway across three waves. In this approach, each variable—*X*, *M*, and *Y*—is modeled as influencing its future values and the corresponding measures of the other variables in the next wave (e.g., *X*1→*M*2, *M*1→*Y*2). This setup enables researchers to focus on lag-1 effects, specifically whether values at one time point influence those at the next time point. One of the key strengths of this model is that it can be applied even when only two waves of data are available. It is also better suited for situations where the mediator and outcome are expected to be affected relatively quickly by changes in the predictor. ![alternative way to do longitudinal mediation analysis](https://longitudinalanalysis.com/wp-content/uploads/2025/10/image.webp) However, this specification has some limitations. Because the model estimates separate paths for each time interval, we cannot formally compute overall direct and indirect effects across waves. The mediation process is implied by the sequence of coefficients (e.g., *a*1 and *b*1), but cannot be summarized in a single pathway. This makes it less straightforward to quantify how much of the total effect of *X* on *Y* is transmitted through *M*. Additionally, this structure can become complex to interpret as the number of waves increases. To illustrate the model, we adapt the code to our data. Each time interval now has its own set of parameters: *a*1, *b*1, and *c*1 for the paths from Wave 1 to Wave 2, and *a*2, *b*2, and *c*2 for the paths from Wave 2 to Wave 3. ``` model <- ' logincome_2 ~ logincome_1 sati_2 ~ a1*logincome_1 + sati_1 sf12mcs_2 ~ b1*sati_1 + c1*logincome_1 + sf12mcs_1 logincome_3 ~ logincome_2 sati_3 ~ a2*logincome_2 + sati_2 sf12mcs_3 ~ b2*sati_2 + c2*logincome_2 + sf12mcs_2 ' med3 <- sem(model, data = usw) summary(med3, standardized = TRUE) ``` ``` ## lavaan 0.6-19 ended normally after 33 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 21 ## ## Used Total ## Number of observations 18008 51007 ## ## Model Test User Model: ## ## Test statistic 6942.089 ## Degrees of freedom 18 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_2 ~ ## logincm_1 0.583 0.005 117.620 0.000 0.583 0.659 ## sati_2 ~ ## logincm_1 (a1) 0.013 0.007 1.952 0.051 0.013 0.013 ## sati_1 0.478 0.007 69.996 0.000 0.478 0.462 ## sf12mcs_2 ~ ## sati_1 (b1) 1.625 0.052 31.523 0.000 1.625 0.237 ## logincm_1 (c1) 0.267 0.047 5.672 0.000 0.267 0.040 ## sf12mcs_1 0.182 0.008 23.998 0.000 0.182 0.181 ## logincome_3 ~ ## logincm_2 0.454 0.006 72.381 0.000 0.454 0.475 ## sati_3 ~ ## logincm_2 (a2) 0.028 0.008 3.346 0.001 0.028 0.024 ## sati_2 0.344 0.007 46.775 0.000 0.344 0.329 ## sf12mcs_3 ~ ## sati_2 (b2) 1.094 0.044 24.726 0.000 1.094 0.170 ## logincm_2 (c2) 0.149 0.050 2.956 0.003 0.149 0.020 ## sf12mcs_2 0.331 0.007 50.939 0.000 0.331 0.342 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_3 ~~ ## .sati_3 0.033 0.011 3.064 0.002 0.033 0.023 ## .sf12mcs_3 0.186 0.064 2.909 0.004 0.186 0.022 ## .sati_3 ~~ ## .sf12mcs_3 2.589 0.088 29.341 0.000 2.589 0.224 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_2 0.854 0.009 94.889 0.000 0.854 0.566 ## .sati_2 1.563 0.016 94.889 0.000 1.563 0.786 ## .sf12mcs_2 76.834 0.810 94.889 0.000 76.834 0.877 ## .logincome_3 1.070 0.011 94.889 0.000 1.070 0.775 ## .sati_3 1.940 0.020 94.889 0.000 1.940 0.891 ## .sf12mcs_3 68.833 0.725 94.889 0.000 68.833 0.837 ``` The “a” and “b” paths are similar to those previously estimated. The “c” paths from wave 1 to wave 2 are larger than what we saw in the previous model, while those from wave 2 to wave 3 are similar. We can visualize the results using a SEM diagram as well: ![results from alternative way to do mediation analysis](https://longitudinalanalysis.com/wp-content/uploads/2025/10/image-4.webp) ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ### Investigating if the coefficients are equal in time with longitudinal mediation In the context of longitudinal mediation, it can be interesting to test whether the mediation effects remain **stable over time**. Real-world processes, such as the relationship between income, satisfaction, and health, may evolve as individuals age or as broader social and economic conditions shift. For example, income increases may have a stronger effect on satisfaction in earlier periods of life, while later on, satisfaction may become more important for maintaining good mental health. To formally test whether the **direct effect** of income on health is constant across waves, we can constrain the relevant parameters to be equal in the model. In the code below, both direct paths—from `logincome_1` to `sf12mcs_2` and from `logincome_2` to `sf12mcs_3`—are labeled with the same parameter name `c`. By using an identical label, the model forces these coefficients to take the same value. If this constraint significantly worsens model fit compared to a freely estimated model, it suggests that the direct effect changes over time; if not, it supports the idea of temporal stability in this relationship. ``` model <- ' logincome_2 ~ logincome_1 sati_2 ~ a1*logincome_1 + sati_1 sf12mcs_2 ~ b1*sati_1 + c*logincome_1 + sf12mcs_1 logincome_3 ~ logincome_2 sati_3 ~ a2*logincome_2 + sati_2 sf12mcs_3 ~ b2*sati_2 + c*logincome_2 + sf12mcs_2 ' med3b <- sem(model, data = usw) summary(med3b, standardized = TRUE) ``` ``` ## lavaan 0.6-19 ended normally after 33 iterations ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 21 ## Number of equality constraints 1 ## ## Used Total ## Number of observations 18008 51007 ## ## Model Test User Model: ## ## Test statistic 6945.017 ## Degrees of freedom 19 ## P-value (Chi-square) 0.000 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## logincome_2 ~ ## logincm_1 0.583 0.005 117.620 0.000 0.583 0.659 ## sati_2 ~ ## logincm_1 (a1) 0.013 0.007 1.952 0.051 0.013 0.013 ## sati_1 0.478 0.007 69.996 0.000 0.478 0.462 ## sf12mcs_2 ~ ## sati_1 (b1) 1.624 0.052 31.504 0.000 1.624 0.237 ## logincm_1 (c) 0.212 0.034 6.163 0.000 0.212 0.031 ## sf12mcs_1 0.182 0.008 24.057 0.000 0.182 0.181 ## logincome_3 ~ ## logincm_2 0.454 0.006 72.417 0.000 0.454 0.475 ## sati_3 ~ ## logincm_2 (a2) 0.031 0.008 3.675 0.000 0.031 0.026 ## sati_2 0.344 0.007 46.771 0.000 0.344 0.329 ## sf12mcs_3 ~ ## sati_2 (b2) 1.095 0.044 24.731 0.000 1.095 0.170 ## logincm_2 (c) 0.212 0.034 6.163 0.000 0.212 0.029 ## sf12mcs_2 0.331 0.007 50.876 0.000 0.331 0.341 ## ## Covariances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_3 ~~ ## .sati_3 0.033 0.011 3.064 0.002 0.033 0.023 ## .sf12mcs_3 0.186 0.064 2.911 0.004 0.186 0.022 ## .sati_3 ~~ ## .sf12mcs_3 2.590 0.088 29.347 0.000 2.590 0.224 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .logincome_2 0.854 0.009 94.889 0.000 0.854 0.566 ## .sati_2 1.563 0.016 94.889 0.000 1.563 0.786 ## .sf12mcs_2 76.840 0.810 94.889 0.000 76.840 0.878 ## .logincome_3 1.070 0.011 94.889 0.000 1.070 0.775 ## .sati_3 1.940 0.020 94.889 0.000 1.940 0.891 ## .sf12mcs_3 68.841 0.725 94.889 0.000 68.841 0.837 ``` To assess whether constraining the direct effects to be equal across time significantly worsens model fit, we can compare the **unconstrained** and **constrained** models using the `anova()` function in R. This performs a **chi-squared difference test**, where the null hypothesis is that the simpler (constrained) model fits the data as well as the more complex one. A significant p-value would indicate that the constraint leads to a poorer fit, suggesting that the effects differ over time. ``` anova(med3, med3b) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## med3 18 478458 478622 6942.1 ## med3b 19 478459 478615 6945.0 2.9283 0.010348 1 0.08704 . ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` In this case, the chi-squared difference test yields a value of 2.93 with 1 degree of freedom and a p-value of 0.087. Since this is above the conventional 0.05 threshold, we do not reject the null hypothesis. The AIC and BIC also indicate that the constrained model is similar to or better than the unconstrained model (smaller values indicate a better fit). This means that constraining the direct effect of income on mental health to be equal across waves does not significantly reduce model fit. In other words, there is no strong evidence that the direct effect changes over time—the direct relationship between income and health appears to be relatively stable across the two time intervals. In addition to testing whether the direct effect remains stable over time, we can also examine whether the **a** and **b** paths—the effects of income on satisfaction and of satisfaction on mental health—remain constant across waves. To do this, we assign the same parameter labels (`a` and `b`) to the corresponding paths in both time intervals. ``` model <- ' logincome_2 ~ logincome_1 sati_2 ~ a*logincome_1 + sati_1 sf12mcs_2 ~ b*sati_1 + c*logincome_1 + sf12mcs_1 logincome_3 ~ logincome_2 sati_3 ~ a*logincome_2 + sati_2 sf12mcs_3 ~ b*sati_2 + c*logincome_2 + sf12mcs_2 ' med3c <- sem(model, data = usw) anova(med3b, med3c) ``` ``` ## ## Chi-Squared Difference Test ## ## Df AIC BIC Chisq Chisq diff RMSEA Df diff Pr(>Chisq) ## med3b 19 478459 478615 6945.0 ## med3c 21 478514 478655 7003.8 58.811 0.039716 2 1.696e-13 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ``` The chi-squared difference test comparing these two models shows a large and highly significant difference (Δ*χ*2= 58.81, df = 2, p < 0.001). This indicates that forcing the **a** and **b** coefficients to be equal substantially worsens model fit. In other words, the effects of income on satisfaction and the effects of satisfaction on mental health are not constant overtime. The strength of these relationships likely changes between waves, suggesting that the mediation process itself evolves—perhaps becoming weaker or stronger as people’s circumstances change. ## Want to learn more? Check [our on-demand course on moderation and mediation](https://leanpub.com/c/mediation-moderation-r). [Explore course](https://leanpub.com/c/mediation-moderation-r) ## Conclusions regarding longitudinal mediation Mediation analysis enables researchers to move beyond simple associations and explore the mechanisms that link causes and effects. When applied to longitudinal data, it becomes an even more powerful tool. This approach can address key challenges of cross-sectional mediation, such as uncertainty about the causal direction or timing of effects. Our example also illustrated how longitudinal mediation can reveal whether specific pathways remain stable or evolve as people’s circumstances change, as well as the impact of confounders on key statistics. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis **Tags:** longitudinal data analysis, r, structural equation modelling --- ### [Introduction to Path and Mediation Analysis with R](https://longitudinalanalysis.com/introduction-to-path-and-mediation-analysis-with-r/) **Published:** September 29, 2025 **Author:** Alex Cernat **Excerpt:** Introduction to path analysis and mediation analysis in R. Estimate direct, indirect, and total effects with diagrams, examples, and code. **Content:** Mediation and path analysis are two of the most popular methods in the social sciences because they allow researchers to move beyond simple regression and study complex networks of relationships. Instead of looking only at one outcome at a time, these methods make it possible to examine how multiple variables influence each other. For example, we might want to understand how parental education shapes income, not only through a direct effect but also indirectly through educational attainment and self-esteem. In psychology, we might study whether stress affects health outcomes directly or indirectly by reducing sleep quality. By separating direct, indirect, and total effects, path and mediation analysis provide a clearer picture of the mechanisms that connect variables—making them powerful tools for answering “how” and “why” questions in research. In this post, we will introduce path analysis as a method for empirically testing mediation relationships. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Investigating mediation using path analysis Path analysis can be considered a special case of Structural Equation Modeling (SEM) in which we include only observed variables. Both path analysis and SEM are typically represented using graphs to facilitate understanding of the model of interest. An example of a path diagram is shown below. ![Basic path analysis diagram showing a mediation model](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image-1024x574.webp) Mediation analysis builds on path analysis by focusing on how and through what mechanisms one variable influences another. In a path diagram, variables are shown as squares (observed variables), while single-headed arrows represent causal paths or regression slopes. For example, if we want to know whether parental education influences income through education, we would draw an arrow from parental education to education, and another from education to income. The indirect path formed by these arrows shows the mediating process. By following the arrows in the diagram, we can separate direct effects (“c”, the arrow from X to Y) from indirect effects (“a” and “b” in the figure above). Sometimes a predictor no longer has a direct effect on the outcome once the mediator is included. This is called **complete mediation**. For instance, if parental education affects income only through education, the direct path from parental education to income would be close to zero once education is controlled for. In contrast, if both the direct and indirect effects remain strong, we have partial mediation. Complete mediation is important because it suggests that the mediator fully explains the mechanism linking the two variables. Identifying such cases helps researchers build stronger theoretical models and design interventions that target the key mediating variable. ![Basic path analysis diagram showing a complete mediation ](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image-1-1024x567.webp) Real-world data often involves more than one mediator or multiple outcomes. Imagine a study in public health where researchers aim to understand the impact of childhood socioeconomic status (SES) on adult health outcomes. SES may have a direct effect on health, but it may also operate indirectly through multiple mediators, such as educational attainment, job opportunities, lifestyle factors (including diet, exercise, and smoking), and psychological stress. In this case, the path diagram would contain several squares for each variable, with arrows tracing both direct and indirect routes from childhood SES to adult health. By estimating all these paths simultaneously, path and mediation analysis can reveal not just whether SES matters, but how exactly it translates into long-term health inequalities. Let’s examine an example model that can be used to investigate the impact of parents’ education on an individual’s income. The path analysis can be represented in this graph: ![complex path and mediation model](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image-4-1024x625.webp) In this model, we have five variables: parental education, education, IQ score, self-esteem, and respondent income. In such graphs, single-headed arrows represent regression slopes. For example, the arrow from parental education to income (labelled “f”) represents a regression slope. Squares with arrows coming toward them are outcomes in regression equations, while those from which arrows leave are the predictors. In this model, we have three regressions: 1. Education (“edu”) is explained by parental education (arrow “c”) and IQ (arrow “a”) 2. Self-esteem is explained by education (arrow “b”) 3. Income is explained by parental education (arrow “f”), education (arrow “d”), and self-esteem (arrow “e”) To locate these indirect effects, we can follow the paths in the graph. For example, parental education has an **indirect** effect on self-esteem through education. We can calculate this effect in a path diagram by multiplying the coefficients from the path, in this case, by multiplying the “c” coefficient with “b”. If we look at the effect of parental education on income, we see that it has both a **direct effect** (arrow “f”) and an **indirect effect**. More precisely, there are two possible **indirect effects**: going only through education (arrows “c” and “d”) or going through education and self-esteem (arrows “c”, “b”, and “e”). We can calculate the size of the two indirect effects by multiplying the coefficients on the path. For the first path, this would be equal to *c*∗*d*, while for the second one, it would be *c*∗*b*∗*e*. As we can see, this framework divides the relationships into **direct** and **indirect** effects. Using path analysis we can also sum these effects up to calculate the **total effect** of a variable on another. To do this, we add the direct and the indirect effects. For example, for the relationship between parental education and income, we have: \\( total\_{parent\_edu \\rightarrow income} = direct + indirect = f + c \\times d + c \\times b \\times e \\) If arrows are absent in path/SEM diagrams, we expect the relationship between those two variables to be 0. For example, the fact that we do not include an arrow from parental education to IQ implies that we fix this relationship to be 0 (so, no relationship). Such decisions regarding which regression coefficients to include and which to fix to 0 can be based on theory and prior empirical results. ## Using R and `lavaan` to estimate direct and indirect effects To make these ideas more concrete, let’s look at a real example using the [Understanding Society](https://www.understandingsociety.ac.uk/) dataset. Here, we aim to determine whether education level (“degree”) directly influences mental health (SF-12 MCS score) or if part of this effect is mediated through income. This is a classic mediation problem: education may improve health partly because it increases income, which in turn shapes mental well-being. Before running the model, we need to perform some data cleaning. The `lavaan` package does not always work well with factors. To make sure the coding is correct, we will make a new version of the “degree” variable that will be coded as a dummy (1 or 0) to make it easier to interpret: ``` usw <- mutate(usw, degree = ifelse(degree.fct == "Degree", 1, 0)) count(usw, degree.fct, degree) ``` ``` ## # A tibble: 3 × 3 ## degree.fct degree n ## ## 1 Degree 1 16547 ## 2 No degree 0 34349 ## 3 NA 111 ``` Now we can run our path model. We will first write down the equations, then use the `sem()` command to estimate the model, and finally, look at the results. ``` library(lavaan) model <- 'sf12mcs_1 ~ degree logincome_1 ~ degree sf12mcs_1 ~ logincome_1' fit <- sem(model, data = usw) summary(fit, standardized = T) ``` ``` ## lavaan 0.6-19 ended normally after 1 iteration ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 5 ## ## Used Total ## Number of observations 47350 51007 ## ## Model Test User Model: ## ## Test statistic 0.000 ## Degrees of freedom 0 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree 1.003 0.101 9.891 0.000 1.003 0.047 ## logincome_1 ~ ## degree 0.737 0.015 50.647 0.000 0.737 0.227 ## sf12mcs_1 ~ ## logincome_1 0.162 0.031 5.211 0.000 0.162 0.025 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .sf12mcs_1 102.222 0.664 153.867 0.000 102.222 0.997 ## .logincome_1 2.224 0.014 153.867 0.000 2.224 0.949 ``` The results show an interesting pattern. Education has a direct association with mental health, with the coefficient of 1.003 indicating that people with higher education report slightly higher mental health scores. At the same time, education is strongly and positively related to income, with a coefficient of 0.737 for logged income. Income, in turn, shows a positive effect on mental health, with a coefficient of 0.162. Taken together, these findings suggest that education shapes mental health both directly and indirectly through its effect on income. The output is informative, but it can be challenging to understand at times. The semPlot package provides a neat way to visualize the mediation model as a path diagram: ``` library(semPlot) semPaths( fit, what = "path", whatLabels = "est", residuals = FALSE, rotation = 2, ) ``` ![R lavaan mediation analysis output showing path coefficients from education to income to mental health.](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image-5-1024x731.webp) This diagram shows variables as boxes, arrows as paths, and estimated coefficients on each line. It provides a quick overview of the strength of each effect and which pathways are statistically significant. One of the biggest advantages of path and mediation analysis is that it allows us to decompose effects into direct, indirect, and total components. Instead of manually multiplying coefficients, we can tell `lavaan` to calculate these quantities for us. This has the advantage of also calculating standard errors and p-values. For this, we need to label the main paths in the model and explicitly define the indirect and total effects. In this specification, the paths are labeled “a”, “b”, and “c”, which makes it easy to refer to them when calculating the effects. The indirect effect of education on mental health through income is expressed as the product of “a” and “b”, while the total effect is defined as the sum of the direct effect “c” and the indirect effect. ``` model <- 'sf12mcs_1 ~ c*degree logincome_1 ~ a*degree sf12mcs_1 ~ b*logincome_1 # indirect effect (a*b) ab := a*b # total effect total := c + (a*b)' fit <- sem(model, data = usw) summary(fit, standardized = T) ``` ``` ## lavaan 0.6-19 ended normally after 1 iteration ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 5 ## ## Used Total ## Number of observations 47350 51007 ## ## Model Test User Model: ## ## Test statistic 0.000 ## Degrees of freedom 0 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree (c) 1.003 0.101 9.891 0.000 1.003 0.047 ## logincome_1 ~ ## degree (a) 0.737 0.015 50.647 0.000 0.737 0.227 ## sf12mcs_1 ~ ## logincom_1 (b) 0.162 0.031 5.211 0.000 0.162 0.025 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .sf12mcs_1 102.222 0.664 153.867 0.000 102.222 0.997 ## .logincome_1 2.224 0.014 153.867 0.000 2.224 0.949 ## ## Defined Parameters: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## ab 0.120 0.023 5.184 0.000 0.120 0.006 ## total 1.122 0.099 11.365 0.000 1.122 0.052 ``` The results are the same as before, but we now also obtain the indirect and total effects. The indirect effect, calculated as the product of the path from education to income and the path from income to mental health, is 0.120. When the direct and indirect effects are combined, the total effect amounts to 1.122, confirming that the overall influence of education on mental health in this model is positive and that most of the relationship comes from the direct effect. This illustrates the strength of mediation analysis: rather than stopping at a single regression, we can break down how much of the effect flows directly versus indirectly, which helps answer questions about mechanisms and pathways. ## Expanding path models for mediation Path analysis can be extended in many different directions. We can add control variables, include multiple mediators, model sequential processes, or move toward full structural equation modeling with latent variables. Each of these extensions helps us answer more realistic questions about social processes. ### Including control variables In real-world research based on observational data, it’s rarely enough to only consider the main variables of interest. Other factors may also influence both the mediator and the outcome. If we don’t control for these, our mediation results might be biased. Extending the model to include these controls makes the results more credible. As an example of how we can extend the model, here is the updated version with controls for age and gender. The focus remains on the direct and indirect effects, but now we are accounting for these two confounders. ``` model <- 'sf12mcs_1 ~ c*degree + age + gndr.fct logincome_1 ~ a*degree + age + gndr.fct sf12mcs_1 ~ b*logincome_1 + age + gndr.fct # indirect effect (a*b) ab := a*b # total effect total := c + (a*b)' fit2 <- sem(model, data = usw) summary(fit2, standardized = T) ``` ``` ## lavaan 0.6-19 ended normally after 1 iteration ## ## Estimator ML ## Optimization method NLMINB ## Number of model parameters 9 ## ## Used Total ## Number of observations 47350 51007 ## ## Model Test User Model: ## ## Test statistic 0.000 ## Degrees of freedom 0 ## ## Parameter Estimates: ## ## Standard errors Standard ## Information Expected ## Information saturated (h1) model Structured ## ## Regressions: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## sf12mcs_1 ~ ## degree (c) 1.200 0.102 11.796 0.000 1.200 0.056 ## age 0.033 0.003 12.499 0.000 0.033 0.058 ## gndr.fct -1.684 0.094 -17.972 0.000 -1.684 -0.083 ## logincome_1 ~ ## degree (a) 0.787 0.014 55.124 0.000 0.787 0.242 ## age 0.015 0.000 41.489 0.000 0.015 0.182 ## gndr.fct -0.315 0.013 -23.353 0.000 -0.315 -0.102 ## sf12mcs_1 ~ ## logincom_1 (b) 0.029 0.032 0.905 0.365 0.029 0.004 ## ## Variances: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## .sf12mcs_1 101.208 0.658 153.867 0.000 101.208 0.987 ## .logincome_1 2.121 0.014 153.867 0.000 2.121 0.905 ## ## Defined Parameters: ## Estimate Std.Err z-value P(>|z|) Std.lv Std.all ## ab 0.023 0.025 0.905 0.365 0.023 0.001 ## total 1.222 0.099 12.398 0.000 1.222 0.057 ``` Adding age and gender as control variables changes the picture in several ways. The direct effect of education on mental health becomes slightly stronger, from 1.003 to 1.200. The effect of education on income also increases slightly, from 0.737 to 0.787. By contrast, the link between income and mental health, which was previously significant, is now very weak and not statistically different from zero. As a result, the indirect effect of education on income is no longer significant, suggesting that what appeared to be mediation before was largely explained by age and gender. The total effect of education on mental health remains close to its earlier value, at 1.222 compared with 1.122, confirming that education continues to predict mental health overall. The controls themselves seem to be important, with older individuals reporting slightly higher mental health and income, while women report both lower mental health and lower income. In short, without controls, we saw evidence of mediation through income. With controls, the mediation path disappears, indicating that part of what appeared to be mediation was actually due to age and gender differences. This illustrates why including controls is crucial in applied path analysis; otherwise, we risk attributing indirect effects to the wrong mechanisms. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ### More complex mediation pathways in path analysis So far, we’ve looked at a basic mediation model with a single mediator. But real social processes are rarely that simple. Often, multiple pathways connect predictors and outcomes. For example, education may affect health not only through income but also through factors such as life satisfaction, which can be influenced by income. By allowing for multiple mediators, path analysis can capture a more realistic web of relationships. In the model below, we extend the analysis by adding life satisfaction (sati\_1) as a second mediator: ![Multiple mediation pathways in R path analysis: education affects income, satisfaction, and mental health through several indirect effects](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image-2-1024x775.webp) In this extended path analysis, education influences both income and life satisfaction directly, with paths from degree to income and from degree to satisfaction. Income, in turn, is specified as a predictor of life satisfaction, which creates a sequential pathway from education to income to satisfaction. Both income and satisfaction are then allowed to affect mental health, capturing two additional routes through which education can have an impact. To make these mechanisms explicit, three indirect effects are defined: the pathway from education through income to mental health, the longer chain from education through income, satisfaction, and then to mental health, and the route from education directly to satisfaction and then to mental health. The total effect is then calculated as the sum of the direct path and all of these indirect components, giving a complete picture of how education influences mental health across multiple pathways. Here is the code for running such a model: ``` model <- ' sf12mcs_1 ~ c*degree logincome_1 ~ a*degree sati_1 ~ d*degree + e*logincome_1 sf12mcs_1 ~ b*logincome_1 + f*sati_1 # indirect effects ab := a*b aef := a*e*f df := d*f # total effect total := c + ab + aef + df ' fit3 <- sem(model, data = usw) summary(fit3) ``` Running this extended model shows how the effect of education is distributed across several pathways. Education continues to have a direct association with mental health, while income provides one route of mediation on its own. A second, more complex chain emerges when income influences satisfaction, which in turn contributes to mental health, capturing the idea that education indirectly shapes well-being through both economic and psychological channels (although this is not significant here). There is also a pathway in which education directly affects satisfaction, which in turn influences mental health. By summing these together, the total effect of education reflects both its direct role and its various indirect contributions. Rather than focusing only on a single route, this approach reveals how education exerts its influence through multiple overlapping processes, offering a more nuanced understanding of the mechanisms that sustain social inequalities. The semPlot package can again help make sense of this more complex diagram: ``` semPaths( fit3, what = "path", whatLabels = "est", residuals = FALSE, rotation = 2, edge.label.cex = 1.2, nCharNodes = 10, nCharEdges = 5, label.cex = 1.2, sizeMan = 8 ) ``` ![Comprehensive path and mediation analysis diagram in R illustrating direct and indirect effects of education on mental health through income and satisfaction](https://longitudinalanalysis.com/wp-content/uploads/2025/09/image-3-1024x731.webp) The plot clearly shows multiple mediators and pathways, with the estimated coefficients displayed on each arrow. Visualizing these models is especially useful once they become more complex, as it helps to see at a glance how the variables connect. ## Conclusions on path models and mediation Mediation and path analysis allow us to move beyond simple regression and uncover the mechanisms that link predictors and outcomes. In this post, we examined how education can impact mental health both directly and indirectly, and how these pathways are altered when control variables are introduced or multiple mediators are considered. The ability to separate effects into direct, indirect, and total components makes path analysis a powerful tool for testing theories in the social sciences. ## Want to learn more? Check [our on-demand course on moderation and mediation](https://leanpub.com/c/mediation-moderation-r). [Explore course](https://leanpub.com/c/mediation-moderation-r) At the same time, the examples here were based on cross-sectional data, which only capture relationships at a single point in time. Many of the most interesting questions are longitudinal in nature. We may want to know how changes in education, income, or life satisfaction affect mental health across the life course, whether early-life advantages accumulate to shape outcomes years later, or whether mediation effects are stable across different stages of life. Path analysis naturally extends to longitudinal models such as autoregressive models, [cross-lagged panel models](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/), and [latent growth models](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/). These approaches allow us to investigate not only whether mediation occurs, but also when and how it unfolds over time. In future posts, we will explore these longitudinal extensions and demonstrate how the same principles of direct and indirect effects can be applied to repeated measures data, thereby opening the way to richer insights into how social processes develop. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** longitudinal data analysis, visualization **Tags:** longitudinal data analysis, mediation, path analysis, r, structural equation modelling --- ### [Mixture Latent Growth Models R: A Step-by-Step Guide](https://longitudinalanalysis.com/mixture-latent-growth-models-r-a-step-by-step-guide/) **Published:** February 24, 2025 **Author:** Alex Cernat **Excerpt:** The blog post discusses Mixture Latent Growth Models (MLGM) that enhance traditional longitudinal models by identifying latent subgroups with distinct trajectories over time. It details the implementation of MLGM in R using the tidySEM package and compares results from using R and Mplus for improved understanding of individual and aggregate changes. **Content:** Longitudinal models, such as the [latent growth model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) and the [multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/), enable us to examine both individual and aggregate change over time. This gives us a more nuanced understanding of how individuals, organizations and societies change. However, these models assume one aggregate or average rate of change in time. In reality, there may be subgroups of individuals who follow different trajectories. Often, we do not know what these groups are in advance and identifying them can significantly improve our understanding of what is happening in the data and help us develop theories and interventions. Mixture Latent Growth Models (MLGM) can identify latent or underlying subgroups and model their unique trajectories. This blog post will explore how to fit MLGM in R, visualize the latent classes, and interpret the results. ## Preparing the data for analysis We start by preparing the data. We will look at satisfaction over four waves of data. We will use the wide version of the Understanding Society data (“usw”) to explore the different types of trajectories in satisfaction (more on how to prepare the data in [this previous post](https://longitudinalanalysis.com/cleaning-longitudinal-data-in-r-a-step-by-step-guide/)). Here, satisfaction is measured on a scale from 1 to 7, with higher values indicating higher satisfaction levels. We will also use the `tidySEM` package to run the models. This package is a wrapper for the `OpenMx` package, which can run MLGM in R but has a more complex syntax. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! We start by loading the packages (we assume they have already been installed). ``` library(tidyverse) library(tidySEM) ``` We then load the cleaned data from the “data” subfolder in our working directory: ``` load("./data/us_clean_syn.RData") ``` We will select the necessary variables to make the models easier to run. ``` df <- dplyr::select(usw, pidp, starts_with("sati_")) ``` We will also take a subsample of 3000 individuals to estimate the models faster (using `sample_n()`). The `set.seed()` command will allow us to reproduce the results (you will have the same results if you try to run the code). ``` set.seed(1234) df_small <- sample_n(df, 3000) ``` ## What is the Mixture Latent Growth Mixture Model? Understanding how individuals change over time is a central goal in longitudinal research. Traditional [Latent Growth Models](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) (LGM) assume that aggregate change follows a trajectory, with variation captured through random effects. However, in many real-world applications—such as education, health, and behavioural sciences—subpopulations may exist with distinct patterns of change. A single growth trajectory may not adequately represent these subgroups. Mixture Latent Growth Models (MLGM) extend traditional LGM by incorporating latent class analysis. They allow us to identify unobserved subgroups that follow different trajectories. Instead of assuming one common trajectory, MLGM assigns individuals probabilistically to latent classes, each characterised by its growth parameters. This provides a more nuanced understanding of heterogeneity in longitudinal data. We can visualise the model using an SEM diagram: ![SEM diagram of mixure latent growth model](https://longitudinalanalysis.com/wp-content/uploads/2025/02/image-1024x893.png) The figure represents the structure of an MLGM. It extends a [standard latent growth curve](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) model by introducing a latent categorical variable (*ηc*) that accounts for subgroup membership. The model includes the following components: - Observed variables (y1, y2, y3, y4): These are repeated measures collected over time. - Latent intercept (*η*0) and slope (*η*1): These capture individual differences in the starting point and rate of change over time. - Factor loadings (numbers on the paths): The intercept (*η*0) is linked to all time points with a loading of 1, representing a baseline level. The slope (*η*1) has loadings increasing over time (e.g., 0, 1, 2, 3), reflecting linear growth. - Latent class variable (*ηc*): This dashed-line path indicates that class membership influences the intercept and slope, meaning each subgroup has different initial levels and rates of change. - Residual errors (*ϵ*1, *ϵ*2, *ϵ*3, *ϵ*4): These represent measurement errors or unexplained variance in observed outcomes. In summary, the Mixture Latent Growth Model allows us to account for heterogeneous trajectories within a population by estimating separate growth parameters for each latent class. This approach is valuable in identifying subgroups that may respond differently to interventions or exhibit unique developmental patterns over time. ## Running Mixture Latent Growth Models in R We will initially use the `TidySEM` package to run this model. This package is a wrapper for the `OpenMx` package, which can run a wide range of models in R. We use `TidySEM` here because its syntax is simpler than the one in `OpenMx`. We can start by creating a model using a similar syntax to that from `lavaan` (see an explanation of code in [this blogpost](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/)). ``` model <- 'i_sati =~ 1*sati_1 + 1*sati_2 + 1*sati_3 + 1*sati_4 s_inc =~ 0*sati_1 + 1*sati_2 + 2*sati_3 + 3*sati_4' ``` The typical procedure for Mixture LGM is to run models with different numbers of classes and then compare them. We can use the results and fit indices to decide which model to select and interpret further. We can run multiple models using the `mx_growth_mixture()` function. This will run multiple models with different numbers of classes. Here, we will run models with 1 to 4 classes. ``` res_step <- mx_growth_mixture( model = model, classes = 1:4, data = df_small) ``` The model with four classes had some estimation issues, so we can try running it a few more times to see if it helps. ``` res_step[[4]] <- mxTryHardWideSearch(res_step[[4]], extraTries = 200) ``` Once the model has run, we can look at the model fit: ``` tab_fit <- table_fit(res_step) tab_fit ``` ``` ## Name Classes LL n Parameters AIC BIC saBIC Entropy ## 1 1 1 -12540.12 3000 9 25098.23 25152.29 25123.69 1.0000000 ## 2 2 2 -11258.28 3000 19 22554.56 22668.68 22608.31 0.6228562 ## 3 3 3 -11079.30 3000 29 22216.60 22390.78 22298.64 0.5570806 ## 4 4 4 -12540.12 3000 39 25158.23 25392.48 25268.56 1.0000000 ## prob_min prob_max n_min n_max np_ratio np_local ## 1 1.0000000 1.0000000 1.0000000 1.0000000 333.33333 333.33333 ## 2 0.8364136 0.8969973 0.4320000 0.5680000 157.89474 144.00000 ## 3 0.4428439 0.9442728 0.1133333 0.5423333 103.44828 37.77778 ## 4 NA NA 0.0000000 1.0000000 76.92308 0.00000 ``` The results for the four-class model seem suspect. We can explore the estimation by looking at the status and warnings. ``` res_step[[4]]$output$status ``` ``` ## $code ## [1] 0 ## ## $status ## [1] 0 ``` ``` res_step[[4]]$output$warnings ``` ``` ## NULL ``` While it appears the model has converged, the results again look strange. If we look at the class probabilities, we can see that three classes have no members (count and proportions are very close to 0). This is a sign that the model may not be reliable, as it basically allocated everyone to one class. ``` class_prob(res_step[[4]])[[1]] ``` ``` ## class count proportion ## 1 class1 7.210771e-08 2.403590e-11 ## 2 class2 3.468490e-08 1.156163e-11 ## 3 class3 3.000000e+03 1.000000e+00 ## 4 class4 2.102998e-07 7.009994e-11 ``` On the other hand, the model with three classes seems to have better class distribution. We can look at the results of this model. ``` class_prob(res_step[[3]])[[1]] ``` ``` ## class count proportion ## 1 class1 602.4605 0.2008202 ## 2 class2 1155.8228 0.3852743 ## 3 class3 1241.7167 0.4139056 ``` To make the comparison between the models easier to interpret, we can extract the model fit indices we want. In general, lower BIC values are associated with better-fitting models. On the other hand, entropy, a measure of classification accuracy, should be close to 1. ``` tab_fit[c("Classes", "LL", "BIC", "Entropy")] ``` ``` ## Classes LL BIC Entropy ## 1 1 -12540.12 25152.29 1.0000000 ## 2 2 -11258.28 22668.68 0.6228562 ## 3 3 -11079.30 22390.78 0.5570806 ## 4 4 -12540.12 25392.48 1.0000000 ``` Based on the fit indices, we will select the model with three classes for now. However, because entropy is relatively low (ideally, it should be above 0.9), the classification may not be very accurate. This means that for some individuals, we are not sure in what class they belong. We can extract the results of the three-class model using the `table_results()` function. This gives quite a large output. To focus on the things we care the most about, we can extract just the “means” part of the model using a combination of `filter()` and `str_detect()`. ``` table_results(res_step[[3]]) |> filter(str_detect(label, "Means")) ``` ``` ## label est_sig se pval confint class ## 1 Means.i_sati 6.01*** 0.05 0.00 [5.91, 6.11] class1 ## 2 Means.s_inc -0.61*** 0.03 0.00 [-0.68, -0.55] class1 ## 3 Means.i_sati 3.92*** 0.07 0.00 [3.78, 4.05] class2 ## 4 Means.s_inc 0.15*** 0.04 0.00 [0.07, 0.22] class2 ## 5 Means.i_sati 6.03*** 0.02 0.00 [5.99, 6.07] class3 ## 6 Means.s_inc -0.00 0.01 0.81 [-0.02, 0.02] class3 ``` We see that classes 1 and 3 start with relatively high levels of satisfaction, but while class 1 decreases in satisfaction, class 3 is stable. On the other hand, class 2 starts much lower (3.92) and has a slight improvement in time (0.15) per wave. In a previous table, we saw that class 3 is the largest one (41%), while class 1 is the lowest, with 20% of the sample. To facilitate interpretation, we can also plot the trajectories using `plot_growth()` from the `tidySEM` package. ``` plot_growth(res_step[[3]], rawdata = TRUE, alpha_range = c(0, .05)) ``` ![trajectories of a 3 class mixture latent class model in R](https://longitudinalanalysis.com/wp-content/uploads/2025/02/Untitled-1024x731.png) We see the trends described in the previous table. Now, it also becomes obvious that class 1 members will end up having lower satisfaction levels than those in class 2, even if they start with significantly higher levels. ## Running Mixture Latent Growth Models in R using MplusAutomation and MplusLGM Unfortunately, the R packages for running mixture models still have some limitations. If the data is complex or we have estimation issues (like we had in the 4-class model above), one alternative is to use Mplus, specialised software for latent variable modelling. Unfortunately, this is not free or open source. If you do have Mplus, then models can be run from R directly using the `MplusAutomation` and `MplusLGM` packages. Let’s start by loading the packages: ``` library(MplusLGM) library(MplusAutomation) ``` The code for running Latent Growth Models in Mplus is slightly different from the one in `lavaan`. We will run the model using the `fitGBTM()` function. This facilitates running multiple models with different number of classes. The code below runs a similar model to the one before in Mplus. ``` mixture_model <- fitGBTM( data = df_small, outvar = c("sati_1", "sati_2", "sati_3", "sati_4"), idvar = "pidp", starting_val = 500, min_k = 1L, max_k = 5L, timescores = c(0, 1, 2, 3), polynomial = 1, output = c("TECH1", "TECH11", "SAMPSTAT", "STANDARDIZED") ) ``` Similarly to what we did before, we can start by comparing the fit indices of the models: ``` fit_indices <- getFit(mixture_model) fit_indices ``` ``` ## Title Observations Parameters NLatentClasses LL BIC ## 1 GBTM_P1_K1_S1000; 2644 3 1 -12906.05 25835.74 ## 2 GBTM_P1_K2_S1000; 2644 6 2 -12380.40 24808.07 ## 3 GBTM_P1_K3_S1000; 2644 9 3 -12201.53 24473.98 ## 4 GBTM_P1_K4_S1000; 2644 12 4 -12157.95 24410.47 ## 5 GBTM_P1_K5_S1000; 2644 15 5 -12150.26 24418.73 ## aBIC AIC AICC CAIC T11_LMR_Value T11_LMR_PValue count_1 ## 1 25826.20 25818.10 25818.10 25838.73 NA NA 2644 ## 2 24789.01 24772.79 24772.83 24814.07 1008.635 0.00 611 ## 3 24445.38 24421.06 24421.12 24482.98 343.219 0.00 413 ## 4 24372.34 24339.91 24340.03 24422.47 83.610 0.00 368 ## 5 24371.07 24330.53 24330.71 24433.73 14.759 0.05 352 ## count_2 count_3 count_4 count_5 proportion_1 proportion_2 proportion_3 ## 1 NA NA NA NA 100.00 NA NA ## 2 2033 NA NA NA 23.11 76.89 NA ## 3 316 1915 NA NA 15.62 11.95 72.43 ## 4 1847 219 210 NA 13.92 69.86 8.28 ## 5 62 237 168 1825 13.31 2.34 8.96 ## proportion_4 proportion_5 Proportion_criterion APPA1 APPA2 APPA3 APPA4 APPA5 ## 1 NA NA pass 1.000 NA NA NA NA ## 2 NA NA pass 0.878 0.937 NA NA NA ## 3 NA NA pass 0.844 0.800 0.891 NA NA ## 4 7.94 NA pass 0.775 0.874 0.714 0.653 NA ## 5 6.35 69.02 fail 0.746 0.645 0.591 0.641 0.871 ## APPA_criterion Entropy Entropy_criterion ## 1 pass NA pass ## 2 pass 0.726 pass ## 3 pass 0.704 pass ## 4 fail 0.698 pass ## 5 fail 0.703 pass ## Warnings ## 1 All continuous latent variable covariances involving I have been fixed to 0 because the variance of I is fixed at 0. TECH11 option is not available for TYPE=MIXTURE with only one class. Request for TECH11 is ignored. Data set contains cases with missing on all variables. These cases were not included in the analysis. Number of cases with missing on all variables: 356 3 WARNING(S) FOUND IN THE INPUT INSTRUCTIONS ## 2 All continuous latent variable covariances involving I have been fixed to 0 because the variance of I is fixed at 0. Data set contains cases with missing on all variables. These cases were not included in the analysis. Number of cases with missing on all variables: 356 2 WARNING(S) FOUND IN THE INPUT INSTRUCTIONS ## 3 All continuous latent variable covariances involving I have been fixed to 0 because the variance of I is fixed at 0. Data set contains cases with missing on all variables. These cases were not included in the analysis. Number of cases with missing on all variables: 356 2 WARNING(S) FOUND IN THE INPUT INSTRUCTIONS ## 4 All continuous latent variable covariances involving I have been fixed to 0 because the variance of I is fixed at 0. Data set contains cases with missing on all variables. These cases were not included in the analysis. Number of cases with missing on all variables: 356 2 WARNING(S) FOUND IN THE INPUT INSTRUCTIONS ## 5 All continuous latent variable covariances involving I have been fixed to 0 because the variance of I is fixed at 0. Data set contains cases with missing on all variables. These cases were not included in the analysis. Number of cases with missing on all variables: 356 2 WARNING(S) FOUND IN THE INPUT INSTRUCTIONS ## Errors ## 1 ## 2 ## 3 ## 4 ## 5 ``` Again, we get quite a lot of fit indices, so we can concentrate on the main ones: ``` fit_indices |> select(NLatentClasses, LL, BIC, Entropy, starts_with("Proportion_cri")) ``` ``` ## NLatentClasses LL BIC Entropy Proportion_criterion ## 1 1 -12906.05 25835.74 NA pass ## 2 2 -12380.40 24808.07 0.726 pass ## 3 3 -12201.53 24473.98 0.704 pass ## 4 4 -12157.95 24410.47 0.698 pass ## 5 5 -12150.26 24418.73 0.703 fail ``` Based on these indicators, we can decide which model to choose. For example, the four-class model has the lowest BIC value, but the entropy is quite low. We also see that the five-class model has a class with a very low proportion (below 5%). Alternatively, the `MplusLGM` package has a command to help us with the decision-making (`getBest()`). Here, we ask it to select the best model based on the BIC and the adjusted Likelihood Ratio Test: ``` LGM_best <- getBest( lgm_object = mixture_model, ic = "BIC", lrt = "aLRT", p = 0.05 ) LGM_best ``` ``` ## [[1]] ## GBTM_P1_K4_S1000 ## ## Estimated using MLR ## Number of obs: 2644, number of (free) parameters: 12 ## ## Fit Indices: ## ## CFI = NA, TLI = NA, SRMR = NA ## RMSEA = NA, 90% CI [NA, NA], p < .05 = NA ## AIC = 24339.91, BIC = 24410.47 ## NULL ``` This would indicate the selection of the four-class model based on the criteria we gave. We can see how large the classes are in the selected model by extracting the table of interest from the output: ``` mixture_model[[4]]$results$class_counts$posteriorProb ``` ``` ## class count proportion ## 1 1 483.5599 0.18289 ## 2 2 1677.2632 0.63437 ## 3 3 234.2893 0.08861 ## 4 4 248.8876 0.09413 ``` The majority of cases are in class 2 (63%), while classes 3 and 4 have below 10% of the sample. We can extract the means of the classes from the output to see how their trajectories are different: ``` table_results(mixture_model[[4]]) |> filter(str_detect(label, "Means")) ``` ``` ## label est_sig se pval confint ## 1 Means.C#1 0.66*** 0.16 0.00 [ 0.35, 0.98] ## 2 Means.C#2 1.91*** 0.15 0.00 [ 1.62, 2.20] ## 3 Means.C#3 -0.06 0.28 0.83 [-0.60, 0.48] ## 4 Means.I 5.46*** 0.09 0.00 [ 5.28, 5.64] ## 5 Means.I 5.82*** 0.03 0.00 [ 5.77, 5.88] ## 6 Means.I 2.65*** 0.16 0.00 [ 2.33, 2.97] ## 7 Means.I 3.07*** 0.15 0.00 [ 2.78, 3.36] ## 8 Means.S -0.83*** 0.04 0.00 [-0.92, -0.75] ## 9 Means.S -0.04** 0.01 0.00 [-0.06, -0.01] ## 10 Means.S 0.22* 0.10 0.02 [ 0.03, 0.42] ## 11 Means.S 0.79*** 0.07 0.00 [ 0.65, 0.93] ``` We see that the first two classes start with high levels of satisfaction while the others start with relatively low levels. Class 1 significantly decreases its satisfaction, while classes 3 and 4 increase it. Again, we can graph the trajectories for the different classes using the `plotGrowthMixtures()` function from the `MplusAutomation` package. ``` plotGrowthMixtures( LGM_best, bw = FALSE, rawdata = TRUE, alpha_range = c(0, 0.05) ) ``` ![trajectories of a 4 class mixture latent class model in R and Mplus](https://longitudinalanalysis.com/wp-content/uploads/2025/02/image-1-1024x731.png) Now, the patterns are clearer. We see that class 1 has a significant decrease in satisfaction while class 2 is stable in time. Classes 3 and 4 have a more pronounced increase in satisfaction. ## Want to really learn? Follow along using the data and code. Get them when you join the newsletter. Additionally, you will get my 63-point pre-submission checklist for your research. All for free! ## Conclusion In this blog post, we explored how to run Mixture Latent Growth Models in R. We saw how to use the `tidySEM` package to simplify the code needed to run the model (compared to the original `OpenMx` package). We also saw how to run such models using Mplus through R through the `mplusLGM` and `MplusAutomation` packages. Hopefully, this has given you an idea of the possible insights with this model and why it is so popular. The model could be extended by explaining the classes with co-variates or by adding more complex growth patterns. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) --- **Categories:** longitudinal data analysis, visualization **Tags:** latent growth modelling, longitudinal data analysis, Mplus, r, structural equation modelling, visualization --- ### [Merge Data in R: Complete Guide to Joining Datasets](https://longitudinalanalysis.com/merge-data-in-r-complete-guide-to-joining-datasets/) **Published:** March 30, 2026 **Author:** Alex Cernat **Excerpt:** Learn how to merge data when you have information in different files, at different levels and at multiple time points. Explore four real-world scenarios **Content:** When working with more complex data, information is often stored in different files. For example, individual and neighbourhood data might come from different sources, and you might need to merge data before you can analyse it. Similarly, in panel data, we might have individual and household-level data as well as data at multiple time points. When accessing the data, each one is typically stored in a separate file. To make the most of this information, we need to merge data at different levels. This can be a complex process, and it is important to do it correctly to avoid mistakes and ensure we use the data as effectively as possible. In this post, I will provide a step-by-step guide to merging data in R, with a focus on panel data. ## Different ways to merge data There are different types of merges or joins possible. In social science, we typically perform a mutating join, which aims to bring information together from multiple sources for analysis. If we use the [tydiverse package](https://tidyverse.org/packages/), these would come in four slightly different flavours. At one extreme, `full_join()` will bring all variables and cases together into a dataset, while at the other, `inner_join()` will keep only cases present in both datasets. In between, we have `left_join()` and `right_join()`, which keep all cases from one dataset and only the matching cases from the other. Here is a visual representation of these different types of joins: ![different ways to merge data in R using mutating joins](https://longitudinalanalysis.com/wp-content/uploads/2026/03/image.webp) Another dimension to consider when joining data is the level at which it happens. The most straightforward approach would be a “1:1” merger, in which each case in one dataset has a unique match in the other. For example, if we have data at two points in time at the individual level can do a 1:1 merger. However, sometimes we also deal with “1:m” or “m:m” mergers. For example, if we have individual-level and household-level data, we would need to perform a “1:m” merger, since multiple individuals can belong to the same household. Similarly, if we have neighbourhood and school data that we want to link to students, we would have a “m:m” merger. In R, the join command identifies the type of join, so we do not need to explicitly specify it. As a result, we need to ensure that the data and IDs are structured correctly before we merge them. ## Merging panel data Longitudinal or panel data can be particularly complex to merge, as they often include data at different levels (e.g., individual, household, neighbourhood) and multiple time points. We will use this to illustrate how to merge data in general. As an example, we will use data from the [Understanding Society](https://www.understandingsociety.ac.uk/documentation/) study to explore the main types of merging you might want to use. This study includes data at different levels. Here we will focus on the following types of data: - “indresp”: individual-level data with answers from the main survey - “hhresp”: household-level data with information about the household - “youth”: survey answers from those between 10 and 15 in the household - “egoalt”: data about the relationships in the household Before merging, it is also important to understand the IDs (sometimes called “keys”). In this case, we can use the following variables: - “pidp”: individual-level ID that can also be used across time - “x\_hidp”: household-level ID that can be used within each point in time but not across time - “x\_pn”: identifies the individual in the household. Could be used in combination with “x\_hidp” to identify individuals, as an alternative to “pidp” - “apidp”: identifies the other person in the relationship file. Could be used in combination with “pidp” to identify the partner, child, sibling, etc. The other thing to keep in mind with this study is that the first letter denotes the first wave, so “a\_indresp” is the wave 1 data, while “b\_indresp” is the second wave. This is also true for the variable names. An exception to this is “pidp”, which is stable in time, so it does not need a prefix. We will explore four different scenarios of merging panel data: 1. add household-level information to individual-level data 2. combine info from the youth data with that from the household and the adults 3. add information about the partner at the individual level data 4. merge across waves We can visualise the data and the different levels in the following way: ![different ways to merge data when you have panel of longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2026/03/image-3.webp) Let’s prepare the ground for our scenarios. We will import the data we want to use (using the `col_select` option to select just the variables of interest) and do some basic cleaning to make it easier to work with: ``` library(tidyverse) library(haven) a_indresp <- read_dta("./data/a_indresp.dta", col_select = all_of(c("pidp", "a_hidp", "a_dvage", "a_sex", "a_marstat_dv", "a_sf12mcs_dv", "a_hiqual_dv"))) a_hhresp <- read_dta("./data/a_hhresp.dta", col_select = all_of(c("a_hidp", "a_hhsize", "a_nkids_dv", "a_hhtype_dv", "a_tenure_dv"))) a_youth <- read_dta("./data/a_youth.dta", col_select = all_of(c("pidp", "a_hidp", "a_yp2uni", "a_ypacvwell", "a_ypargm"))) a_egoalt <- read_dta("./data/a_egoalt.dta") b_indresp <- read_dta("./data/US/UKDA-6614-stata/stata/stata13_se/ukhls/b_indresp.dta", col_select = all_of(c("pidp", "b_hidp", "b_marstat_dv", "b_sf12mcs_dv"))) # some data cleaning a_indresp <- a_indresp |> mutate(a_degree = ifelse(a_hiqual_dv %in% 1:2, T, F), a_partner = ifelse(a_marstat_dv %in% 1:2, T, F), a_sf12mcs = ifelse(a_sf12mcs_dv < 0, NA, a_sf12mcs_dv)) ``` ### Merge data scenario 1: add household-level information to individual-level data The first scenario is the most straightforward one. We want to add household-level information to individual-level data. This is a “1:m” merger, as multiple individuals can belong to the same household. The ID we will use is “a\_hidp”, which is present in both datasets. We will apply the `left_join()` command to keep all cases from the individual-level data and add only the matching cases from the household-level data. We use this strategy because the main unit of analysis for us is the individual, and we want to retain all individuals in our data. If we used an `inner_join(),` we would lose all the individuals that do not have a match in the household-level data. Similarly, if we used a `full_join(),` we would get many missing values in the household-level variables for individuals who do not have a match in the household data. The command is pretty straightforward once we understand what we are doing: ``` a_ind_hh <- left_join(a_indresp, a_hhresp, by = "a_hidp") glimpse(a_ind_hh) ``` ``` ## Rows: 50,994 ## Columns: 14 ## $ pidp 68001367, 68004087, 68006127, 68006135, 68006807, 6800748… ## $ a_hidp 68001363, 68004083, 68006123, 68006123, 68006803, 680… ## $ a_sex 1, 1, 2, 2, 2, 2, 1, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2,… ## $ a_dvage 39, 59, 39, 17, 72, 57, 59, 25, 22, 38, 51, 51, 31, 2… ## $ a_marstat_dv 6, 4, 2, 6, 4, 1, 1, 6, 6, 1, 1, 3, 6, 6, 4, 6, 4, 6,… ## $ a_hiqual_dv 3, 2, 4, 2, 9, 2, 3, 3, 3, 4, 3, 5, 2, 3, 1, 3, 1, 9,… ## $ a_sf12mcs_dv 61.13, 58.17, 26.66, 41.58, 43.89, 59.53, -7.00, -7.0… ## $ a_degree FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALS… ## $ a_partner FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALS… ## $ a_sf12mcs 61.13, 58.17, 26.66, 41.58, 43.89, 59.53, NA, NA, NA, 24.… ## $ a_hhsize 1, 1, 4, 4, 1, 4, 4, 4, 4, 2, 2, 1, 1, 1, 2, 2, 1, 4,… ## $ a_hhtype_dv 3, 3, 11, 11, 2, 19, 19, 19, 19, 6, 6, 3, 3, … ## $ a_nkids_dv 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,… ## $ a_tenure_dv 2, 7, 6, 6, 2, 2, 2, 2, 2, 1, 1, 2, 2, 3, 6, 6, 2, 6,… ``` Now we have a combination of individual and household-level data. We can use this information to explore how individual and household-level information explain outcomes of interest. For example, let’s imagine we want to see how the mental health of individuals (measured by “a\_sf12mcs” from the individual-level data) differs for those with children in the household (measured by “a\_nkids\_dv” from the household-level data). We can do this by grouping the data by whether they have children and then calculating the average mental health score for each group. ``` a_ind_hh |> group_by(a_nkids_dv > 0) |> summarise(mean_sf12mcs = mean(a_sf12mcs, na.rm = T), n = n()) ``` ``` ## # A tibble: 2 × 3 ## `a_nkids_dv > 0` mean_sf12mcs n ## ## 1 FALSE 50.8 32968 ## 2 TRUE 49.8 18026 ``` In this case, it appears that people who have children in the household have lower mental health on average. This is just an example, but it shows how we can use the merged data to explore interesting research questions. ### Merge data scenario 2: add info to youth data from household and adult In addition to the individual-level interview, Understanding Society also collects data from those aged 10 to 15 in the household. This is stored in the file called “youth”. When analysing this kind of data, we might want to explore how context, such as the household, influenced the outcomes of interest for the youth. We could get this kind of information in two ways. First, we could merge the youth data with the household-level data. This is similar to what we did above with the main individual data. In this case, the code would be: ``` a_youth_hh <- left_join(a_youth, a_hhresp, by = "a_hidp") glimpse(a_youth_hh) ``` ``` ## Rows: 4,899 ## Columns: 9 ## $ pidp 68006139, 68026539, 68028579, 68028583, 68028587, 68029935… ## $ a_hidp 68006123, 68026523, 68028563, 68028563, 68028563, 68029923… ## $ a_ypargm 4, 4, 2, 1, 4, 3, 4, 2, 3, 3, 3, 3, 4, 4, 2, 4, 4, 4, … ## $ a_ypacvwell 1, 2, 1, 3, 1, 2, 1, 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 1, … ## $ a_yp2uni 1, 1, 1, -9, 1, 1, 1, 1, 1, 1, -8, 1, 1, -8… ## $ a_hhsize 4, 5, 6, 6, 6, 4, 2, 3, 5, 4, 5, 5, 4, 4, 4, 3, 5, 4, … ## $ a_hhtype_dv 11, 12, 12, 12, 12, 11, 4, 10, 12, 20, 20, 20, 5, 5… ## $ a_nkids_dv 1, 2, 3, 3, 3, 2, 1, 1, 3, 1, 2, 2, 3, 3, 3, 1, 2, 2, … ## $ a_tenure_dv 6, 6, 2, 2, 2, 2, 7, 1, 3, 2, 2, 2, 3, 3, 6, 2, 2, 2, … ``` The second way to get household information is to **aggregate** data from the main interview with adults and then merge it with the youth data. For example, we could take the “a\_degree” variable from the main interview and, for each household, calculate whether at least one person has a degree and the proportion of people who do. This would give us a different perspective on the household context. Here, we group the data by “a\_hidp” and use `transmute()` to create new variables that summarise the information about the degree in the household. The first variable, “a\_onedegree”, is a binary indicator of whether at least one person in the household has a degree. The second variable “a\_avg\_degree” is the proportion of individuals with a degree. We then filter the data to keep only one row per household (using `row_number() == 1`) and ungroup it. ``` a_agg <- a_indresp |> group_by(a_hidp) |> transmute(a_onedegree = sum(a_degree, na.rm = T) > 0, a_avg_degree = mean(a_degree, na.rm = T)) |> filter(row_number() == 1) |> ungroup() glimpse(a_agg) ``` ``` ## Rows: 30,035 ## Columns: 3 ## $ a_hidp 68001363, 68004083, 68006123, 68006803, 68007483, 680… ## $ a_onedegree FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE… ## $ a_avg_degree 0.00, 1.00, 0.50, 0.00, 0.25, 0.00, 0.00, 1.00, 0.00, 0.5… ``` Now we can link this information to the youth data using `left_join()`, since we want to keep all cases from the youth data and only add matching cases from the aggregated data. ``` a_youth_hh2 <- left_join(a_youth_hh, a_agg, by = "a_hidp") glimpse(a_youth_hh2) ``` ``` ## Rows: 4,899 ## Columns: 11 ## $ pidp 68006139, 68026539, 68028579, 68028583, 68028587, 6802993… ## $ a_hidp 68006123, 68026523, 68028563, 68028563, 68028563, 680… ## $ a_ypargm 4, 4, 2, 1, 4, 3, 4, 2, 3, 3, 3, 3, 4, 4, 2, 4, 4, 4,… ## $ a_ypacvwell 1, 2, 1, 3, 1, 2, 1, 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 1,… ## $ a_yp2uni 1, 1, 1, -9, 1, 1, 1, 1, 1, 1, -8, 1, 1, -… ## $ a_hhsize 4, 5, 6, 6, 6, 4, 2, 3, 5, 4, 5, 5, 4, 4, 4, 3, 5, 4,… ## $ a_hhtype_dv 11, 12, 12, 12, 12, 11, 4, 10, 12, 20, 20, 20, 5, … ## $ a_nkids_dv 1, 2, 3, 3, 3, 2, 1, 1, 3, 1, 2, 2, 3, 3, 3, 1, 2, 2,… ## $ a_tenure_dv 6, 6, 2, 2, 2, 2, 7, 1, 3, 2, 2, 2, 3, 3, 6, 2, 2, 2,… ## $ a_onedegree TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FAL… ## $ a_avg_degree 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.… ``` We could use the contextual data to explain the outcomes of the children in the “youth” data. For example, let’s see whether the likelihood of them wanting to go to university (measured by “a\_yp2uni”) differs for those with at least one household member with a degree (measured by “a\_onedegree”). We can do this by grouping the data by whether the household has at least one person with a degree, and then calculating the proportion who want to go to university for each group. ``` a_youth_hh2 |> filter(a_yp2uni %in% 1:2) |> # remove missing cases group_by(a_onedegree) |> count(a_yp2uni) |> na.omit() |> # remove missing cases mutate(prop = n/sum(n)) ``` ``` ## # A tibble: 4 × 4 ## # Groups: a_onedegree [2] ## a_onedegree a_yp2uni n prop ## ## 1 FALSE 1 [yes] 1688 0.938 ## 2 FALSE 2 [no] 112 0.0622 ## 3 TRUE 1 [yes] 1591 0.971 ## 4 TRUE 2 [no] 48 0.0293 ``` We see that most youth in the sample want to go to university, and the proportion is slightly higher among those with at least one person in the household who has a degree. Again, this is just an example, but it shows how we can use the merged data to explore interesting research questions. ### Merge data scenario 3: add information about the partner at the individual level Another interesting aspect of this study is that it is a household panel. That means that all the adults in the household are interviewed. This also allows us to explore how relationships among individuals in the household influence the outcomes of interest. For example, we could explore how the mental health of individuals is influenced by the mental health of their partner. To understand how individuals relate to each other, we need to use the “egoalt” data. In this data, each row represents a relationship between two individuals in the same household. ``` glimpse(a_egoalt) ``` ``` ## Rows: 182,802 ## Columns: 18 ## $ pidp 68006127, 68006127, 68006127, 68006131, 68006131, 68… ## $ a_hidp 68006123, 68006123, 68006123, 68006123, 68006123, 68… ## $ a_pno 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 1, 1, 1, 2, … ## $ apidp 68006131, 68006135, 68006139, 68006127, 68006135, 68… ## $ a_apno 2, 3, 4, 1, 3, 4, 1, 2, 4, 1, 2, 3, 2, 3, 4, 1, … ## $ a_hhorig 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, … ## $ a_memorig 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, … ## $ a_psu 2012, 2012, 2012, 2012, 2012, 2012, 2012, 2012, … ## $ a_strata 2006, 2006, 2006, 2006, 2006, 2006, 2006, 2006, … ## $ a_sampst 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, … ## $ a_sex 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, … ## $ a_relationship 2, 9, 9, 2, 12, 12, 4, 7, 14, 4, 7, 14, … ## $ a_rel_dv 3, 4, 4, 3, 7, 7, 13, 25, 10, 13, 25, 10, … ## $ a_relationship_dv 2, 9, 9, 2, 12, 12, 4, 7, 14, 4, 7, 14, … ## $ a_asex 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 2, 1, 1, 1, 2, … ## $ pid -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, … ## $ a_enwstat 2, 2, 1, 3, 3, 3, 3, 3, 3, 1, 2, 2, 1, 2, 1, 1, … ## $ a_anwstat 3, 3, 1, 2, 3, 2, 2, 3, 2, 1, 3, 3, 1, 3, 1, 1, … ``` The main information of interest is the “apidp”, the ID of the other person in the relationship and “a\_rel\_dv”, which indicates the type of relationship between the two individuals. ``` count(a_egoalt, a_rel_dv) ``` ``` ## # A tibble: 27 × 2 ## a_rel_dv n ## ## 1 0 [Undefined] 256 ## 2 2 [Lawful spouse] 29466 ## 3 3 [Live-in partner] 6568 ## 4 4 [Natural child] 43874 ## 5 5 [Adopted child] 315 ## 6 6 [Foster child] 122 ## 7 7 [Step/partner's-child] 1844 ## 8 9 [Daughter/son-in-law] 631 ## 9 10 [Natural brother/sister] 35018 ## 10 11 [Other brother/sister] 1026 ## # ℹ 17 more rows ``` We will focus on the relationships that are coded as 2 or 3, which indicate a partner. We will select the “pidp” and “apidp” variables to create a dataset containing the individual’s ID and their partner’s ID. ``` a_partner <- a_egoalt |> filter(a_rel_dv %in% 2:3) |> select(pidp, apidp) ``` Now that we have a dataset containing each individual’s ID and their partners, we can merge it with the individual-level data to get information about the partners’ mental health. We will use a `left_join()` to keep all cases from the individual-level data and add only the matching cases from the partner data. We will also select only the relevant variables and rename them to make them easier to work with later. Note that here we use “apidp” to do the merging (using `by = c("apidp" = "pidp")`) so the information we select is that of the partner. ``` a_partner_data <- left_join(a_partner, a_indresp, by = c("apidp" = "pidp")) |> select(pidp, apidp, a_sf12mcs) |> rename(a_partner_pidp = apidp, a_partner_sf12mcs = a_sf12mcs) ``` Now we can merge this partner data with the individual-level data to create a dataset that includes information on the individuals and their partners’ mental health. ``` a_indresp2 <- left_join(a_indresp, a_partner_data, by = "pidp") ``` With this data, we can explore how the mental health of individuals is related to the mental health of their partners. For example, we could calculate the correlation between the individual’s mental health and their partner’s mental health. ``` a_indresp2 |> select(a_sf12mcs, a_partner_sf12mcs) |> cor(use = "complete.obs") ``` ``` ## a_sf12mcs a_partner_sf12mcs ## a_sf12mcs 1.0000000 0.2889263 ## a_partner_sf12mcs 0.2889263 1.0000000 ``` There seems to be a small positive correlation between an individual’s mental health and their partner’s. This approach could be extended to examine relationships such as that between mothers and daughters or between siblings, just to give some examples. ### Merge data scenario 4: merge across waves Finally, the most common type of merger we use when working with longitudinal data is merging data across waves. One useful strategy here is to create indicators for whether someone is present in your data before you perform the merger. This will help you identify patterns of participation and [attrition](https://longitudinalanalysis.com/attrition-bias-what-is-it-and-how-to-measure-it/). ``` a_indresp2 <- mutate(a_indresp2, a_present = T) b_indresp <- mutate(b_indresp, b_present = T) ``` Once we have these indicators, we can do the merger. I tend to use `full_join()` to bring all the cases together, then use the “present” variables to decide which ones I want to keep for my analysis. For example, if I want to conduct a balanced panel analysis, I would keep only cases present in both waves. If I want to conduct an unbalanced panel analysis, I would keep all cases that appear in at least one wave. Let’s merge the data across time: ``` ab_indresp <- full_join(a_indresp2, b_indresp, by = "pidp") ``` And let’s explore the patterns of participation: ``` count(ab_indresp, a_present, b_present) ``` ``` ## # A tibble: 3 × 3 ## a_present b_present n ## ## 1 TRUE TRUE 38364 ## 2 TRUE NA 12630 ## 3 NA TRUE 16205 ``` Here we see that around 38,000 cases were present in both waves, and 12,000 dropped out after the first wave. We also have around 16,000 new cases that were not present in the first wave but are present in the second wave. If we want to do a balanced panel analysis, we would keep only those cases that are present in both waves. We can do this by filtering the data to keep only those cases where both “a\_present” and “b\_present” are TRUE: ``` ab_ind_balanced <- filter(ab_indresp, a_present == T, b_present == T) count(ab_ind_balanced, a_present, b_present) ``` ``` ## # A tibble: 1 × 3 ## a_present b_present n ## ## 1 TRUE TRUE 38364 ``` ## Tips on how to better merge data A few things to consider before starting to merge panel data: ### Tip 1: Understand data sources It is important to spend time at the beginning of your research to become familiar with your study and how it organises the data. Each study is different, and it’s important to know what data is available, how it is structured and how the different files relate to each other. This will help you to plan your strategy for merging data. It will also help you to understand the limitations of your data and to make informed decisions about how to use it. For example, you can look at the documentation for [Understanding Society](https://www.understandingsociety.ac.uk/documentation/mainstage/datafiles/) and that of the [Health and Retirement Study](https://hrs.isr.umich.edu/documentation/data-descriptions) to see how they organise their data and what information they provide. ### Tip 2: Understand your IDs In addition to the types of files you have, it is important to know how the IDs are coded in each file and how they relate to each other. This will help you to identify the correct IDs to use for merging and to avoid mistakes. For example, in Understanding Society, we have a “pidp” variable that is stable across time and can be used to merge data across waves. We also have the “x\_hidp” variables, which are valid only within each wave and cannot be used to merge data across waves. ### Tip 3: Use the correct sequence of merging When merging panel data, it is important to use the correct sequence. One useful strategy is to first merge the data within each wave (e.g., individual and household) and then merge across waves. ### Tip 4: Define the target sample and use the correct type of merging Before starting to merge panel data, it is important to define your target sample and to use the correct type of merging. For example, if you want to do a balanced panel analysis, you would need to use an `inner_join()` to keep only those cases that are present in both waves. If you want to do an unbalanced panel analysis, you would need to use a `full_join()` to keep all the cases that are present in at least one wave. Alternatively, you could create indicators of presence in each wave and then use a `full_join()` to get all the cases together and then use the indicators to decide which ones to keep for your analysis. It is important to ensure that the data you have reflects the population of interest. For example, if my study focuses on participants in the first waves of the study, I can still use unbalanced data but will exclude any individuals who join the study after wave 1. ## Conclusions on how to merge data Merging data is a complex process that requires careful planning and attention to detail. It is important to define your target sample, understand your data sources and IDs, and plan an appropriate sequence of merges. By following the procedures and tips presented here, you can avoid mistakes and ensure you use the data appropriately. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data management, data restructuring, r --- ### [Data structures for longitudinal analysis: wide versus long](https://longitudinalanalysis.com/data-structures-for-longitudinal-analysis-wide-versus-long/) **Published:** February 2, 2024 **Author:** alexcernat **Excerpt:** Learn how to create, store and reshape longitudinal data. Reshaping data from wide to long data format and back using R. Hands on examples **Content:** Longitudinal data is essential for understanding how individuals, organizations and societies change. But what exactly is longitudinal data? How do we create, store and reshape such data to answer our research questions? ## What is longitudinal data? Different academic fields have different definitions of longitudinal data. To investigate individual-level change and apply the methods often discussed in this blog, longitudinal data needs to meet one important criterion: **data has to be collected multiple times from the same elements**. Elements can be individuals, organizations, societies, sensors and so on. This definition is not met by designs such as repeated cross-sectional studies (where there are new individuals each wave) but is met by designs such as panel studies (where the same individuals are interviewed regularly). This definition covers a wide range of other data sources, such as administrative data and sensor data. ## Types of variables Before we discuss how to create and store longitudinal data, it is important to understand the different types of variables we can have in this context. When working with longitudinal data, we can consider variables as **time-varying** or **time-constant**. For example, if we collect a variable such as general satisfaction each wave, we can treat it as time-varying. As a result, for each individual at each wave, this value could change (although it is not required). Other variables that do not change in time, such as year of birth, are treated as time-constant variables. It is enough to collect this information once from each individual, as we do not expect it to change. There are also some situations where we can choose if we treat a variable as time constant or time-varying. For example, we could recode birth year as age, which is a time-varying variable. Similarly, we could take each individual’s average of “general satisfaction” and make that variable time constant. In such situations, the decision to treat a variable as time constant or variable should be based on theoretical considerations, the data available and the modelling strategy used. ## Creating longitudinal data Typically, data is stored separately for each wave in larger studies. For example, after downloading [Understanding Society](https://www.understandingsociety.ac.uk/), we have one dataset for each wave and each level/type (e.g., individual-level data, household-level data, relationship data). To do longitudinal data analysis, we need to bring these datasets together. For example, imagine we have these two datasets: ``` data_w1 ## # A tibble: 4 × 3 ## id sf1 birthy ## ## 1 68004087 4 1986 ## 2 68008847 2 2001 ## 3 68009527 3 1978 ## 4 68009521 5 1988 data_w2 ## # A tibble: 4 × 2 ## id sf1 ## ## 1 68004087 3 ## 2 68008847 3 ## 3 68009527 3 ## 4 68009522 4 ``` To bring the data together, we need a unique ID for each individual (the “id” column in this case) and decide if variables will be treated as time-constant or time-varying. In this example, we can treat “sf1” (a measure of general health) as a time-varying (it is measured at multiple points in time and can change) while we can treat “birthy” as a time-constant. The latter is measured just once and does not change in time. We can then use one of two strategies to merge the data. The first strategy is to **merge the datasets by column**. There are different commands for this, but the …\_join() commands in the “tidyverse” package are very useful here. To bring all the data together, we can use full\_join() by adding the datasets and the unique ID as inputs. Before we attempt this type of data merging, we need to make sure that the time-varying variables have unique names. It is usually good practice to add a wave-specific suffix: ``` library(tidyverse) data_w1b <- rename(data_w1, sf1_1 = sf1) data_w1b ## # A tibble: 4 × 3 ## id sf1_1 birthy ## ## 1 68004087 4 1986 ## 2 68008847 2 2001 ## 3 68009527 3 1978 ## 4 68009521 5 1988 data_w2b <- rename(data_w2, sf1_2 = sf1) data_w2b ## # A tibble: 4 × 2 ## id sf1_2 ## ## 1 68004087 3 ## 2 68008847 3 ## 3 68009527 3 ## 4 68009522 4 ``` Now we can join the data: ``` data_w12 <- full_join(data_w1b, data_w2b, by = "id") data_w12 ## # A tibble: 5 × 4 ## id sf1_1 birthy sf1_2 ## ## 1 68004087 4 1986 3 ## 2 68008847 2 2001 3 ## 3 68009527 3 1978 3 ## 4 68009521 5 1988 NA ## 5 68009522 NA NA 4 ``` We now have five individuals in the data and four variables. Three of the individuals are present in both waves, while an individual is present in just one of the waves. This could be due to missing data (people dropping out) or new people joining the study. There are different versions of the `..._join()` commands that can facilitate selecting the cases we want. You can find out more [here](https://dplyr.tidyverse.org/reference/mutate-joins.html). The data we created is known as unbalanced data. This means that we include in the data any case, even if it is present just once. If, on the other hand, we wanted to select only cases present in all the waves, also known as **balanced data**, we could use `inner_join()`: ``` inner_join(data_w1b, data_w2b, by = "id") ## # A tibble: 3 × 4 ## id sf1_1 birthy sf1_2 ## ## 1 68004087 4 1986 3 ## 2 68008847 2 2001 3 ## 3 68009527 3 1978 3 ``` The alternative way to combine data is to join them by row. Before that, it is good practice to create a “time” or “wave” variable so we know where the data comes from. ``` data_w1c <- mutate(data_w1, wave = 1) data_w1c ## # A tibble: 4 × 4 ## id sf1 birthy wave ## ## 1 68004087 4 1986 1 ## 2 68008847 2 2001 1 ## 3 68009527 3 1978 1 ## 4 68009521 5 1988 1 data_w2c <- mutate(data_w2, wave = 2) data_w2c ## # A tibble: 4 × 3 ## id sf1 wave ## ## 1 68004087 3 2 ## 2 68008847 3 2 ## 3 68009527 3 2 ## 4 68009522 4 2 ``` We can then use the `bind_rows()` command to do the merger: ``` data_l12 <- bind_rows(data_w1c, data_w2c) data_l12 ## # A tibble: 8 × 4 ## id sf1 birthy wave ## ## 1 68004087 4 1986 1 ## 2 68008847 2 2001 1 ## 3 68009527 3 1978 1 ## 4 68009521 5 1988 1 ## 5 68004087 3 NA 2 ## 6 68008847 3 NA 2 ## 7 68009527 3 NA 2 ## 8 68009522 4 NA 2 ``` Notice that because the time constant variable is present only in wave 1, it only has missing information in the second one (`NA`). We could copy the values from the first wave to all the others by first grouping the data by individual and then taking the maximum of the variable: ``` data_l12 %>% group_by(id) %>% mutate(birthy = max(birthy, na.rm = T)) ## # A tibble: 8 × 4 ## # Groups: id [5] ## id sf1 birthy wave ## ## 1 68004087 4 1986 1 ## 2 68008847 2 2001 1 ## 3 68009527 3 1978 1 ## 4 68009521 5 1988 1 ## 5 68004087 3 1986 2 ## 6 68008847 3 2001 2 ## 7 68009527 3 1978 2 ## 8 68009522 4 -Inf 2 ``` *Notice that one individual has `-Inf` because they have no information available (they joined the study in wave 2).* Which strategy should we use when merging longitudinal data? My general recommendation is to use the first approach, where we merge by adding columns (also known as mutating joins). One reason is that it gives more control regarding which cases to include in the data. It also makes it easier to identify errors and understand the patterns of participation. Finally, in large datasets, we tend to have a mix of time-constant and time-varying variables. Mergers by rows can be complicated in such situations. ## Data structures The two different strategies for merging longitudinal data also highlight that such data can be stored in two different ways: **wide** and **long** formats. Merging the columns leads to a wide format. Here is another example with four waves: ``` ## # A tibble: 3 × 6 ## id sf1_1 sf1_2 sf1_3 sf1_4 birthy ## ## 1 68004087 4 3 3 4 1986 ## 2 68008847 2 3 4 1 2001 ## 3 68009527 3 3 3 3 1978 ``` We see that this is similar to cross-sectional data because each row represents data for an individual (with a unique “id”). If we have information from multiple waves, it appears in different columns. For example, “sf1” is measured four times. The suffix after “\_” represents the wave in which the data was collected. We can also have time-constant variables that do not have the suffix (like birth year: “birthy”). In this type of data, if we want to look at change in time, we need to look at how values change within each row. For example, the person with id “68004087” has an initial decrease on “sf1”, and then, by wave 4, it returns to the original value. On the other hand, the individual with id “68009527” shows no change at all. We call this the **wide data format**, as new waves of data will bring in more columns, making the data wider. Alternatively, we can store the data in the **long format**. This looks like this: ``` ## # A tibble: 12 × 4 ## id wave sf1 birthy ## ## 1 68004087 1 4 1986 ## 2 68004087 2 3 1986 ## 3 68004087 3 3 1986 ## 4 68004087 4 4 1986 ## 5 68008847 1 2 2001 ## 6 68008847 2 3 2001 ## 7 68008847 3 4 2001 ## 8 68008847 4 1 2001 ## 9 68009527 1 3 1978 ## 10 68009527 2 3 1978 ## 11 68009527 3 3 1978 ## 12 68009527 4 3 1978 ``` Now, each row is a combination of person and time. Because each person participated in the study four times, there were four different rows. Now we have a new variable, “wave”, which tells us when the data on that row was collected. This way of storing data is called the **long format**, as new waves of data make the data longer. One format is not better than the other; they have different strengths and uses. The wide format is somewhat easier to work with and is the format used by models based on the Structural Equation Modeling framework, like the latent growth model and the cross-lagged model. It is also easier to use if you want to create correlation matrices and transition tables. The long format is used by some other models, like the fixed effects model and the multilevel model for change. It is also generally easier to clean and visualise the data in the long format. It is possible to restructure the data relatively easily from one format to another as we will discuss next. ## Reshaping data wide to long Imagine we just imported and merged our data. Often, cleaning longitudinal data is easier to do in the long format. There are multiple ways of doing this, but a flexible approach is the `pivot_longer()` command from “tidyverse”. Here, we are going to use the following options: - the data, - the columns that are time-varying (notice here that we select the time constant variables and put “!” to take the opposite, i.e., the other variables), - the separator that is between the name of the variable and the wave number, - the pattern in the name. Here, we say that the first part of the name is the variable name (defined as “.value”) and that the suffix should be a new variable called “wave”. *You can find out more about this command by running `vignette("pivot")` in the R console.* Here is the final command: ``` data_long <- pivot_longer( data_wide, cols = !c(id, birthy), names_sep = "_", names_to = c(".value", "wave") ) data_long ## # A tibble: 12 × 4 ## id birthy wave sf1 ## ## 1 68004087 1986 1 4 ## 2 68004087 1986 2 3 ## 3 68004087 1986 3 3 ## 4 68004087 1986 4 4 ## 5 68008847 2001 1 2 ## 6 68008847 2001 2 3 ## 7 68008847 2001 3 4 ## 8 68008847 2001 4 1 ## 9 68009527 1978 1 3 ## 10 68009527 1978 2 3 ## 11 68009527 1978 3 3 ## 12 68009527 1978 4 3 ``` ## Reshaping data long to wide Imagine that we have finished cleaning the data and now want to run a [Latent Growth Model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/). For such a model, we need the data in wide format. The command we will use is `pivot_wider()` (the opposite of `pivot_longer()`). We use the following inputs: - name of long data - time-varying variables (`values_from`) - how to separate the suffix (`names_sep`) - where to take the suffix from (`names_from`) ``` pivot_wider( data_long, values_from = !c(id, birthy), names_sep = "_", names_from = wave ) %>% select(-starts_with("wave")) ## # A tibble: 3 × 6 ## id birthy sf1_1 sf1_2 sf1_3 sf1_4 ## ## 1 68004087 1986 4 3 3 4 ## 2 68008847 2001 2 3 4 1 ## 3 68009527 1978 3 3 3 3 ``` *By default, this creates wave variables for each wave, which is not very useful in the wide format. The `select()` command removes them from the data.* ## Conclusions Here, we covered some of the key decisions we need to consider when preparing longitudinal data for analysis. First, we must decide how to treat the variables, **time constant or varying**. Second, we must decide how to merge the data and what cases to keep. Here, I recommend merging the data by columns (using the …\_join() commands) and creating wide data. You can decide to use balanced or unbalanced data depending on the research question. Third, I recommend restructuring the data in the long format to make it easier to clean. The final data version (long or wide) will depend on how you plan to use it. [Visualization using ggplot](https://longitudinalanalysis.com/visualizing-transitions-in-time-using-r-and-alluvial-graphs/) and models such as fixed effects, [multilevel models for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) and survival models work with data in the long format while models such as [cross-lagged](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/) or [latent growth](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) use the wide data. --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management **Tags:** data cleaning, data management, data restructuring, r --- ### [Data cleaning tips for making the most of longitudinal data](https://longitudinalanalysis.com/data-cleaning-tips-for-making-the-most-of-longitudinal-data/) **Published:** May 1, 2026 **Author:** Alex Cernat **Excerpt:** Before visualising and analysing longitudinal data, it is essential to prepare it correctly. In this guide, we cover data cleaning tips before visualisation **Content:** Data visualisation is a key step when exploring data, developing hypotheses and preparing for more advanced statistical models. Often, researchers rush to this step before properly cleaning their data. In this guide, we will cover key data cleaning tips before visualisation. ## Data cleaning tips: use the data checklist A good point to start with is our data preparation checklist. This includes some of the key things to look out for before you visualise and analyse your data. ![Data cleaning tips: Data preparation checklist ](https://longitudinalanalysis.com/wp-content/uploads/2026/05/Design-768x1024.webp) ### Is the variable in the correct format? The first data cleaning tip is to ensure that the variables you will use are coded in the correct format. Many functions in R run differently depending on the input. For example, if you use the `summary()` command, the statistics you get will differ between numeric variables and factors (which are used to code categorical data). When importing data in R sometimes the variables are not coded in the format you expect and this might lead to errors downstream. For example, if a variable is treated as text, you cannot use it to calculate a mean. We can look at data from the [Understanding Society](https://www.understandingsociety.ac.uk/) to see how this can be problematic. We have two variables to measure time: the wave and the interview year (“istrdaty”). If we select them and use `glimpse()` we see: ``` usl |> select(wave, istrtdaty) |> glimpse() ``` ``` ## Rows: 204,028 ## Columns: 2 ## $ wave "1", "2", "3", "4", "1", "2", "3", "4", "1", "2", "3", "4", … ## $ istrtdaty 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, … ``` First, the wave is treated as “character” or text (“<chr>” in the output). This is incorrect; it should be numeric instead. The date of the interview is ``. This stands for numeric (or “double”) with labels. This is a format that is often used when importing data using the `haven` package. A better approach would be to code this either as a numeric or a date variable. We can convert the original data to numeric using the `as.numeric()` function. For the date format, we can use the `ymd()` function. Here, we will just assume the data is collected on the first day of each year, so we combine the year with “0101”. For most purposes, just having the numeric year is enough, but if we need the date format, now we will also have that: ``` usl |> transmute(wave = as.numeric(wave), year_num = as.numeric(istrtdaty), year_date = ymd(paste0(year_num, "0101"))) |> glimpse() ``` ``` ## Rows: 204,028 ## Columns: 3 ## $ wave 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, … ## $ year_num 2009, 2010, 2011, 2012, 2010, 2011, 2012, 2013, 2009, NA, NA… ## $ year_date 2009-01-01, 2010-01-01, 2011-01-01, 2012-01-01, 2010-01-01,… ``` ### Are missing categories coded accordingly? One key decision is how to treat missing values. In R, typically, these should be coded as `NA` unless you plan to use them explicitly. So, a first step is to check that missing values are coded as `NA`. Below, when we do a graph of mental health, we see some extreme negative values. ``` qplot(us1$a_sf12mcs_dv) ``` ![original sf12 distribtion with missing data](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-1024x731.webp) A closer look at the attributes indicates that these are different types of missing answers. ``` attributes(us1$a_sf12mcs_dv) ``` ``` ## $label ## [1] "SF-12 Mental Component Summary (PCS)" ## ## $format.stata ## [1] "%12.0g" ## ## $class ## [1] "haven_labelled" "vctrs_vctr" "double" ## ## $labels ## missing inapplicable Proxy respondent ## -9 -8 -7 ``` The simplest way to deal with this is to recode negative values `NA` using the code below: ``` us1 |> mutate(mcs = ifelse(a_sf12mcs_dv < 0, NA, a_sf12mcs_dv)) |> select(mcs) |> summary() ``` ``` ## mcs ## Min. : 0.00 ## 1st Qu.:45.91 ## Median :53.04 ## Mean :50.49 ## 3rd Qu.:57.16 ## Max. :77.11 ## NAs :3594 ``` Missing data can be complex, and when the amount of missing data is large or systematic, it is worth considering more advanced methods for addressing it, such as imputation or weighting. More on this in a future guide. ### Are categories labelled correctly? In the social sciences, we often work with categorical data. In R, it is best to code these as a factor. These types of variables come with their own issues and commands. One problem you might have concerns the ordering of the categories. In the example below, it seems the categories are not in the right order. ``` count(usl, vote6) ``` ``` ## # A tibble: 5 × 2 ## vote6 n ## ## 1 Fairly 49363 ## 2 Very 14638 ## 3 Not very 41082 ## 4 Not at all 38036 ## 5 60909 ``` We can put them in the order we want using the `fct_relevel()` command. This will move the categories we select as the first labels. For example, if we want “Very” to be the first category, we can use the following command. ``` mutate(usl, vote6 = fct_relevel(vote6, "Very")) |> count(vote6) ``` ``` ## # A tibble: 5 × 2 ## vote6 n ## ## 1 Very 14638 ## 2 Fairly 49363 ## 3 Not very 41082 ## 4 Not at all 38036 ## 5 60909 ``` We will discuss more issues regarding factors at the end of this guide. For now, remember this data cleaning tip for categorical variables: check that the categories have appropriate labels and are in the correct order. ### Does the distribution look reasonable? The next data cleaning tip is to check the distribution of the variables of interest. Here, having some domain expertise is invaluable as it will allow you to spot strange patterns or errors. For example, do you spot any strange things about the income variable? ``` qplot(us1$a_fimngrs_dv) ``` ![histogram of income with negative values](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-1-1024x731.webp) From this distribution, it looks like there are some negative values. Let’s check this also using `summary()`: ``` summary(us1$a_fimngrs_dv) ``` ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. ## -12436.6 508.7 1097.0 1455.2 1946.2 22666.0 ``` There indeed seem to be some negative values. To me, this seems implausible. It might be that these were mistakes introduced earlier on. It would be good to investigate this, for example, by looking at the documentation or contacting the data collection team. Here, we will assume this is an error and treat all negative values as missing: ``` us1 <- us1 |> mutate(gross_income = ifelse(a_fimngrs_dv < 0, NA, a_fimngrs_dv)) qplot(us1$gross_income) ``` ![histogram of income without negative values](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-2-1024x731.webp) Sometimes it is possible to do other types of logical checks. For example, you could investigate whether there is income for those who don’t work or are not allowed to work (e.g., children). The more checks you can do, the more confidence you can have in your data. ### Are there extreme cases or outliers? For continuous variables, such as income, we often encounter extreme cases or outliers. The next data cleaning tip focuses on this. A good way to investigate this is to look at the box-and-whisker plot, where the box represents 50% of the distribution. Cases outside the box-and-whisker (box + line) range represent outliers. If we look at the graph for income, we get: ``` ggplot(us1, aes(gross_income)) + geom_boxplot() ``` ![box an whiskers plot of income](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-6-1024x731.webp) We see relatively few cases above ~£10,000. Here, there are a couple of decisions we can make. One of the most common ones is to cap the variable at some extreme cutoff point. This is sometimes called Winsorisation. Here, as an example, we will cap income to a maximum of £10,000 using the ifelse() command. For this, we add our condition, as well as what should happen when the condition (i.e., the value is greater than 10000) is met (set the value to 10000) or not met (copy the old value). ``` us1 <- us1 |> mutate(gross_income_cap = ifelse(gross_income > 10000, 10000, gross_income)) qplot(us1$gross_income_cap) ``` ![histogram of income capped ](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-7-1024x731.webp) Now the distribution looks a little more reasonable. A more flexible way to do this is to calculate the percentile and cap it at that level. For example, if we want to see what value separates the top 1% of the distribution from the rest we can use the command below: ``` cap <- quantile(us1$gross_income, probs = 0.99, na.rm = T) cap ``` ``` ## 99% ## 7991.999 ``` Now we can use that value to do the cap. We can choose different cut-off points (like 5% or 10%) depending on how skewed the distribution is. ``` us1 |> transmute(gross_income_cap = ifelse(gross_income > cap, cap, gross_income)) |> ggplot(aes(gross_income_cap)) + geom_histogram() ``` ![histogram of income capped at 99%](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-5-1024x731.webp) ### Do we need to rescale the variables? Sometimes we need to rescale some of the variables we have. A common one in the social sciences is to take the log of income. This is done because the distribution is skewed, with relatively few people having very large incomes. Taking a log of 0 yields an unwanted result (-Infinity), so we typically add a constant to avoid losing those cases. ``` qplot(log(us1$gross_income_cap + 0.01)) ``` ![log of income histogram](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-8-1024x731.webp) Alternatively, we could use rankings of people by income. This would address the skewness of the data but would lose the original scale. The command `percent_rank()` is useful for this. You can see what the distribution would look like if we used this for income: ``` qplot(percent_rank(us1$gross_income)) ``` ![histogram of income ranking](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-10-1024x731.webp) There are other ways in which we might want to change the scale of variables. When working with longitudinal income data, we need to be aware that currency values may change due to inflation. So, £1 does not mean the same thing in 1990 as in 2000. We can use the `priceR` package to adjust the income by inflation. We provide our gross income and the year it was collected, and ask to adjust the values to 2009, the first year of data collection. ``` library(priceR) usl <- usl %>% mutate(fimngrs.cap.adjust = adjust_for_inflation(fimngrs.cap, year, "GB", to_date = 2009)) ``` If we compare the original income variable and the adjusted one, we see quite big differences over a relatively small period of time: ``` usl |> group_by(year) |> summarise(mean_income = mean(fimngrs.cap, na.rm = T), mean_income_adj = mean(fimngrs.cap.adjust, na.rm = T)) ``` ``` ## # A tibble: 7 × 3 ## year mean_income mean_income_adj ## ## 1 2009 1462. 1462. ## 2 2010 1506. 1477. ## 3 2011 1616. 1546. ## 4 2012 1699. 1565. ## 5 2013 1740. 1563. ## 6 2014 1785. 1567. ## 7 NA 1498. NaN ``` Other types of standardisation could account for currency differences across countries or household composition (e.g., using the OECD standardised scale). More generally, in data science, we often recode variables to a 0-1 scale to facilitate the estimation of more complex models. ## Other tips ### Data cleaning tips: Adjusting factors As mentioned above, factors come with their own complications, so it’s useful to discuss other typical issues that might arise. Let’s look at a barplot for satisfaction: ``` usl |> ggplot(aes(sati.fct)) + geom_bar() + coord_flip() ``` ![barplot of satisfaction](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-4-1024x731.webp) One thing we might want to do is to reverse the order of the categories. We can use the `fct_rev()` to do this quickly: ``` usl |> ggplot(aes(fct_rev(sati.fct))) + geom_bar() + coord_flip() ``` ![bar plot of satisfaction with reverse scale](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-9-1024x731.webp) This does what we want, but highlights another issue. How best to treat missing data? Sometimes, if the focus is just on the available data, we can first filter out the missing data and then do the graph: ``` usl |> filter(!is.na(sati.fct)) |> ggplot(aes(sati.fct)) + geom_bar() + coord_flip() ``` ![barplot without missing data](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-11-1024x731.webp) Alternatively, if we want to show the amount of missing data, it might be better to treat it as a normal category: ``` usl |> mutate(sati.fct = fct_explicit_na(sati.fct, "Missing")) |> ggplot(aes(sati.fct)) + geom_bar() + coord_flip() ``` ![barplot of satisfaction with explicit missing category](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-12-1024x731.webp) We can move the missing category to the end using the `fct_relevel()` command. ``` usl |> mutate(sati.fct = fct_explicit_na(sati.fct, "Missing"), sati.fct = fct_relevel(sati.fct, "Missing")) |> ggplot(aes(sati.fct)) + geom_bar() + coord_flip() ``` ![barplot of satisfaction with missing category at the end](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-15-1024x731.webp) Let’s look at another example where we first compute summary statistics and then plot them. Here, we use the highest degree awarded. The `as_factor() `command takes labels imported from Stata or SPSS and uses them as labels for a factor variable. ``` us1 <- us1 |> mutate(edu = as_factor(a_hiqual_dv)) ``` We then use this variable to calculate the average income by education level as well as the number of cases in each: ``` edu_stats <- us1 |> group_by(edu) |> summarise(income = mean(gross_income_cap, na.rm = T), n = n()) edu_stats ``` ``` ## # A tibble: 7 × 3 ## edu income n ## ## 1 Missing 1518. 92 ## 2 Degree 2355. 10954 ## 3 Other higher 1732. 5537 ## 4 A level etc 1318. 9591 ## 5 GCSE etc 1161. 10526 ## 6 Other qual 1166. 5225 ## 7 No qual 844. 9069 ``` We can use it to make a graph: ``` edu_stats |> ggplot(aes(income, edu)) + geom_point() ``` ![everage income by education](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-13-1024x731.webp) Another data cleaning tip is to reorder categories in a factor based on a second variable. For example, in this graph, we might want the categories to be ordered by their average income. We can use the `fct_reorder()` for that: ``` edu_stats |> mutate(edu = fct_reorder(edu, income)) |> ggplot(aes(income, edu)) + geom_point() ``` ![change category order for average income by education](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-14-1024x731.webp) Another thing we might want to do sometimes is to collapse or lump some categories together. This is useful if we have categories with few cases. If we want to show only the top three categories, plus all the others lumped together, we can use `fct_lump_n(edu, 3)`. This would lead to a much simpler graph. ``` us1 |> mutate(edu = fct_lump_n(edu, 3)) |> group_by(edu) |> summarise(income = mean(gross_income_cap, na.rm = T), n = n()) |> ggplot(aes(income, edu)) + geom_point() ``` ![average income by education with 4 categories](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-16-1024x731.webp) ### Data cleaning tips: Changing the time variable when plotting When working with longitudinal data, the way we code the time variable is key. Let’s see how this could be done in different ways with a simple example using the change in time of income by wave. ``` usl |> ggplot(aes(wave, logincome)) + geom_smooth(method = "lm") ``` ![plot of change in time with issue](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-18-1024x731.webp) For some reason, we get an empty graph. If we look at how the variable is coded, we see it is a character (text). ``` typeof(usl$wave) ``` ``` ## [1] "character" ``` We can code this as numeric and redo the graph: ``` usl |> mutate(wave = as.numeric(wave)) |> ggplot(aes(wave, fimngrs.cap.adjust)) + geom_smooth(method = "lm") ``` ![change in time graph](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-17-1024x731.webp) This is better. Sometimes, treating a variable with few categories as continuous can yield scales that do not make sense, such as a wave of “2.5”. Here is an example: ``` usl |> mutate(wave = as.numeric(wave)) |> filter(wave < 4) |> ggplot(aes(wave, fimngrs.cap.adjust)) + geom_smooth(method = "lm") ``` ![change in time over three waves with problematic scale](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-19-1024x731.webp) There are two strategies to deal with this. First, we can define the x scale by hand: ``` usl |> filter(wave %in% 1:3) |> mutate(wave = as.numeric(wave)) |> ggplot(aes(wave, fimngrs.cap.adjust)) + geom_smooth(method = "lm") + scale_x_continuous(breaks = 1:3) ``` ![change in time with three waves with cleaner scale](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-21-1024x731.webp) Secondly, we can code time as a factor. When calculating summary statistics, we will need to add the option `group = 1` to be able to estimate trend lines: ``` usl |> filter(wave %in% 1:3) |> mutate(wave = as.factor(wave)) |> ggplot(aes(wave, fimngrs.cap.adjust, group = 1)) + geom_smooth(method = "lm") ``` ![change in time with three waves with scale as a factor](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-20-1024x731.webp) This has the benefit of including only valid values in the axis. Another data cleaning tip for working with longitudinal data is to always consider how best to define the time metric. For example, with this data, we could also define time as years: ``` usl |> ggplot(aes(year, fimngrs.cap.adjust)) + geom_smooth(method = "lm") ``` ![change in time for income by year](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-22-1024x731.webp) Or we could look at change by age: ``` usl |> ggplot(aes(age, fimngrs.cap.adjust)) + geom_smooth(method = "lm") ``` ![change in time by age of income](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-25-1024x731.webp) Make sure that whatever time metric you choose makes substantive sense and that it is coded correctly. ### Data cleaning tips: Creating weighted graphs The final data cleaning tip to consider before doing visualisations concerns weighting. Weights are variables created to adjust for the sampling design used or for issues such as non-response and coverage bias. Sometimes, ignoring the provided weights can lead to incorrect visualisations and results. There are different ways to do weighted statistics. Here we will use the `survey` package. We first define a simple design that has no complex survey design (clustering or stratification) but has a weight variable (“a\_indinus\_xw”): ``` library(survey) des <- svydesign( ids = ~1, weights = ~a_indinus_xw, data = us1 ) ``` We then create a table, as before, showing the average income by education level. This now accounts for the weights and also provides a corrected confidence interval. ``` edu_stats_w <- svyby( ~gross_income_cap, ~edu, des, svymean, na.rm = TRUE, vartype = "ci" ) edu_stats_w ``` ``` ## edu gross_income_cap ci_l ci_u ## Missing Missing 988.6604 581.2113 1396.1095 ## Degree Degree 2479.7152 2434.8854 2524.5450 ## Other higher Other higher 1779.8557 1736.8228 1822.8886 ## A level etc A level etc 1383.6905 1353.2563 1414.1246 ## GCSE etc GCSE etc 1197.7313 1172.5039 1222.9586 ## Other qual Other qual 1187.9602 1154.2907 1221.6297 ## No qual No qual 859.1098 840.2124 878.0071 ``` Now we can use this to create a graph with the weighted statistics: ``` ggplot(edu_stats_w, aes(gross_income_cap, edu)) + geom_pointrange(aes(xmin = ci_l, xmax = ci_u)) ``` ![weighted average income by education](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-24-1024x731.webp) We can compare this with the unweighted statistics from before, and we see that there are some important differences, especially for the “Missing” category: ``` ggplot(edu_stats_w, aes(gross_income_cap, edu)) + geom_pointrange(aes(xmin = ci_l, xmax = ci_u)) + geom_point(data = edu_stats, aes(income, edu), color = "red") ``` ![average income by education with and without weights](https://longitudinalanalysis.com/wp-content/uploads/2026/05/image-23-1024x731.webp) This approach is very flexible and can be used with more complex survey designs and other statistical methods as well. ## Conclusions on data cleaning tips before visualisation Here, we cover key data cleaning tips to consider before performing more advanced visualisations and analyses. We went through a checklist of things to look for when cleaning data, as well as a more in-depth discussion of factors, time variables, and weighting. You can learn more about data cleaning in [this post](https://longitudinalanalysis.com/preparing-longitudinal-data-for-analysis-in-r-a-step-by-step-guide/) or in [our online course](https://leanpub.com/c/long-data-wrangle?lng=en). You can also check [our complete guide to visualising longitudinal data](https://longitudinalanalysis.com/complete-guide-to-visualizing-longitudinal-data-in-r/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** communication, data management, statistics, visualization **Tags:** data cleaning, data management, longitudinal data analysis, r, visualization --- ### [How to create reproducible workflows for longitudinal data analysis](https://longitudinalanalysis.com/how-to-develop-a-reproducible-workflow-for-longitudinal-data-analysis/) **Published:** March 28, 2025 **Author:** Alex Cernat **Excerpt:** Learn best practices for longitudinal data analysis, including Git, renv, and reproducible workflows to improve efficiency, accuracy, and collaboration. **Content:** Longitudinal data analysis often involves complex processes, including data preparation, cleaning, modeling, and presentation. As a result, having a clear and structured workflow is essential. A good workflow ensures that the analysis is reproducible, transferable, and easy to revise and share. Without a structured approach, it is easy to lose track of decisions and steps, leading to confusion or errors. Here are some key principles to consider when developing your data workflow: - **No copy and paste**: Avoid manual copying and pasting. Instead, write scripts that automate repetitive tasks to ensure consistency and reduce errors. When coding, an useful rule of thumb is to not copy and edit a piece of code more than twice. If you are doing repetitive coding it may be better to write a function or a loop instead. Also, never copy and paste results as this is prone to errors and cannot be easily replicated. - **Back up your work**: Always back up your scripts and data. A simple way to do that is by using a service like Dropbox or One drive. Even better, using a version control system like Git makes it possible to create a full history of the documents you worked on. By combining Git with GitHub, you can back up your work in the cloud and make it available publicly or with a smaller group of collaborators (more on this below). - **Document your work**: Document your code, decisions and workflow. Use comments in your scripts and commit messages in version control systems to explain what and why you are doing something. While this might be obvious at the time it will be less so for your colleagues and even for yourself in the future. - **Make your work transferable**: Use tools like relative paths, dynamic documents, and self-contained project structures to ensure that your analysis can run seamlessly on another system. This is especially important if you are collaborating with others or planning to share your work. ## Using version control with Git and GitHub for reproducible workflows [Git ](https://git-scm.com/downloads)is a powerful version control system that creates a history of your work as well as associated documentation for each important step. It also facilitates collaboration with others. You can also combine Git with [GitHub](https://github.com/), facilitating online back-ups and collaboration with others. The main strengths of version control software such as Git (+ GitHub): - **Version control**: Track changes to your project files over time, allowing you to revert to previous versions if needed. - **Collaboration**: Work with others on the same project and manage version conflicts. - **Backup**: Store your project in the cloud, ensuring that your work is safe and accessible. - **Documentation**: Keep a clear history of your project, including who made changes and why. - **Branches**: Work on different features or analyses simultaneously without affecting the main project. Git works by creating a local repository that stores your project files and their history. You can then commit changes to the repository, creating a snapshot of your work at that point in time. By using branches, you can work on different features or analyses simultaneously without affecting the main project. When you are ready, you can merge these branches back into the main project. Git and GitHub are well integrated in RStudio, making it easy to manage your project. Once you install Git on your computer you can get started by initializing a Git repository in your project directory: ``` usethis::use_git() ``` Alternatively you can also initialize a Git repository from the menu options in RStudio or when you create an Rstudio project. After you did some work in the project and are at a stage where you want to save what you have done you can do a **commit**. When you commit you need to decide the changes you want to save and add a comment that explains what you have done. You can commit them to the repository using using the Rstudio menu or a command such as: ``` usethis::use_git_commit("Description of changes") ``` Committing is a process that happens locally, on your computer. If you want to backup your work on GitHub the next step would be to **push** the changes to the remote repository (you first need to create a GitHub account and link it to RStudio). You can do this using the RStudio menu or the following command (or using the Rstudio menu): ``` usethis::pr_push() ``` Pushing sends the current code to the remote repository on GitHub. This is useful if you want to share your work with others or if you want to have a backup of your work in the cloud. The opposite of pushing is **pulling**. Pulling is used to get the latest version from the remote repository. This is useful if you are working with others and want to incorporate their changes into your work. You can pull changes using the RStudio menu or the following command: ``` usethis::pr_pull() ``` These are just some of the basics of Git and GitHub. There are many more features and commands that can be used to manage your project. Keep in mind that there is some initial work to set up Git and GitHub properly and to link it to RStudio. For a more detailed introduction to Git and GitHub you can check out the online book [Happy Git with R](https://happygitwithr.com/). ## Managing dependencies in R with the `renv` package Often we work on multiple projects at different points in time. As R and packages change it may become difficult to reproduce results or to re-run code from the past. The R package `renv `partially solves this problem. It does this by installing and managing separate packages for each project. By creating a local library of packages for your project, `renv` ensures that the same versions of packages are used regardless of when or where the analysis is run. This is especially useful for complex projects that might span over months or years. You can activate `renv` when creating a new project in RStudio. Alternatively, you can also initialize it in an existing project directory: ``` renv::init() ``` This creates a snapshot of your current package environment. You can restore this environment later with: ``` renv::restore() ``` Now, when you install packages they will be installed directly in the project folder. When you open you RStudio project again it will automatically load the local packages. This makes it easier to share your project with others or to run it on a different computer. This is also very useful if you need to go back to an old project and rerun the analysis (e.g., to revise a paper). The package will also remember the version of R you used and make it possible to restore all the packages you used in the past (e.g., if these were deleted), again helping reproduce your results. ## Structuring projects and using relative paths Another aspect to consider when working on more complex projects is how to organize your folders. Consider the following folder structure as a way to organize your longitudinal data projects: ``` project/ ├── data/ ├── scripts/ ├── results/ ├── figures/ └── reports/ ``` - **data**: Store raw and cleaned datasets here - **scripts**: Add your R scripts here. If the project is more complex separate your scripts by stage (e.g., cleaning, analysis, visualization) - **results**: Save intermediate outputs like model results, estimates and tables - **figures**: Keep all visualizations and graphs in one place - **reports**: Use dynamic documents (e.g., R Markdown) to generate reports that combine text, code, and results (more below) Of course, you can adapt this structure your needs. Other useful folders that you might want to consider are: “documentation” (e.g., for the data used), “literature” (for papers and references), “presentations” (for slides and presentations), and “manuscript” (for versions of a paper). Another good practice is the use of “relative” as opposed to “absolute” paths. An absolute path shows where to find a file on the computer and looks like “C:/Users/YourName/project/data/your\_dataset.csv” (for a Windows computer). The disadvantage of this approach is that the code will not work if you move the project somewhere else or if a collaborator tries to run your code on a different device. An alternative to this is to use a relative path, such as “data/your\_dataset.csv”. This path is relative to your working directory. If you use a Rstudio project it will automatically set the working directory to your project folder. In this way the path will work regardless of where the project is stored. For example, you can read a dataset using a relative path like this (i.e., file “your\_dataset.csv” from the “data” subfolder): ``` read.csv("data/your_dataset.csv") ``` Now, once you set up the working directory (or if you use an RStudio project) you can use relative paths to access files in your project. This makes it easy to run code across multiple devices. Also try to have a consistent naming convention. In general try to avoid having spaces in the names of folders or files as it sometimes leads to confusion. So use a folder name like “raw\_data” instead of “raw data”. I also tend to use only lower case in my naming convention to avoid confusion but this is more of a personal preference. ## Stages of a workflow So, given these principles and tools, what does a typical workflow for longitudinal data analysis look like? Here are some steps to consider: 1. **Set up the project**: Create a folder for the project, set-up the working directory, initiate a Git repository and activate `renv`. All of this can be done easily in RStudio by creating a “New Project” (remember to select to initiate a Git repository and `renv` in the menu). ![how to set up a reproducible project with rstudio](https://longitudinalanalysis.com/wp-content/uploads/2025/03/image-2.png) 2. **Create a project structure**: Decide what kind of files you will be working with and create a folder structure that makes sense for your project. This can include folders for data, scripts, results, figures, and reports. This can be done in the “Files” pane in RStudio or by using commands (that need to be run only once) such as: ``` dir.create("data") dir.create("scripts") dir.create("results") dir.create("figures") dir.create("reports") ``` 3. **Data preparation**: Often this is one of the most time consuming parts of working with data. Write scripts for importing, cleaning, and reshaping your data. If the scripts become long separate each step in different scripts to make the process more modular. Also, consider numbering the scripts so it is clear in which order they should be run (e.g., “01\_data\_import.R”, “02\_data\_clean.R”, etc.). Ideally each script should have a clear set of inputs and outputs and all of them should be run to create the final results of your analysis. 4. **Analysis**: Again, create scripts for doing the analysis. When conducting more complex analyses consider separate scripts for exploratory analysis, model fitting, and presenting of results. 5. **Reports and presentations**: Use dynamic documents (e.g., R Markdown or Quarto) to create reproducible reports or presentations to share with others. 6. **Work in stages**: Try to divide your work in stages. A stage could be when you finished doing something in R, for example finished the data cleaning, the analysis, a report, etc. You can also use the end of the coding session as a milestone. At this points commit your code to Git with a comment about what you have done in this stage. This will build a history of your work and make it easier to track changes. 7. **Collaboration**: If you are working with others, make sure to communicate about the workflow and the tools you are using. This will make it easier to collaborate and avoid confusion. Consider using GitHub as a tool for collaboration and sharing your work. If you do use GitHub remember to start your work session by **Pulling** the latest version of the code and end it by **Pushing** your changes. ## Conclusions By following these steps and principles, you can create an efficient, reproducible workflow for longitudinal data analysis. A well-structured workflow is not just about organization—it’s about ensuring that your findings are robust, your process is transparent, and your work can be easily shared and built upon by others. Also keep in mind that it takes time to learn all of these tools and to develop a workflow that works for you. That being said, it is worth the investment as it will save you time in the long run and make your work more efficient and reproducible. To learn how these practices fit in the larger workflow you need to follow when working with longitudinal data check out [this post](https://longitudinalanalysis.com/understanding-the-longitudinal-data-workflow-a-comprehensive-guide/). You can also check out how to use dynamic documents [here ](https://longitudinalanalysis.com/using-dynamic-documents-to-present-results-in-r/)and how to present results [here](https://longitudinalanalysis.com/how-to-present-results-from-longitudinal-analysis/). --- Want to take your skills to the next level? Join our next live course to learn how to efficiently prepare and explore data as well as the main frameworks for analysing longitudinal data. [Find out more](https://longitudinalanalysis.com/intro-long-analysis-course/) **Categories:** data management, longitudinal data analysis **Tags:** data management, r --- ## Pages ### [Home](https://longitudinalanalysis.com/) **Published:** February 2, 2024 **Author:** alexcernat **Content:** # Master Longitudinal Data Learn how to clean, model, and visualise change over time with expert guidance, practical tools, and real-world data. [****Buy b****ook](https://longitudinalanalysis.com/#book) [Join course](https://longitudinalanalysis.com/#courses) ![Visualising patterns for longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2024/02/alluvial_front-1024x559.png) ## Testimonials *Analysing longitudinal data is challenging… no other book compiles the relevant topics in such a pedagogical way… a must-read for both people new to longitudinal data analysis and those looking to improve their existing knowledge.* **Kim Backström**, PhD student, Åbo Akademi, Finland *I had a longitudinal dataset that was ideal for answering an important research question in my field, but I had no experience with longitudinal analyses. After reading this book, I felt confident enough to run the analyses myself. The paper is now ready to be submitted. I was honestly surprised that a book could help someone with zero background in longitudinal analysis do complex analyses for a real research project.* **Omid Ghasemi**, Postdoctoral Research Associate, University of New South Wales *Thoroughly recommend anything taught by Alex*. **Michelle Degli Esposti**, Postdoctoral Researcher, University of Oxford *I owe Alex’s 2018 course my ‘re-birth’ as an R data manager and analyst.* **Teresio Poggio**, Research Assistant, University of Trento *What I really liked about the book was how unique it was… accessible… excellent, particularly around multi-level modelling.* **Emily Lowthian**, Lecturer in Education, Swansea University ![Longitudinal modelling and trends ](https://longitudinalanalysis.com/wp-content/uploads/2024/02/stock-1863880_1920-300x200.jpg)![Alexandru Cernat, professor](https://longitudinalanalysis.com/wp-content/uploads/2025/05/alexandru_cernat-1024x911.webp) ## Author & Platform Creator I’m Alex Cernat, [Professor of Methodology and Social Data Science at the University of Manchester](https://research.manchester.ac.uk/en/persons/alexandru.cernat), specialising in collecting and analysing longitudinal data. Over the past decade, I’ve [published over 50 papers and book chapters](https://www.alexcernat.com/publications/) using advanced models to study how people and societies change. This website combines everything I’ve learned to offer you practical tools, real-world examples, and clear explanations for mastering longitudinal data. [**Learn more**](http://alexcernat.com) --- ## Get the Book ## Longitudinal Data Analysis Using R The book covers all the key skills needed to prepare, explore, and analyse longitudinal data. It interweaves explanations of key concepts, statistical modelling, code and visualisations using real-world data. [**Buy ebook**](http://leanpub.com/long-data-r) [Buy paperback](https://www.amazon.com/dp/B0GBN1KKMF) ![patterns of change in longitudinal data](https://irn.ncc.temporary.site/.website_7306148f/wp-content/uploads/2024/02/cover_11-edited.png)![complex patterns of change in longitudinal data](https://irn.ncc.temporary.site/.website_7306148f/wp-content/uploads/2024/02/cover_11-724x1024.png) --- ## Access the Courses ## [Introduction to Longitudinal Data Analysis](https://longitudinalanalysis.com/intro-long-analysis-course/) using R Online live: October – November 2026 [Explore](https://longitudinalanalysis.com/intro-long-analysis-course/) ## [Introduction to R](https://leanpub.com/c/intro-r-social?lng=en) Online: On demand [Explore](https://leanpub.com/c/intro-r-social?lng=en) ## [Master Longitudinal Data Wrangling](https://leanpub.com/c/long-data-wrangle?lng=en) Online: on demand [Explore](https://leanpub.com/c/long-data-wrangle?lng=en) ## [Mediation and Moderation Analysis Using R](https://leanpub.com/c/mediation-moderation-r) Online: on demand [Explore](https://leanpub.com/c/mediation-moderation-r) ![bespoke training and consulting for longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2025/04/longitudinal-consulting-training-scaled.webp) Transform Your Team’s Data Skills ## Bespoke Training Contact me to discuss how to best upskill your team. [**Schedule a meeting**](http://longitudinalanalysis.com/#contact) --- ## Latest Guides - [![AI Agent for Data Analysis and Why You Need Taste](https://longitudinalanalysis.com/wp-content/uploads/2026/07/ChatGPT-Image-Jul-10-2026-11_40_31-AM.webp)](https://longitudinalanalysis.com/ai-agent-for-data-analysis-and-why-you-need-taste/)[data management](https://longitudinalanalysis.com/category/data-management/) ### [AI Agent for Data Analysis and Why You Need Taste](https://longitudinalanalysis.com/ai-agent-for-data-analysis-and-why-you-need-taste/) - [![Causal Mediation in R: A Practical Guide](https://longitudinalanalysis.com/wp-content/uploads/2026/06/example-5-diagram-1-4.webp)](https://longitudinalanalysis.com/causal-mediation-in-r/)[longitudinal data analysis](https://longitudinalanalysis.com/category/longitudinal-data-analysis/) · [statistics](https://longitudinalanalysis.com/category/statistics/) ### [Causal Mediation in R: A Practical Guide](https://longitudinalanalysis.com/causal-mediation-in-r/) - [![How to run a multiple mediation model in R](https://longitudinalanalysis.com/wp-content/uploads/2026/06/a-multiple-mediation-model-example-4-6.webp)](https://longitudinalanalysis.com/a-multiple-mediation-model-r/)[longitudinal data analysis](https://longitudinalanalysis.com/category/longitudinal-data-analysis/) · [statistics](https://longitudinalanalysis.com/category/statistics/) ### [How to run a multiple mediation model in R](https://longitudinalanalysis.com/a-multiple-mediation-model-r/) [**All guides**](http://longitudinalanalysis.com/blog) --- ## Contact [← Back](/wp-cron.php?doing_wp_cron=1795437944.2557749748229980468750) #### Thank you for your response. ✨ ![]() Name(required) Email(required) Message 1. **Send message**Submitting form Δ --- ### [Understanding attrition bias in longitudinal data](https://longitudinalanalysis.com/interactive/attrition-bias/) **Published:** November 20, 2026 **Author:** Alex Cernat **Excerpt:** An interactive guide to attrition bias in longitudinal data: how people leaving a study bias its results, how to measure it and how big it is in a real study. **Content:** Longitudinal data, or data collected multiple times from the same cases, is very exciting because it lets us see how people change in time. To collect it, we go back to the same respondents again and again. Unfortunately that also means that some of them will stop taking part. This is called **attrition**. In this guide, you will see how attrition bias appears, how survey methodologists measure it, how large it is in a real study and how the amount of attrition and the type of people who leave change our results. ## Start with a population Let’s imagine we want to know how healthy the people in a small town are. Each dot is one person with a physical health score between 0 and 100, where higher scores mean better health. The average for the whole town is 50, and this is the number we would like to estimate. *Hover or tap any dot to see that person’s score.* A town of 800 people Each dot is one person, placed by their health score ## Taking a random sample We rarely have the time or the money to ask everyone. So, we draw a **sample**, where every person has the same chance of being selected. The average health of the sample is close to that of the town, but it is rarely identical. Another sample would give a slightly different number. This is **sampling error**. It goes in both directions, gets smaller as samples get bigger and is what determines the size of confidence intervals or our precision. *Press “Draw another sample” a few times. Each tick under the dots is the average of one sample, and they scatter around the true value.* ## Not everyone takes part Selecting people is just the first step. We then have to find them and convince them to take part. Some will be away, some too busy and some will simply refuse. This is called **unit non-response**. When someone takes part but skips a question, we call it item non-response. Here, 4 in 10 of the people we selected do not take part (the hollow circles). For now they are a random subset of the sample, so the average of those who did take part stays close to the average of everyone we selected. We just have fewer people and a less precise estimate. ## Who does not take part matters Unfortunately, non-response is rarely random. People in poorer health might find a long interview harder, or be in hospital when the interviewer calls. In the figure, the people in poorer health are now less likely to take part, and the hollow circles bunch up on the left. Those who took part are healthier than the sample as a whole, so their average is pulled to the right. The gap between the average of those who took part and the average of everyone we selected is **non-response bias**. Unlike sampling error, it stays the same however big the sample is. A bigger sample would only give us a more precise estimate of the wrong value. ## Inviting the same people again In a longitudinal study we go back to the people who took part in the first wave and invite them again. Each column is now one wave, and each dot is one person. At every wave some people do not take part. This is **attrition**, and the losses add up. In [Understanding Society](https://www.understandingsociety.ac.uk/), a large UK panel study, about a quarter of the people from the first wave did not give a full interview in the second, and only half gave a full interview at all in the first five waves. Here, 16% of those still in the study leave at each wave, so about half remain by wave 5. Some people miss a wave and come back later, but not many. In Understanding Society, only about one in five of those missing at wave 2 gave a full interview again by wave 5, so here, once people leave, they do not come back. For now they leave at random, so the average of those still taking part (teal line) stays close to the average of everyone from the first wave (dashed line). ## When leaving is linked to health Now imagine that the people in poorer health are more likely to leave. The health of the group as a whole does not change (dashed line), but the average of those still taking part drifts up over the waves. The people who remain look healthier because the less healthy ones have left. If we took this at face value, we might conclude that health improves in time. So, attrition bias can look exactly like change, and it builds up with every wave. To make this easy to see, the link between health and leaving is much stronger here than in most real studies. We will look at real numbers in a moment. ## Measuring attrition bias Survey methodologists describe this bias with a simple formula. If we use the average of the people who took part to estimate the average of everyone we selected, the bias is: bias(*y*r) = *m*/*n* × (*y*r − *y*m) Where: - ***m*/*n*** is the share of the sample that did not take part, with *m* non-respondents out of *n* people selected. - ***y*r** is the average of those who took part. - ***y*m** is the average of those who did not. In the figure, the formula becomes a rectangle. The width is the share who did not take part, the height is how different they are from those who did, and the area is the bias. The starting values come from the non-response example above. *Drag the corner of the rectangle, or use the sliders, to try other combinations.* The curved lines join the combinations that give the same bias. For example, 20% non-response with a difference of 10 points gives a bias of 2 points, exactly like 50% non-response with a difference of 4 points. So, the response rate on its own tells us little about bias. We also need to know how different the people who are missing are. A [meta-analysis by Groves and Peytcheva](https://doi.org/10.1093/poq/nfn011) found that response rates are poor predictors of non-response bias. ## Attrition makes the rectangle wider The same formula works at every wave of a longitudinal study. Now *n* is the number of people who took part in the first wave, *m* is how many of them have left, and the difference is between those who stay and those who left. Each dot in the figure is one wave from the example where people in poorer health were more likely to leave. With every wave more people are missing, so the rectangle gets wider. The people who remain also become more and more different from those who left, so it usually gets taller too. So, attrition bias tends to grow over the life of a study. *Pick a wave under the figure to see its rectangle.* ## Attrition bias in a real study So far we have used simulated data, with a link between health and leaving that is stronger than usual. Let’s look at Understanding Society. In its general population sample, 41,046 people gave a full interview in the first wave. Of these, 76% gave one again in wave 2, 56% in wave 5 and 36% in wave 11. In a real study we do not know how healthy people are once they have left. We do know what everyone said in the first wave, so we can use the formula to calculate how much attrition biases the averages of those answers. The figure shows this bias for five variables, in standard deviations so they can be compared. The people who stay are more educated and better off. By wave 11, 27% of those still taking part have a degree, against 21% of everyone from the first wave, and their monthly income is about £200 higher. Health and life satisfaction are biased less, although the gap only opens up from wave 4. Before that, all the lines are close to zero. The share who left is almost the same for every variable, so the differences between them come from how different the leavers are on each one. *Pick a variable under the figure to see its numbers.* These biases look small, around a tenth of a standard deviation. That being said, for most variables they are still growing at wave 11. This is why panel studies such as Understanding Society provide weights. ## Simulating your own study Let’s put all of this together. Here you can choose how many people leave at each wave, how strongly leaving is linked to their health in the previous wave and how many people we follow. The teal line is the average of those still taking part, with its 95% confidence interval, and the dashed line is the true average of everyone we started with. The shaded area between them is the bias. A few things to note. When people leave at random, even heavy attrition mostly costs us precision. The intervals get wider, but they stay around the true value. When leaving is linked to health, attrition bias grows with every wave. Try “Realistic, like income”, which gives a bias about as large as the one for income in Understanding Society by wave 5. With 1,000 people the bias is lost in the sampling error and the interval includes the true value. With 10,000 people the interval is much narrower while the bias stays about the same, so the interval no longer includes the true value. | Wave | Taking part | Average, taking part | True average | Bias | |---|---|---|---|---| Simulated data. Bias is the average of those taking part minus the average of everyone we started with. ## What can we do about attrition bias? Prevent it Keeping people in the study is the most direct way to limit attrition. Panel studies keep in touch with participants between waves, trace those who move, offer incentives and try to keep the same interviewer. Measure it We know quite a lot about the people who leave, because we collected their data at the earlier waves. Comparing those who stay with those who leave on their first-wave answers tells us who is missing. The [post on measuring attrition bias](https://longitudinalanalysis.com/attrition-bias-what-is-it-and-how-to-measure-it/) shows how to do this in `R`. Correct for it Weights give more importance to the people who resemble those who left, and studies such as Understanding Society provide longitudinal weights. Models that use all the available data also help, such as the [multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) or a [latent growth model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) estimated with full information maximum likelihood, and so does multiple imputation. These methods only work when leaving depends on things we observed, such as health in the previous wave. Check how sensitive the results are If leaving depends on things we did not observe, such as a sudden drop in health just before the interview, no method can fully remove the bias. Sensitivity analyses show how much the results would change under different assumptions about the people who left. Want to go further? These ideas are the foundation of every longitudinal method. To learn how to apply them to your own data, take a course or read the book. [Browse the courses](https://longitudinalanalysis.com/#courses) [Get the book](https://longitudinalanalysis.com/#book) --- ### [Introduction to Longitudinal Data Analysis using R](https://longitudinalanalysis.com/intro-long-analysis-course/) **Published:** July 30, 2026 **Author:** Alex Cernat **Content:** Live online course · February 2027 # Introduction to Longitudinal Data Analysis using R Choose, fit and interpret the right longitudinal model for your research **A live online course with Prof. Alexandru Cernat, author of [*Longitudinal Data Analysis Using R*](https://leanpub.com/long-data-r). Learn how to use longitudinal analysis to answer your research questions.** - **Dates**1–12 Feb 2027 - **Time**08:00–11:00 Pacific 11:00–14:00 Eastern 16:00–19:00 UK - **Format**Live on Zoom, 10 × 3 hours - **Price**US$1,200, 20 places [Book your place](https://www.tickettailor.com/events/longitudinalanalysiscom/2477680?ref=website_button_top) [See the schedule](#schedule) Full refund within 14 days of booking or after the first session if it’s not for you Paying through your university or employer? [Request an institutional invoice](https://longitudinalanalysis.com/#contact) > *As a PhD researcher, this course helped me understand the various topics involved in longitudinal research and gave me the confidence to use R for analysis. I’d highly recommend it to any Early Career Researcher looking to build these skills!* > ★★★★★ > > *Vanessa Cieplinska, UCL, PhD Candidate* ## About the course Longitudinal data is essential for social and health research because it allows us to understand how people, organisations, and societies change, why events happen, and to support stronger causal inference. In this course, you will learn both how to clean longitudinal data and the main statistical models used to analyse it. The course will cover three fundamental frameworks for analysing longitudinal data: multilevel modelling, structural equation modelling and event history analysis. The course is organised as a mixture of lectures and hands-on practicals using real-world data. During the course, there will also be opportunities to discuss how to apply these models in your own research. The course runs over two weeks, three hours a day, so you can complete the guided reading for each session and apply the techniques we cover to your own research. This learn-apply-review format gives you time to consolidate each method, use it with your own data, and resolve problems while support is still available. The follow-up data clinics will further help you apply these methods to your own research. ### By the end of the course, you will be able to - Prepare and visualise longitudinal data in R - Choose between multilevel, SEM and event-history models - Fit and interpret the principal longitudinal approaches - Recognise their assumptions and limitations - Develop a defensible analysis plan for your own research ## Schedule Ten live sessions · 08:00–11:00 Pacific · 11:00–14:00 Eastern · 16:00–19:00 UK ### Week 1 · 1–5 February - **Mon 1 Feb**Longitudinal data preparation - **Tue 2 Feb**Longitudinal data visualisation - **Wed 3 Feb**Introduction to SEM and autoregressive models - **Thu 4 Feb**Cross-lagged models and longitudinal mediation - **Fri 5 Feb**Fixed effects and the multilevel model for change ### Week 2 · 8–12 February - **Mon 8 Feb**Advanced multilevel models for change - **Tue 9 Feb**Introduction to Latent Growth Modelling - **Wed 10 Feb**Advanced Latent Growth Modelling - **Thu 11 Feb**Longitudinal equivalence and second-order LGM - **Fri 12 Feb**Survival analysis in discrete and continuous time *All sessions are recorded (available for 30 days).* ## What’s included ### Before the course - ***[Introduction to R for Social Researchers](https://leanpub.com/c/leanpub/intro-r-social)*** – full on-demand course (RRP $250) - [***Mediation and Moderation Analysis using R*** ](https://leanpub.com/c/leanpub/mediation-moderation-r)– full on-demand course (RRP $200) ### During the course - **10 live 3-hour sessions**: live lectures + guided R practicals, support with your research and **30 days recording of class** - [***Longitudinal Data Analysis Using R***](https://leanpub.com/long-data-r) – the complete ebook (RRP $80) and recommended reading for each day - **[*The Ultimate Longitudinal Analysis Cheat Sheet*](https://leanpub.com/longitudinal-data-cheat-sheet)** (RRP $20) ### After the course - **Three live group data clinics** (RRP $400) after the course [Book your place](https://www.tickettailor.com/events/longitudinalanalysiscom/2477680?ref=website_button_included) > *This course provided me with the confidence to tackle large longitudinal datasets for the first time, giving a helpful and thorough overview of the primary methods in the field. In particular, the guided practicals and associated R code were extremely helpful in ensuring I understood how to apply these methods, and gave me the skills to use them in my own datasets.* > > Jessica Foley, Postdoctoral Scholar, Tufts University ## Your instructor ![Alexandru Cernat, professor](https://longitudinalanalysis.com/wp-content/uploads/2025/05/alexandru_cernat-768x683.webp) I’m **Alexandru Cernat**, Professor in Methodology and Social Data Science at the [University of Manchester](https://research.manchester.ac.uk/en/persons/alexandru.cernat). I have more than 10 years of experience doing research and teaching statistical methods, and hundreds of students from around the world have taken my classes. I’m the editor of [*Measurement Error in Longitudinal Data*](https://academic.oup.com/book/39454?login=false) and the author of[ *Longitudinal Data Analysis Using R*](https://leanpub.com/long-data-r). I’ve published over [50 peer-reviewed articles](https://scholar.google.com/citations?user=GOxqSVcAAAAJ&hl=en) in top journals and have served as an associate editor for the [Journal of the Royal Statistical Society A](https://academic.oup.com/jrsssa?login=false), [Journal of Survey Statistics and Methodology](https://academic.oup.com/jssam?login=false) and [Survey Research Methods](https://ojs.ub.uni-konstanz.de/srm/). Thousands of researchers use my guides at [longitudinalanalysis.com](https://longitudinalanalysis.com) every month to learn how to analyse their data. ## What participants say *This course was very comprehensive in scope and depth. I feel much more knowledgeable about different methods and models in longitudinal data analysis (including their strengths and weaknesses). The combination of having access to the book, listening to the lectures, and doing the practical exercises helped to acquire the knowledge in an efficient way.* P. Linh Nguyen, INED/University of Mannheim *Prof. Dr. Cernat is able to teach in a clear, engaging, and pedagogically effective way, regardless the prior knowledge and level of expertise of his students. He always provides clear answers to questions, no matter how specific or complex they are.* *Emir Zecovic, Federal Institute for Population Research (BiB), PhD Student* *I owe Alex’s 2018 course my ‘re-birth’ as an R data manager and analyst.* *Teresio Poggio, Research Assistant, University of Trento* *The course truly helped me develop a more systematic understanding of the longitudinal data analysis workflow and consolidate my previously fragmented experience with data analysis. I would recommend it to researchers seeking a clear, well-structured framework for planning and conducting longitudinal analyses.* *Jingjing Jiang, PhD student, Queen Mary, University of London* *The course provided a clear, structured overview of the different research models and the steps to follow in the correct order. I especially appreciated the opportunity to discuss my own research questions, with time for personalized feedback and guidance.* Ans De Wachter *Thoroughly recommend anything taught by Alex.* *Michelle Degli Esposti, Postdoctoral Researcher, University of Oxford* ## Frequently asked questions What are the prerequisites for this course? Basic knowledge of regression and R. Need to learn these? No worries, use the book and the on-demand courses included to get ready! Can’t make every session? Recordings of the lectures, solutions, and data clinics are available for 30 days from the date of recording. Software used? R and RStudio (free). Need to learn it? No problem; use the included course to get ready. When do I get access to the bonus content? You will get the bonuses immediately on enrolment. What is the cancellation/refund policy? Full refund within 14 days of booking, no questions asked. And if you attend the first session and find it’s not for you, email me that week, and I’ll refund you in full. Can my institution pay by invoice? Yes. If your university or employer needs to pay by invoice or purchase order, [contact me](https://longitudinalanalysis.com/#contact) with the participant’s name and email, your institution’s billing address and any purchase order number, and I will send you an invoice. Is there a certificate? Yes, you will receive a certificate at the end of the course. How do the data clinics work? You will submit questions about your own research in advance of the meeting. During the live online session, I will answer all the questions received. Meeting recordings will be available for 30 days from the date of recording. Which time zone applies? Sessions run 11:00–14:00 Eastern (08:00–11:00 Pacific, 16:00–19:00 UK). **If you have any other questions, feel free to [contact me](https://longitudinalanalysis.com/#contact)** ## Join the February cohort Ten live sessions on Zoom · 1–12 February 2027 · US$1,200 · 20 places [Book your place](https://www.tickettailor.com/events/longitudinalanalysiscom/2477680?ref=website_button_bottom) Paying through your institution? [Request an invoice](https://longitudinalanalysis.com/#contact) --- ### [Within and between variation](https://longitudinalanalysis.com/interactive/within-between/) **Published:** September 25, 2026 **Author:** Alex Cernat **Excerpt:** Longitudinal data carries two sources of variation at once. Pull them apart by hand, on income and on life satisfaction, and see what a multilevel model reports back. **Content:** Longitudinal data is exciting, because it can tell us how individuals change in time and it also lets us understand how much they differ in the first place. That said, it is more complex and harder to understand than data collected once. One of the key concepts you need to learn is the difference between **within-variation** and **between-variation**. ## Start with a simple graph Let us look at how individuals change in time based on some simulated data. Here we will focus on two examples: **income** and **satisfaction**. *Hover or tap any point to follow that individual.* Income Satisfaction Twelve individuals over four years Monthly income Dots Distributions ## Calculate each individual’s average One way to understand this data is to calculate the average for each individual. We have four values for each one, so we can simply take their average. That gives us an idea of what usually happens with this individual. *Here we follow just three people: the dashed line is that person’s average, and each orange stem is one year’s distance from it.* ## Two sources of variation If we take the difference between the individual average and the observed scores, we can separate two sources of variation. The **between variation** tells us how different people are from each other. The **within variation** tells us how different a particular time point is compared to that individual’s own average. ## How to calculate their relative importance? One interesting way to think about this is to ask how much variation there is at each level. What proportion is between, and what proportion is within? That tells us whether something is relatively stable in time or changes a lot, and whether people are very different from each other. We measure the amount of variation in each, and we represent the between variation as **σ²u** while the within one is **σ²e**. For these, a bigger number simply means a wider spread. Income has more between-person variation, while satisfaction has more within-variation. *Drag the slider under the figure and you will see that, depending on where you are, you get different combinations of between and within.* ## Testing it with a model We can test this formally by running a statistical model. There are a couple of ways to do it, but if we run something like a multilevel model we can calculate the amount of between- and within-variation. Simulated results based on the variances above lead to these results: | Parameter | Estimate | |---|---| The coefficient that captures the proportion of variation at each level is called the **ICC**, or intra-class correlation, and it tells us the proportion of variation that is between compared to within. ## Strategies for dealing with this complexity Get rid of the between variation altogether We can treat the data as a kind of quasi-experimental design, throw away all the between variation and keep only the within variation. This is what the fixed effects model does. Or model both sources at once The random effects model, the [multilevel model for change](https://longitudinalanalysis.com/estimating-and-visualizing-multilevel-models-for-change-in-r/) and the [latent growth model](https://longitudinalanalysis.com/estimating-and-visualizing-latent-growth-models-with-r/) all model both sources of variation, and let us see both how people change over time and how they differ from each other in their rates of change. They can also be added to other models, like the [cross-lagged model](https://longitudinalanalysis.com/understanding-causal-direction-using-the-cross-lagged-model/), to improve interpretation and assumptions. Want to go further? These ideas are the foundation of every longitudinal method. To learn how to apply them to your own data, take a course or read the book. [Browse the courses](https://longitudinalanalysis.com/#courses) [Get the book](https://longitudinalanalysis.com/#book) --- ### [Interactive guides](https://longitudinalanalysis.com/interactive/) **Published:** September 25, 2026 **Author:** Alex Cernat **Excerpt:** Interactive explainers for longitudinal data analysis: move the numbers yourself and watch what the model does. **Content:** Tools you can play with. Each one takes a single idea from longitudinal analysis and turns it into something you can move with your hands rather than read about: change the numbers, watch what the model does, and see where the intuition comes from. - [![Understanding attrition bias in longitudinal data](https://longitudinalanalysis.com/wp-content/uploads/2026/11/og-attrition-bias.webp)](https://longitudinalanalysis.com/interactive/attrition-bias/) Interactive guide ## [Understanding attrition bias in longitudinal data](https://longitudinalanalysis.com/interactive/attrition-bias/) An interactive guide to attrition bias in longitudinal data: how people leaving a study bias its results, how to measure it and how big it is in a real study. [Open the guide](https://longitudinalanalysis.com/interactive/attrition-bias/) - [![Within and between variation](https://longitudinalanalysis.com/wp-content/uploads/2026/09/og-within-between.webp)](https://longitudinalanalysis.com/interactive/within-between/) Interactive guide ## [Within and between variation](https://longitudinalanalysis.com/interactive/within-between/) Longitudinal data carries two sources of variation at once. Pull them apart by hand, on income and on life satisfaction, and see what a multilevel model reports back. [Open the guide](https://longitudinalanalysis.com/interactive/within-between/) --- ### [Privacy policy](https://longitudinalanalysis.com/privacy-policy/) **Published:** April 15, 2025 **Author:** Alex Cernat **Content:** **Last updated: 31 July 2026** ## 1. Who we are Alexandru Cernat, trading as LongitudinalAnalysis.com, is the data controller responsible for the personal information described in this policy. - Email: <contact@alexcernat.com> This policy applies when you visit longitudinalanalysis.com (the “Website”), contact us, subscribe to the newsletter, book or attend a course, or purchase another service directly from us. ## 2. Information we collect Depending on how you use the Website and our services, we may collect: - **Contact and professional details** — name, email address, address, employer or institution. - **Booking and payment details** — booking, payment-status, invoice and purchase-order information. Payment providers process full card details; we do not normally receive or store them. - **Course information** — attendance, questions, feedback and certificate details. - **Recordings** — your display name, voice, image, chat or screen where a recorded session captures your contribution. - **Correspondence** — messages, complaints, refund requests and other information you choose to submit. - **Newsletter information** — subscription status and email engagement. - **Technical information** — browser, device, pages visited, referral source, approximate location, IP address and cookie choices. We may also receive information from booking and payment providers, from an employer or institution booking on your behalf, or from platforms used to deliver content. ## 3. How and why we use information | Purpose | Lawful basis | |---|---| | Responding to enquiries and providing participant support | Legitimate interests | | Processing bookings, payments and refunds; delivering services, materials, recordings and certificates | Performance of a contract | | Sending the newsletter | Consent | | Producing Website statistics (Google Analytics) | Consent | | Maintaining security, preventing misuse, and improving the Website and our services | Legitimate interests | | Meeting accounting, tax and other legal obligations | Legal obligation | | Managing complaints and legal claims | Legitimate interests and legal obligation | Where we rely on legitimate interests, these are running, protecting and improving an independent training business. You can object to this processing (see section 9). We do not sell personal information or make solely automated decisions with legal or similarly significant effects. ## 4. Newsletter We use MailerLite to manage the newsletter and send marketing emails only to people who have subscribed. Subscription is optional and never a condition of booking. You can unsubscribe using the link in each marketing email or by contacting us. We keep a minimal suppression record so we do not add you back accidentally. Emails needed to administer a booking or deliver a purchased service are not marketing and may still be sent. ## 5. Cookies and Google Analytics Cookies store or access information on your device. Necessary cookies support security, basic functions and storage of your cookie choices. With your consent, we use Google Analytics to produce statistics about visits, pages viewed, referral sources, broad device information and approximate location, which we use to understand and improve the Website. Google Analytics runs only after you accept **Statistics** cookies. You can refuse them in the cookie banner or withdraw consent at any time via **Manage Consent** in the Website footer. We do not use Google Analytics for personalised advertising or remarketing, and we do not send names, email addresses or research data to Google. | Cookie | Purpose | Duration | |---|---|---| | `_ga` | Distinguishes browsers for Website statistics | Up to 2 years | | `_ga_` | Maintains Analytics session information | Up to 2 years | | Cookie-preference cookies | Remember your cookie choices | 30 days | Google may process Analytics information outside the UK. Google states that GA4 uses IP addresses only to derive approximate location and discards them before they are logged or stored. We do not currently use behavioural-advertising or cross-site remarketing cookies. If this changes, we will update this policy and request any consent required. ## 6. Recordings and group sessions The relevant course or service page will state whether sessions are recorded and how long recordings remain available. A recording may capture your display name, voice, image, chat or screen if you choose to contribute; you may normally keep your camera and microphone off, or contact us before a session if you have concerns. Do not submit identifiable, confidential or sensitive personal data about research participants, patients, employees or anyone else — use synthetic, anonymised or appropriately de-identified material. Information you share in a group session may be visible to other participants, so do not share anything that would cause harm if disclosed. ## 7. Sharing and international transfers Where necessary, we share information with providers that support the business: website hosting, security, email and IT; analytics; bookings and payments; online teaching; newsletter delivery; digital content; and professional advice. These currently include Google Analytics, Ticket Tailor, Stripe, Zoom, MailerLite and Leanpub, where relevant. We may also disclose information where required by law. We do not sell personal information. Some providers process information outside the UK. Where required, we rely on an adequacy decision, contractual safeguards or another lawful transfer mechanism. ## 8. Retention We keep information only as long as reasonably necessary: - booking, invoice and contractual records — up to six years; - course recordings — for the period advertised, normally 30 days; - routine enquiries — normally up to two years; - newsletter information — until you unsubscribe, then a minimal suppression record; - testimonials — until consent is withdrawn or they are no longer relevant; and - Analytics information and cookies — for the durations described above. Information may be kept longer where the law requires or while a complaint or claim is being handled. ## 9. Your rights Depending on the circumstances, you may have the right to access or correct your information, request deletion or restriction, object to processing — including an absolute right to object to direct marketing — receive certain information in a portable format, and withdraw consent at any time. To exercise a right, email <contact@alexcernat.com>. We may ask for reasonable information to confirm your identity, and we will normally respond within one month, free of charge. You may also complain to the Information Commissioner’s Office at <https://ico.org.uk/make-a-complaint/> or on 0303 123 1113. ## 10. Security, external websites and changes We use reasonable measures to protect personal information, but no internet service is completely secure. Do not send confidential or identifiable research data through ordinary email or Website forms. The Website may link to or embed third-party services; their own privacy policies apply when you use them. We may update this policy when our services, providers or legal obligations change. The current version, with its date, will always be published on the Website. Questions: <contact@alexcernat.com>. --- ### [Terms](https://longitudinalanalysis.com/terms/) **Published:** April 15, 2025 **Author:** Alex Cernat **Content:** **Last updated: 31 July 2026** ## 1. About us LongitudinalAnalysis.com is operated by **Alexandru Cernat trading as LongitudinalAnalysis.com** (“we”, “us”, “our”). - Email: contact@alexcernat.com Unless expressly stated otherwise, our courses and services are provided independently and are not provided, accredited or endorsed by the University of Manchester or any other institution. ## 2. These Terms These Terms apply to longitudinalanalysis.com (the “Website”) and to courses, mentoring, digital materials and other services purchased directly from us. The description of the specific product or service — including price, dates, format, content, prerequisites, recordings, bonuses and any special guarantee — also forms part of your contract. If it conflicts with these Terms, the description takes priority for that purchase. Purchases made through another platform (for example, Leanpub) are also subject to that platform’s terms. ## 3. Booking and payment Your contract is formed when we or our booking provider send confirmation. The total price, in pounds sterling and including any applicable VAT, is shown before purchase and will not change after confirmation. Payments may be handled by third-party booking and payment providers; we do not normally receive or store full card details. If an employer or institution books for a participant, the person booking confirms that they are authorised to do so and that the participant has received these Terms. ## 4. Courses and services We will provide paid services with reasonable care and skill and substantially as described. We may make reasonable changes to topics, examples, platforms or timetables where these do not materially reduce the service’s value. If we make a material change to dates, format, instructor or core content, we will notify you; if the change materially disadvantages you, you may cancel for an appropriate refund. You are responsible for suitable equipment, internet access and any software or prerequisite knowledge stated in the description. Certificates, where offered, are issued by LongitudinalAnalysis.com and confirm participation or completion only. Unless expressly stated otherwise, they carry no academic credit, professional accreditation or university endorsement. Our content is educational. We do not guarantee any particular academic, professional, publication or analytical result. Statistical analysis requires judgement, and you remain responsible for checking your own work and decisions. ## 5. Materials, recordings and group sessions The Website, course materials, code, exercises, templates and recordings belong to us or the relevant rights holder. You receive a personal, non-transferable licence to use supplied materials for your own learning and non-commercial research. You must not share, publish, sell or redistribute substantial parts of them, give others access to your account, or record a live session without permission. The relevant description will state whether sessions are recorded and how long recordings remain available; our Privacy and Cookie Policy explains how recordings and participant information are handled. You may normally keep your camera and microphone off. Do not share identifiable, confidential or sensitive information about research participants, patients, employees or anyone else — use synthetic, anonymised or appropriately de-identified examples. Other participants may see what you share in group sessions; everyone must respect confidentiality, but we cannot guarantee another participant’s conduct. ## 6. Your cancellation and refund rights ### Within 14 days If you book online, you may cancel for any reason within 14 days beginning the day after your booking confirmation. Email contact@alexcernat.com with your name and booking number, or use the model cancellation form below. You do not need to give a reason. Any refund due will be returned to the original payment method without undue delay and no later than 14 days after we receive your cancellation. This 14-day policy also applies where an employer or institution pays, unless separate written terms were agreed. If you expressly ask for a live service to begin within the 14-day period, we may deduct a reasonable amount for the part already provided. If you expressly consent to immediate supply of standalone digital content and acknowledge that you lose your cancellation right, that right ends when supply begins. Access to preliminary materials or bonuses included with a live course does not remove any more generous refund guarantee stated on that course’s page. ### After 14 days Any additional refund or money-back guarantee stated on the relevant product or service page will apply. Otherwise, refunds after 14 days are not automatic: we may consider a transfer or refund where we can resell the place, taking account of our reasonable costs and loss. Non-attendance does not normally entitle you to a refund. ## 7. Cancellation or changes by us A course may depend on minimum enrolment; any threshold and confirmation date will be stated in its description. If we cancel before a service begins, we will refund the full amount paid to us. Any entitlement to keep bonuses or materials will be as stated in the relevant description. If we reschedule or cannot deliver part of a service, we will offer a replacement or reasonable alternative. If that is not reasonably possible, or a material change prevents you from attending, we will refund the affected part. We are not responsible for travel, accommodation or other costs unless the law requires otherwise. ## 8. Conduct Participants must behave professionally and must not harass others, disrupt teaching, misuse access links, compromise security or infringe anyone’s rights. We may restrict or remove someone for serious or repeated misconduct; any refund will take account of the service already supplied and our reasonable loss. ## 9. Liability Nothing in these Terms excludes liability for death or personal injury caused by negligence, for fraud, for breach of your statutory consumer rights, or for anything else that cannot legally be excluded. If you are a consumer, we are responsible for foreseeable loss caused by our breach of these Terms or our failure to use reasonable care and skill. We are not responsible for loss that we did not cause or that was not reasonably foreseeable. If you purchase wholly or mainly for business purposes, our total liability relating to a purchase will not exceed the amount paid for it, and we will not be liable for indirect loss, lost profits or lost business, except where liability cannot legally be limited. ## 10. Privacy, complaints and law We process personal information as described in our Privacy and Cookie Policy. We are not responsible for third-party websites or services we do not control. Send complaints to contact@alexcernat.com with your name, the relevant purchase and a brief description of the problem. We aim to acknowledge complaints within five working days and respond within 14 working days. These Terms are governed by the law of England and Wales. Consumers retain any mandatory rights and access to the courts available under the law where they live. We may update these Terms for future purchases. The version in force when your contract was formed continues to apply to that purchase unless the law requires otherwise or you agree to a change. ## Model cancellation form You may cancel with a clear email or use the following: > To: Alexandru Cernat, contact@alexcernat.com I wish to cancel my booking for: Name: Booking number and date: Date of cancellation: --- ### [Newsletter](https://longitudinalanalysis.com/newsletter/) **Published:** March 21, 2025 **Author:** Alex Cernat **Content:** # Get actionable info on longitudinal research in your inbox Join and receive: 1. **The longitudinal analysis checklist.** 63 checks across planning, data preparation, modelling, validation, and reporting. A PDF to keep next to every project, sent to you immediately. 2. **The code and data behind every guide.** Access to the R code and datasets used across the site, so you can rerun and adapt everything you read. 3. **Updates** from the website with new guides and actionable information for your research. ## Who writes it I’m [Alexandru Cernat](http://alexcernat.com), Professor of Methodology and Social Data Science at the University of Manchester. I’ve published more than 50 peer-reviewed papers using longitudinal data, and this newsletter is where I share the practical side of that work. ![Alexandru Cernat, professor](https://longitudinalanalysis.com/wp-content/uploads/2025/05/alexandru_cernat-1024x911.webp) --- ### [Longitudinal analysis mentorship](https://longitudinalanalysis.com/longitudinal-analysis-mentorship/) **Published:** June 27, 2026 **Author:** Alex Cernat **Content:** ## One-to-one help with your longitudinal research The most valuable part of every course I teach is the same thing: discussing people’s own research. Many researchers working with longitudinal data are the only person in their department doing so. Your supervisor and colleagues know your substantive field, but there is often no one to ask whether a fixed effects model fits your question, why your growth model won’t converge, or how to respond to a reviewer’s comment about attrition. Mentorship sessions exist for exactly that situation. ## What a session is A mentorship session is a 60-minute one-to-one video call focused entirely on your project. When you book, you send a short description of your research project and where you are stuck. I read everything in advance, so we spend the session working on the problem. ## What we can work on Study design and planning your analysis, choosing between models, preparing longitudinal data, understanding and interpreting output, writing up findings, responding to reviewer comments, and deciding what to do next. If your problem isn’t on this list, [ask](https://longitudinalanalysis.com/#contact). If I don’t think a session will help, I will tell you so before you book. ## How it works 1. **Book and pay online.** Pick a time that works for you; payment confirms the booking. 2. **Send your materials.** The booking form asks the information we need. 3. **We meet.** A video call working through your problem together. ## Is it for you? A session works best when you have a concrete project and a specific problem to solve. If you are at the beginning of learning longitudinal analysis, the [guides](https://longitudinalanalysis.com/guides), [courses](https://longitudinalanalysis.com/courses), and [book ](https://longitudinalanalysis.com/#book)will serve you better and cost you less. [Book mentorship session](https://cal.eu/alex-c/mentorship-meeting) --- ### [](https://longitudinalanalysis.com/thank-you/) **Published:** January 23, 2026 **Author:** Alex Cernat **Content:** ![](https://longitudinalanalysis.com/wp-content/uploads/2024/02/stock-1863880_1920-1024x683.jpg) ## **Thank you!** I’m so happy you decided to join our newsletter to get more in-depth knowledge of Longitudinal Data Analysis. **You can access your present [HERE](https://www.alexcernat.com/longitudinalanalysis.com/lda_cheatsheet_vis_v1.pdf).** --- **Want another quick win in your journey to master longitudinal data?** I’ve put together all you need to know about the key concepts, commands and models in the [Ultimate Cheat Sheet for Longitudinal Data Analysis](https://leanpub.com/longitudinal-data-cheat-sheet). Because you’ve put your trust in me by signing up, I’m going to give it to you at half price if you buy in the next 60 minutes. [👉 Get the Cheat Sheet for only $10](https://leanpub.com/longitudinal-data-cheat-sheet/c/31B7AD56F638) ![Alexandru Cernat, professor](https://longitudinalanalysis.com/wp-content/uploads/2025/05/alexandru_cernat-1024x911.webp) --- ### [Forum](https://longitudinalanalysis.com/community/) **Published:** January 8, 2026 **Author:** Alex Cernat **Content:** - [Forums](https://longitudinalanalysis.com/community/) - [Recent Posts](https://longitudinalanalysis.com/community/recent/) [Forums](# "Forums") Notifications Clear all # Longitudinal Analysis Forum [ Unread Posts ](https://longitudinalanalysis.com/community/recent/?view=unread)  \|  [ Forums ](https://longitudinalanalysis.com/wp-cron.php?type=rss2&forum=g "Forums RSS Feed")  \|  [ Topics ](https://longitudinalanalysis.com/wp-cron.php?type=rss2&forum=g&topic=g "Topics RSS Feed") Share: [ ](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Flongitudinalanalysis.com%2Fcommunity%2F) [ ](https://twitter.com/intent/tweet?text=&url=https%3A%2F%2Flongitudinalanalysis.com%2Fcommunity%2F) [ ](https://web.whatsapp.com/send?text=Longitudinal+Analysis+Forum%20URL:%20https%3A%2F%2Flongitudinalanalysis.com%2Fcommunity%2F) Forum Information [ Tags](https://longitudinalanalysis.com/community/tags/) Our newest member: [andrebda](https://longitudinalanalysis.com/participant/andrebda/ "andrebda") Forum Icons: Forum contains no unread posts Forum contains unread posts Topic Icons: Not Replied Replied Active Hot Sticky Unapproved Solved Private Closed [ Powered by wpForo version 3.2.5](https://wordpress.org/plugins/wpforo/) --- ### [Longitudinal Data Analysis Using R](https://longitudinalanalysis.com/long-data-r-extra/) **Published:** June 17, 2025 **Author:** Alex Cernat **Content:** # Supplemental materials This page includes code and supplemental materials for the [Longitudinal Data Analysis Using R](https://leanpub.com/long-data-r) book. #### Accessing the data The primary dataset used throughout this book is Understanding Society. This is a large yearly panel based in the UK. The data can be accessed for free from the [UK Data Archive](https://beta.ukdataservice.ac.uk/datacatalogue/studies/study?id=6614). [![](https://longitudinalanalysis.com/wp-content/uploads/2024/02/cover_11.png)](http://leanpub.com/long-data-r) ## Code from book | **Chapter** | **R code** | **Mplus** | **Stata** | |---|---|---|---| | 2. Introduction to R | *[Link](http://alexcernat.com/long-data-r-code/02-basics-R.R)* | | | | 3. Preparing Longitudinal Data | **[Link](http://alexcernat.com/long-data-r-code/03-data-clean.R)** | ***[Export clean data to Mplus](http://alexcernat.com/long-data-r-code/mplus/mplus_export.R)*** | | | 4. Describing Longitudinal Data | **[Link](http://alexcernat.com/long-data-r-code/04-describe.R)** | | | | 5. Introduction to Regression Models | **[Link](http://alexcernat.com/long-data-r-code/05-regression.R)** | ***[Link](http://alexcernat.com/long-data-r-code/mplus/ch5.zip)*** | *Coming soon* | | 6. Introduction to Path Analysis | **[Link](http://alexcernat.com/long-data-r-code/06-path.R)** | ****[Link](http://alexcernat.com/long-data-r-code/mplus/ch6.zip)**** | *Coming soon* | | 7. Fixed and Random Effects | **[Link](http://alexcernat.com/long-data-r-code/07-fixed-random.R)** | ****[Link](http://alexcernat.com/long-data-r-code/mplus/ch7.zip)**** | *Coming soon* | | 8. The Cross-Lagged Models | **[Link](http://alexcernat.com/long-data-r-code/08-cross-lagged.R)** | ****[Link](http://alexcernat.com/long-data-r-code/mplus/ch8.zip)**** | *Coming soon* | | 9. The Multilevel Model for Change | **[Link](http://alexcernat.com/long-data-r-code/09-multilevel-model.R)** | *****[Link](http://alexcernat.com/long-data-r-code/mplus/ch9.zip)***** | *Coming soon* | | 10. The Latent Growth Model | **[Link](http://alexcernat.com/long-data-r-code/10-latent-growth.R)** | *****[Link](http://alexcernat.com/long-data-r-code/mplus/ch10.zip)***** | *Coming soon* | | 11. Measurement Error and Longitudinal Data | **[Link](http://alexcernat.com/long-data-r-code/12-measurement.R)** | ******[Link](http://alexcernat.com/long-data-r-code/mplus/ch11.zip)****** | *Coming soon* | | 12. Dealing with Missing Data | **[Link](http://alexcernat.com/long-data-r-code/13_missing.R)** | *******[Link](http://alexcernat.com/long-data-r-code/mplus/ch12.zip)******* | *Coming soon* | | 13. Workflows and Presenting Results | **[Link](http://alexcernat.com/long-data-r-code/14-present.R)** | | | --- ### [About LongitudinalAnalysis.com](https://longitudinalanalysis.com/about/) **Published:** February 2, 2024 **Author:** alexcernat **Content:** Many researchers turn to longitudinal data to address critical questions, but quickly find themselves lost, unsure where to begin, overwhelmed by complex methods, and faced with scattered or unclear guidance. **LongitudinalAnalysis.com** was created to support their journey. We offer practical tools, real-world examples, and clear explanations to help researchers learn how to collect data, choose the right models, interpret results and communicate findings effectively. But our mission goes further. LongitudinalAnalysis.com exists to help researchers become independent thinkers confident in their methods, clear in their communication, and capable of producing insights that matter. > ***LongitudinalAnalysis.com** was created to support their journey.* ### What We Stand For ### **Clarity** We believe great ideas should be easy to grasp. That’s why we break down advanced concepts into clear, structured explanations that guide and support our users. ### **Rigour** We combine methodological depth with hands-on learning. Every tool and example is grounded in real-world data. ### **Craft** We take pride in producing well-structured, effective learning materials. Every tutorial, tool, and example is carefully crafted to make complex concepts easier to understand. ### **Curiosity** We’re driven by curiosity and a love of learning. We explore ideas across disciplines to find the best tools, methods, and ways to teach them. ### **Community** We’re part of a broader research community and contribute back. We share what we learn, support open resources, and aim to raise the standard of applied research. ### What We Do ## We help researchers and organisations work confidently with longitudinal data through practical resources, real-world examples, and clear, applied guidance. Our mission is to make complex methods intuitive, effective, and part of everyday research practice. ![](https://longitudinalanalysis.com/wp-content/uploads/2025/05/alexandru_cernat-1024x911.webp) ## Meet the Creator **[Alexandru Cernat](http://alexcernat.com)** is a [Professor at the University of Manchester](https://research.manchester.ac.uk/en/persons/alexandru.cernat), specialising in collecting and analysing longitudinal data. Over the past decade, he has published over 50 papers and book chapters using advanced models to study how people and societies change. His work bridges survey methodology, social statistics, and data science. This website brings together his experince and expertise offering practical tools, real-world examples, and clear explanations to help you master longitudinal data. --- ### [Cookie Policy (EU)](https://longitudinalanalysis.com/cookie-policy-eu/) **Published:** April 28, 2025 **Author:** Alex Cernat **Content:** *This Cookie Policy was last updated on June 19, 2025 and applies to citizens and legal permanent residents of the European Economic Area and Switzerland.* ## 1. Introduction Our website, <https://longitudinalanalysis.com> (hereinafter: “the website”) uses cookies and other related technologies (for convenience all technologies are referred to as “cookies”). Cookies are also placed by third parties we have engaged. In the document below we inform you about the use of cookies on our website. ## 2. What are cookies? A cookie is a small simple file that is sent along with pages of this website and stored by your browser on the hard drive of your computer or another device. The information stored therein may be returned to our servers or to the servers of the relevant third parties during a subsequent visit. ## 3. What are scripts? A script is a piece of program code that is used to make our website function properly and interactively. This code is executed on our server or on your device. ## 4. What is a web beacon? A web beacon (or a pixel tag) is a small, invisible piece of text or image on a website that is used to monitor traffic on a website. In order to do this, various data about you is stored using web beacons. ## 5. Cookies ### 5.1 Technical or functional cookies Some cookies ensure that certain parts of the website work properly and that your user preferences remain known. By placing functional cookies, we make it easier for you to visit our website. This way, you do not need to repeatedly enter the same information when visiting our website and, for example, the items remain in your shopping cart until you have paid. We may place these cookies without your consent. ### 5.2 Statistics cookies We use statistics cookies to optimize the website experience for our users. With these statistics cookies we get insights in the usage of our website. We ask your permission to place statistics cookies. ## 6. Placed cookies ### WordPress Functional Consent to service wordpress #### Usage We use WordPress for website development. [Read more about WordPress](https://cookiedatabase.org/service/wordpress/) #### Sharing data This data is not shared with third parties. #### Functional ##### Name [WP\_PREFERENCES\_USER\_\*](https://cookiedatabase.org/cookie/wordpress/wp_preferences_user_/) ##### Expiration persistent ##### Function Store user preferences ##### Name [wpEmojiSettingsSupports](https://cookiedatabase.org/cookie/wordpress/wpemojisettingssupports/) ##### Expiration session ##### Function Store browser details ##### Name [wp-settings-\*](https://cookiedatabase.org/cookie/wordpress/wp-settings/) ##### Expiration persistent ##### Function Store user preferences ##### Name [wp-settings-time-\*](https://cookiedatabase.org/cookie/wordpress/wp-settings-time/) ##### Expiration 1 year ##### Function Store user preferences ##### Name [wordpress\_test\_cookie](https://cookiedatabase.org/cookie/wordpress/wordpress_test_cookie/) ##### Expiration session ##### Function Read if cookies can be placed ##### Name [wordpress\_logged\_in\_\*](https://cookiedatabase.org/cookie/wordpress/wordpress_logged_in_/) ##### Expiration persistent ##### Function Store logged in users ### Complianz Functional Consent to service complianz #### Usage We use Complianz for cookie consent management. [Read more about Complianz](https://cookiedatabase.org/service/complianz/) #### Sharing data This data is not shared with third parties. For more information, please read the [Complianz Privacy Statement](https://complianz.io/legal/privacy-statement/). #### Functional ##### Name [cmplz\_functional](https://cookiedatabase.org/cookie/complianz/cmplz_functional/) ##### Expiration 365 days ##### Function Store cookie consent preferences ##### Name [cmplz\_statistics](https://cookiedatabase.org/cookie/complianz/cmplz_statistics/) ##### Expiration 365 days ##### Function Store cookie consent preferences ##### Name [cmplz\_preferences](https://cookiedatabase.org/cookie/complianz/cmplz_preferences/) ##### Expiration 365 days ##### Function Store cookie consent preferences ##### Name [cmplz\_marketing](https://cookiedatabase.org/cookie/complianz/cmplz_marketing/) ##### Expiration 365 days ##### Function Store cookie consent preferences ##### Name [cmplz\_consented\_services](https://cookiedatabase.org/cookie/complianz/cmplz_consented_services/) ##### Expiration 365 days ##### Function Store cookie consent preferences ##### Name [cmplz\_policy\_id](https://cookiedatabase.org/cookie/complianz/cmplz_policy_id/) ##### Expiration 365 days ##### Function Store accepted cookie policy ID ##### Name [cmplz\_banner-status](https://cookiedatabase.org/cookie/complianz/cmplz_banner-status/) ##### Expiration 365 days ##### Function Store if the cookie banner has been dismissed ### Miscellaneous Purpose pending investigation Consent to service miscellaneous #### Usage #### Sharing data Sharing of data is pending investigation #### Purpose pending investigation ##### Name jetpack-boost-guide ##### Expiration ##### Function ##### Name WP_DATA_USER_2 ##### Expiration ##### Function ##### Name helpVisible ##### Expiration ##### Function ##### Name cookieyes-consent ##### Expiration ##### Function ##### Name nfd_global_ctb_url_token ##### Expiration ##### Function ##### Name nocache_bfcache_js_enabled ##### Expiration ##### Function ##### Name jetpack_sso_original_request ##### Expiration ##### Function ##### Name jetpack_sso_nonce ##### Expiration ##### Function ##### Name cmplz_cookie_data ##### Expiration 365 days ##### Function ##### Name mailerlite_forms_shown_112420293906007408 ##### Expiration ##### Function ##### Name wpforo_read_topics ##### Expiration ##### Function ##### Name wpforo_read_forums ##### Expiration ##### Function ## 7. Consent When you visit our website for the first time, we will show you a pop-up with an explanation about cookies. As soon as you click on “Accept”, you consent to us using all cookies and plug-ins as described in the pop-up and this Cookie Policy. You can disable the use of cookies via your browser, but please note that our website may no longer work properly. ### 7.1 Manage your consent settings You have loaded the Cookie Policy without javascript support. On AMP, you can use the manage consent button on the bottom of the page. ## 8. Enabling/disabling and deleting cookies You can use your internet browser to automatically or manually delete cookies. You can also specify that certain cookies may not be placed. Another option is to change the settings of your internet browser so that you receive a message each time a cookie is placed. For more information about these options, please refer to the instructions in the Help section of your browser. Please note that our website may not work properly if all cookies are disabled. If you do delete the cookies in your browser, they will be placed again after your consent when you visit our website again. ## 9. Your rights with respect to personal data You have the following rights with respect to your personal data: - You have the right to know why your personal data is needed, what will happen to it, and how long it will be retained for. - Right of access: You have the right to access your personal data that is known to us. - Right to rectification: you have the right to supplement, correct, have deleted or blocked your personal data whenever you wish. - If you give us your consent to process your data, you have the right to revoke that consent and to have your personal data deleted. - Right to transfer your data: you have the right to request all your personal data from the controller and transfer it in its entirety to another controller. - Right to object: you may object to the processing of your data. We comply with this, unless there are justified grounds for processing. To exercise these rights, please contact us. Please refer to the contact details at the bottom of this Cookie Policy. If you have a complaint about how we handle your data, we would like to hear from you, but you also have the right to submit a complaint to the supervisory authority (the Data Protection Authority). ## 10. Contact details For questions and/or comments about our Cookie Policy and this statement, please contact us by using the following contact details: Longitudinal Analysis Oxford Road, Manchester, UK United Kingdom Website: <https://longitudinalanalysis.com> Email: 6k1ctyiq@ex.comduck.com This Cookie Policy was synchronized with [cookiedatabase.org](https://cookiedatabase.org/) on June 11, 2025. --- ## Categories ### [data management](https://longitudinalanalysis.com/category/data-management/) --- ### [visualization](https://longitudinalanalysis.com/category/visualization/) --- ### [longitudinal data analysis](https://longitudinalanalysis.com/category/longitudinal-data-analysis/) --- ### [communication](https://longitudinalanalysis.com/category/communication/) --- ### [statistics](https://longitudinalanalysis.com/category/statistics/) --- ## Tags ### [longitudinal data analysis](https://longitudinalanalysis.com/tag/longitudinal-data-analysis/) --- ### [r](https://longitudinalanalysis.com/tag/r/) --- ### [data management](https://longitudinalanalysis.com/tag/data-management/) --- ### [data cleaning](https://longitudinalanalysis.com/tag/data-cleaning/) --- ### [data restructuring](https://longitudinalanalysis.com/tag/data-restructuring/) --- ### [structural equation modelling](https://longitudinalanalysis.com/tag/structural-equation-modelling/) --- ### [latent growth modelling](https://longitudinalanalysis.com/tag/latent-growth-modelling/) --- ### [visualization](https://longitudinalanalysis.com/tag/visualization/) --- ### [multilevel modeling](https://longitudinalanalysis.com/tag/multilevel-modeling/) --- ### [descriptive statistics](https://longitudinalanalysis.com/tag/descriptive-statistics/) --- ### [tables](https://longitudinalanalysis.com/tag/tables/) --- ### [summaries](https://longitudinalanalysis.com/tag/summaries/) --- ### [data exploration](https://longitudinalanalysis.com/tag/data-exploration/) --- ### [Mplus](https://longitudinalanalysis.com/tag/mplus/) --- ### [communication](https://longitudinalanalysis.com/tag/communication/) --- ### [path analysis](https://longitudinalanalysis.com/tag/path-analysis/) --- ### [mediation](https://longitudinalanalysis.com/tag/mediation/) --- ### [moderation](https://longitudinalanalysis.com/tag/moderation/) --- ### [statistics](https://longitudinalanalysis.com/tag/statistics/) --- ### [mediation analysis](https://longitudinalanalysis.com/tag/mediation-analysis/) --- ### [causality](https://longitudinalanalysis.com/tag/causality/) --- ### [AI](https://longitudinalanalysis.com/tag/ai/) --- ### [data analysis](https://longitudinalanalysis.com/tag/data-analysis/) ---