MariNET - A Novel Framework for Inferring Dynamic Network Relationships from Longitudinal EHRs Using Linear Mixed Models

Introduction to MariNET

The MariNET package provides tools for analyzing longitudinal clinical data using linear mixed models (LMM) and visualizing the results as networks. This vignette demonstrates how to use the package to perform longitudinal analysis and generate network plots.

The purpose of this vignette is to showcase the functionality of the package, including:

  • Fitting linear mixed models to clinical data
  • Visualizing the results as networks
  • Comparing different network structures

Installation

You can install MariNET package from CRAN using:

#install.packages("MariNET")
library("MariNET")

Loading Data

In this section, we will load the dataset included in the package. Sample data was obtained from previous Assesment study about relationships between COVID-19 and clinical variables related to mental health and social contact (Fried et al. 2022).

# Load the dataset from the package
data(example_data)

# Display the first few rows
head(example_data)
#>   id Relax Irritable Worry Nervous Future Anhedonia Tired Hungry Alone Angry
#> 1  1     1         1     2       1      1         1     2      3     1     2
#> 2  1     2         1     2       1      1         1     1      2     1     2
#> 3  1     1         1     3       1      1         1     2      3     1     1
#> 4  1     1         1     3       2      1         1     2      2     1     1
#> 5  1     1         1     2       1      1         1     2      3     1     1
#> 6  1     3         2     2       1      1         1     1      2     1     1
#>   Social_offline Social_online Music Procrastinate Outdoors C19_occupied
#> 1              3             3     2             1        1            3
#> 2              5             3     2             2        2            2
#> 3              4             4     3             3        1            3
#> 4              5             3     1             3        1            3
#> 5              2             3     1             1        1            2
#> 6              4             4     2             2        2            2
#>   C19_worry Home day beep conc
#> 1         2    5   1    0    1
#> 2         2    5   1    1    2
#> 3         1    5   1    2    3
#> 4         2    5   1    3    4
#> 5         1    5   2    0    5
#> 6         1    4   2    1    6

Linear Mixed effects Model network

The present package is focused on the use of linear mixed models in the field of network construction. It should be noted that the described methodology could be applied to different fields of information, as the origin of the data itself makes no difference in the method’s applicability (Bates et al. 2015).

For network construction, a separate linear mixed model is created for each clinical variable, including the others as dependent ones. This process was repeated iteratively for each variable, as performed on previous studies (Velden et al. 2018).

# Extract column names from the dataset
# These represent all available variables in the dataset
varLabs <- colnames(example_data)

# Define a list of variables to be removed from the analysis
# These variables are not included as nodes in the network visualization
remove <- c("id", "day", "beep", "conc")

# Filter out the unwanted variables
# Keeps only the variables that are not in the "remove" list
varLabs <- varLabs[!varLabs %in% remove]

# Print the final list of selected variables to be used as nodes in the network
print(varLabs)
#>  [1] "Relax"          "Irritable"      "Worry"          "Nervous"       
#>  [5] "Future"         "Anhedonia"      "Tired"          "Hungry"        
#>  [9] "Alone"          "Angry"          "Social_offline" "Social_online" 
#> [13] "Music"          "Procrastinate"  "Outdoors"       "C19_occupied"  
#> [17] "C19_worry"      "Home"

The function lmm_analysis() is the main tool of this package. It requires input data with the following conditions:

  • clinical_data: Dataframe containing clinical and metadata for participants, including identifier as participant_id. Make sure this is the first column of the dataframe.
  • variables_to_scale: Character vector of variable names to be analyzed, must be numerical as they are scaled.
  • random_effects: A character string specifying the random effects formula (default: “(1 | participant_id)”).
# Perform Linear Mixed Model (LMM) analysis on the dataset
# This function iterates over selected variables (varLabs) and models their relationships
# while accounting for individual-level variability using a random effect.

model <- lmm_analysis(
  example_data,   # Input dataset containing clinical/longitudinal data
  varLabs,        # List of selected variables to be analyzed in the model
  random_effects = "(1|id)"  # Specifies a random intercept for each individual (id)
)

# Print the model results (optional, useful for debugging or reviewing output)
# print(model)

Network visualization

In order to visualize the plot according to grouping factors, it is important to add a structure to the data. This means grouping or selecting colors to differentiate between correlated symptoms. Visualization is based on qgraph package (Epskamp et al. 2023).

# Define the community structure for the variables
# Assigns labels to different groups based on symptoms or categories
community_structure <- c(
  rep("Stress", 8),   # First 8 variables belong to the "Stress" group
  rep("Social", 6),   # Next 6 variables belong to the "Social" group
  rep("Covid-19", 4)  # Last 4 variables belong to the "Covid-19" group
)

# Create a dataframe linking variable names to their assigned community group
structure <- data.frame(varLabs, community_structure)

# Define labels for the network plot (using variable names)
labels <- varLabs

# Load the qgraph package for network visualization
library(qgraph)

# Generate the network plot using qgraph
qgraph(
  model,                                # Adjacency matrix or network model input
  groups = structure$community_structure, # Assign colors based on community groups
  labels = labels,                        # Display variable names as node labels
  legend = TRUE,                           # Include a legend in the plot
  layout = "spring",                       # Use a force-directed "spring" layout for better visualization
  color = c("orange", "lightblue", "#008080"), # Define colors for different groups
  legend.cex = 0.3                          # Adjust the size of the legend text
)

Comparison between models

As the weighted matrix is built based on t-values, it is not contained between -1 and 1 values. This means that it is not comparable with usual network modeling methods, which rely on correlation and pairwise estimation. For comparability purposes, normalization is performed on the adjacency matrix, scaling values by range. Then, normalized weighted matrices are subtracted to see differences.

# Fit a second Linear Mixed Model (LMM) with a more complex random effects structure
# This model accounts for repeated measures within individuals (id) over different days (day)
# and also considers an additional random effect for the variable "conc" (context or condition)

model2 <- lmm_analysis(
  example_data,    # Input dataset containing clinical/longitudinal data
  varLabs,         # List of selected variables to be analyzed in the model
  random_effects = "(1|id/day) + (1|conc)"  # Random effects structure:
                                            # (1|id/day) -> Nested random effect for each day within an individual
                                            # (1|conc) -> Additional random effect for "conc" variable
)
#> boundary (singular) fit: see help('isSingular')
#> boundary (singular) fit: see help('isSingular')
#> boundary (singular) fit: see help('isSingular')

# Generate a network visualization from the second LMM model
qgraph(
  model2,                                # Adjacency matrix or network model derived from LMM
  groups = structure$community_structure, # Assign colors based on predefined symptom groups
  labels = labels,                        # Display variable names as node labels
  legend = TRUE,                           # Include a legend in the plot
  layout = "spring",                       # Use a force-directed "spring" layout for better visualization
  color = c("orange", "lightblue", "#008080"), # Define colors for different variable groups
  legend.cex = 0.3                          # Adjust the legend text size to avoid oversized labels
)

Subtraction is performed between adjacency matrices. Normalization between -1 and 1 is performed inside differentiation() function. This function requires two adjacency matrices as an input, both of them should have the same dimensions and node names.

# Compute the difference between the two Linear Mixed Model (LMM) networks
# This highlights changes in relationships when considering different random effect structures
difference <- differentiation(model, model2)

# Generate a network visualization of the differences between the two models
qgraph(
  difference,                            # Adjacency matrix representing differences between model1 and model2
  groups = structure$community_structure, # Assign colors based on predefined variable groups
  labels = labels,                        # Display variable names as node labels
  legend = TRUE,                           # Include a legend in the plot
  layout = "spring",                       # Use a force-directed "spring" layout for better visualization
  color = c("orange", "lightblue", "#008080"), # Define colors for different variable groups
  legend.cex = 0.3                          # Adjust legend text size to keep it readable
)

Integration of molecular features

MariNET can also be used to integrate omics data (e.g. gene expression or protein abundance) with longitudinal clinical variables. In this case, the aim is to infer relationships between molecular features and clinical variables, so the network only contains edges between both types of nodes.

For network construction, two sets of linear mixed models are created. On the one hand, each clinical variable is modeled including the rest of clinical variables and all molecular features as independent variables. On the other hand, each molecular feature is modeled including all clinical variables as independent variables. The weight of each edge is the mean of the t-values obtained in both directions, and interactions between clinical variables and between molecular features are set to zero.

Loading omics example data

The package includes a simulated dataset, example_omics, with longitudinal clinical measurements (blood pressure, heart rate, body mass index, glucose and cholesterol) and molecular features for 80 participants with up to 4 visits. Data are fully synthetic. Some molecular features were simulated to be associated with clinical variables: GENE1 with systolic blood pressure (positive), GENE2 with cholesterol (negative), GENE3 with glucose (positive) and GENE4 with heart rate (negative), while GENE5 to GENE8 are not associated with any clinical variable. In a real analysis, molecular features should be merged with clinical data by participant and visit, so that each row of the dataframe contains the clinical assessment and the omics measurements of the same sample.

# Load the simulated omics dataset from the package
data(example_omics)

# Display the first few rows
head(example_omics)
#>   participant_id visit_month    sex age Systolic_BP Diastolic_BP Heart_rate
#> 1           P001           0 Female  56         155           98         85
#> 2           P001          12 Female  56         158          103         63
#> 3           P001          24 Female  56         152           95         96
#> 4           P002           0 Female  71         143           99         80
#> 5           P002          12 Female  71         167          109         79
#> 6           P002          24 Female  71         153          107         73
#>    BMI Glucose Cholesterol GENE1 GENE2 GENE3  GENE4 GENE5 GENE6 GENE7 GENE8
#> 1 32.2     121         255 8.280 6.970 9.021  7.689 6.973 6.974 8.876 8.362
#> 2 34.2     119         252 7.766 7.364 6.747  9.605 9.316 7.801 7.786 9.220
#> 3 36.3     120         270 8.905 7.851 7.892  7.251 7.375 7.055 8.815 7.308
#> 4 33.7     129         221 7.908 9.248 7.552  9.004 8.319 8.237 8.841 7.081
#> 5 33.1     148         218 7.912 8.632 9.321  8.582 7.673 8.444 9.108 9.430
#> 6 34.1     134         210 8.268 7.451 9.437 10.314 7.354 9.322 7.176 6.869

# Define the clinical variables to be included as nodes in the network
clinical_vars <- c("Systolic_BP", "Diastolic_BP", "Heart_rate", "BMI", "Glucose", "Cholesterol")

# Define the molecular features to be integrated in the network
molecular_features <- paste0("GENE", 1:8)

Integrated network

The function lmm_integration_analysis() builds the integrated network. It requires input data with the following conditions:

  • clinical_data: Dataframe containing clinical data, metadata and molecular features for participants, including identifier as participant_id. Each molecular feature must be a column of the dataframe.
  • variables_to_scale: Character vector of clinical variable names to be analyzed, must be numerical as they are scaled.
  • molecular_features: Character vector of molecular feature names to be analyzed, must be numerical as they are scaled. Names that are not syntactically valid in R (e.g. gene symbols such as H1-0) are allowed.
  • random_effects: A character string specifying the random effects formula (default: “(1 | participant_id)”).
# Perform integrated Linear Mixed Model (LMM) analysis on the dataset
# Clinical variables are modeled on the rest of clinical variables and molecular features,
# and molecular features are modeled on clinical variables

model_omics <- lmm_integration_analysis(
  example_omics,       # Input dataset containing clinical data and molecular features
  clinical_vars,       # List of clinical variables to be analyzed in the model
  molecular_features,  # List of molecular features to be integrated in the network
  random_effects = "(1|participant_id) + (1|sex)"  # Random intercept for each participant and for sex
)

# Print edge weights between clinical variables (rows) and molecular features (columns)
round(model_omics[clinical_vars, molecular_features], 2)
#>              GENE1  GENE2 GENE3  GENE4 GENE5 GENE6 GENE7 GENE8
#> Systolic_BP  11.10   0.75  0.21  -0.19 -1.37  0.19  0.27  0.18
#> Diastolic_BP  0.17   0.97 -2.06   1.24  2.10  1.09  0.49  1.45
#> Heart_rate   -0.06  -0.67 -1.68 -12.80 -0.19 -1.81  0.97 -0.73
#> BMI          -3.89   4.33 -4.40   1.34 -0.65  0.25 -1.20 -3.06
#> Glucose      -0.43   1.11 13.11   2.62  0.28  0.36  2.04  2.88
#> Cholesterol  -0.54 -15.28 -2.37   0.58 -1.22 -1.00 -0.75  0.55

The resulting adjacency matrix contains clinical variables followed by molecular features, in the same order as provided to the function. Therefore, community structure can be defined following the same order.

# Define the community structure for clinical variables and molecular features
community_structure_omics <- c(
  rep("Cardiovascular", 3),                           # Systolic_BP, Diastolic_BP and Heart_rate
  rep("Metabolic", 3),                                # BMI, Glucose and Cholesterol
  rep("Gene expression", length(molecular_features))  # Molecular features
)

# Generate the integrated network plot using qgraph
qgraph(
  model_omics,                             # Adjacency matrix derived from integrated LMM analysis
  groups = community_structure_omics,      # Assign colors based on community groups
  labels = colnames(model_omics),          # Display variable names as node labels
  legend = TRUE,                           # Include a legend in the plot
  layout = "spring",                       # Use a force-directed "spring" layout for better visualization
  color = c("orange", "pink", "lightblue"), # Define colors for different groups (alphabetical order of groups)
  legend.cex = 0.3                         # Adjust the size of the legend text
)

Additional information

To check your R session information, including loaded packages, R version, and system details.

sessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04.1 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] qgraph_1.10.1    MariNET_2.0.0    BiocStyle_2.41.0
#> 
#> loaded via a namespace (and not attached):
#>  [1] tidyselect_1.2.1    psych_2.6.9         dplyr_1.2.1        
#>  [4] farver_2.1.2        S7_1.0.0            fastmap_1.2.0      
#>  [7] digest_0.6.39       rpart_4.1.27        lifecycle_1.0.5    
#> [10] cluster_2.1.8.3     magrittr_2.0.5      compiler_4.6.2     
#> [13] rlang_1.3.0         Hmisc_5.3-1         sass_0.4.10        
#> [16] tools_4.6.2         igraph_2.3.4        yaml_2.3.12        
#> [19] data.table_1.18.6.1 knitr_1.52          htmlwidgets_1.6.4  
#> [22] mnormt_2.1.2        plyr_1.8.9          RColorBrewer_1.1-3 
#> [25] abind_1.4-8         foreign_0.8-92      withr_3.0.3        
#> [28] sys_3.4.3           nnet_7.3-21         grid_4.6.2         
#> [31] stats4_4.6.2        lavaan_0.7-3        colorspace_2.1-4   
#> [34] ggplot2_4.0.4       scales_1.4.0        gtools_3.9.5       
#> [37] MASS_7.3-66         cli_3.6.6           rmarkdown_2.32     
#> [40] reformulas_0.4.4    generics_0.1.4      rstudioapi_0.19.0  
#> [43] reshape2_1.4.5      minqa_1.2.8         pbapply_1.7-5      
#> [46] cachem_1.1.0        stringr_1.6.0       splines_4.6.2      
#> [49] parallel_4.6.2      BiocManager_1.30.27 base64enc_0.1-6    
#> [52] vctrs_0.7.3         boot_1.3-32         Matrix_1.7-6       
#> [55] jsonlite_2.0.0      glasso_1.11         Formula_1.2-6      
#> [58] htmlTable_2.5.0     jpeg_0.1-11         maketools_1.3.2    
#> [61] jquerylib_0.1.4     glue_1.8.1          nloptr_2.2.1       
#> [64] stringi_1.8.9       gtable_0.3.6        quadprog_1.5-8     
#> [67] lme4_2.1-0          tibble_3.3.1        pillar_1.11.1      
#> [70] htmltools_0.5.9     R6_2.6.1            Rdpack_2.6.6       
#> [73] evaluate_1.0.5      pbivnorm_0.6.0      lattice_0.23-1     
#> [76] rbibutils_2.4.1     png_0.1-9           backports_1.5.1    
#> [79] corpcor_1.6.10      bslib_0.12.0        Rcpp_1.1.2         
#> [82] fdrtool_1.2.18      gridExtra_2.3.1     nlme_3.1-172       
#> [85] checkmate_2.3.4     xfun_0.62           buildtools_1.0.0   
#> [88] pkgconfig_2.0.3

References

Bates, Douglas, Martin Mächler, Ben Bolker, and Steve Walker. 2015. “Fitting Linear Mixed-Effects Models Using lme4.” Journal of Statistical Software 67 (1): 1–48. https://doi.org/10.18637/jss.v067.i01.
Epskamp, Sacha, Giulio Costantini, Jonas Haslbeck, and Adela Isvoranu. 2023. Qgraph: Graph Plotting Methods, Psychometric Data Visualization and Graphical Model Estimation. https://CRAN.R-project.org/package=qgraph.
Fried, Eiko I, Faidra Papanikolaou, and Sacha Epskamp. 2022. “Mental Health and Social Contact During the COVID-19 Pandemic: An Ecological Momentary Assessment Study.” Clinical Psychological Science 10 (2): 340–54.
Velden, Rachel MJ van der, Anne EP Mulders, Marjan Drukker, Mark L Kuijf, and Albert FG Leentjens. 2018. “Network Analysis of Symptoms in a Parkinson Patient Using Experience Sampling Data: An n= 1 Study.” Movement Disorders 33 (12): 1938–44.