Mohit Gupta commited on
Commit
e434ef8
·
verified ·
1 Parent(s): 24cc657

Commiting rest of the files for selecting Random Effects.

Browse files
05-Research_Program-Affective_Provo/01-Fixation_Duration_Research/01-LME_Model_Structure/01-Scripts/Step-2-Testing_Best_CorrelatedSlopes_for_Selected_Random_Intercept.R ADDED
@@ -0,0 +1,3506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # COPYRIGHT, LICENSING, AND SCHOLARLY CITATION
3
+ # ============================================================
4
+ # Copyright (c) 2026 Mohit Gupta
5
+ # License: MIT
6
+ # SPDX-License-Identifier: MIT
7
+ #
8
+ # This script contains original computational software
9
+ # developed by Mohit Gupta for the AffLex-Provo
10
+ # Research Program.
11
+ #
12
+ # Citation:
13
+ # Researchers using this software in published research
14
+ # are strongly requested to cite the AffLex-Provo repository:
15
+ # https://huggingface.co/datasets/mohitg2/AffLex-Provo
16
+ #
17
+ # Third-party datasets and externally sourced materials
18
+ # remain subject to their respective original licenses.
19
+ #
20
+ # See the applicable repository LICENSE file for the
21
+ # complete MIT License terms.
22
+ # ============================================================
23
+
24
+ # ============================================================
25
+ # CELL 1.1 — PACKAGE INSTALLATION AND INITIALIZATION (Affective Provo)
26
+ # ============================================================
27
+ #
28
+ #
29
+ # REQUIRED R VERSION: R version 4.5.2 (2025-10-31)
30
+ #
31
+ #
32
+ # Purpose:
33
+ # Ensure that all R packages required by the Step 2 analysis
34
+ # pipeline are installed and loaded.
35
+ #
36
+ # Required packages:
37
+ # readr → CSV import
38
+ # readxl → Excel import
39
+ # openxlsx → Excel export and formatting
40
+ # dplyr → data manipulation
41
+ # tidyr → missing-data handling
42
+ # stringr → string utilities
43
+ # purrr → functional/list operations
44
+ # lme4 → linear mixed-effects models
45
+ # optimx → additional optimizers used by lme4::allFit()
46
+ # dfoptim → additional optimizers used by lme4::allFit()
47
+ # future → parallel-processing infrastructure
48
+ # future.apply → future-based apply functions
49
+ # progressr → progress-handling utilities
50
+ # here → portable project-root paths
51
+ #
52
+ # Procedure:
53
+ # 1. Define the complete set of required packages.
54
+ # 2. Identify packages that are not currently installed.
55
+ # 3. Install only the missing packages from CRAN.
56
+ # 4. Load all required packages.
57
+ #
58
+ # Notes:
59
+ # - Existing package installations are left unchanged.
60
+ # - Packages are installed only when absent.
61
+ # - suppressPackageStartupMessages() keeps notebook output clean.
62
+ # - Package versions are recorded later by sessionInfo() in
63
+ # the runtime log.
64
+ # ============================================================
65
+
66
+
67
+ # ------------------------------------------------------------
68
+ # 1. Define Required Packages
69
+ # ------------------------------------------------------------
70
+
71
+ REQUIRED_PACKAGES <- c(
72
+ "readr",
73
+ "readxl",
74
+ "openxlsx",
75
+ "dplyr",
76
+ "tidyr",
77
+ "stringr",
78
+ "purrr",
79
+ "lme4",
80
+ "optimx",
81
+ "dfoptim",
82
+ "future",
83
+ "future.apply",
84
+ "progressr",
85
+ "here"
86
+ )
87
+
88
+
89
+ # ------------------------------------------------------------
90
+ # 2. Identify Missing Packages
91
+ # ------------------------------------------------------------
92
+
93
+ MISSING_PACKAGES <- REQUIRED_PACKAGES[
94
+ !vapply(
95
+ REQUIRED_PACKAGES,
96
+ requireNamespace,
97
+ quietly = TRUE,
98
+ FUN.VALUE = logical(1)
99
+ )
100
+ ]
101
+
102
+
103
+ # ------------------------------------------------------------
104
+ # 3. Install Missing Packages
105
+ # ------------------------------------------------------------
106
+
107
+ if (length(MISSING_PACKAGES) > 0) {
108
+
109
+ message(
110
+ "Installing missing package(s): ",
111
+ paste(MISSING_PACKAGES, collapse = ", ")
112
+ )
113
+
114
+ install.packages(
115
+ MISSING_PACKAGES,
116
+ repos = "https://cloud.r-project.org",
117
+ dependencies = TRUE
118
+ )
119
+
120
+ } else {
121
+
122
+ message("All required packages are already installed.")
123
+ }
124
+
125
+
126
+ # ------------------------------------------------------------
127
+ # 4. Load Required Packages
128
+ # ------------------------------------------------------------
129
+
130
+ suppressPackageStartupMessages({
131
+
132
+ library(readr)
133
+ library(readxl)
134
+ library(openxlsx)
135
+
136
+ library(dplyr)
137
+ library(tidyr)
138
+ library(stringr)
139
+ library(purrr)
140
+
141
+ library(lme4)
142
+ library(optimx)
143
+ library(dfoptim)
144
+
145
+ library(future)
146
+ library(future.apply)
147
+
148
+ library(progressr)
149
+
150
+ library(here)
151
+ })
152
+
153
+
154
+ # ------------------------------------------------------------
155
+ # 5. Confirm Package Initialization
156
+ # ------------------------------------------------------------
157
+
158
+ message(
159
+ "Package initialization complete: ",
160
+ length(REQUIRED_PACKAGES),
161
+ " required packages available."
162
+ )
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+ # ============================================================
174
+ # CELL 1.2 — HARD THREAD CAPS
175
+ # ============================================================
176
+ # Purpose:
177
+ # Restrict low-level numerical libraries to a single thread.
178
+ #
179
+ # Rationale:
180
+ # Mixed-effects models and allFit() may perform substantial
181
+ # numerical computation. If process-level parallelism is used
182
+ # later, unrestricted BLAS/OpenMP threading inside individual
183
+ # workers can cause:
184
+ #
185
+ # - CPU oversubscription
186
+ # - memory contention
187
+ # - reduced performance
188
+ # - computational instability
189
+ #
190
+ # Strategy:
191
+ # Restrict low-level numerical libraries to one thread.
192
+ # Any intentional parallelism should occur at the R-process
193
+ # level rather than within each numerical operation.
194
+ #
195
+ # Controlled libraries:
196
+ # - VECLIB / macOS Accelerate
197
+ # - OpenMP
198
+ # - OpenBLAS
199
+ # - Intel MKL
200
+ # - NumExpr
201
+ #
202
+ # Notes:
203
+ # - This does NOT change the statistical model.
204
+ # - This does NOT change the analysis sample.
205
+ # - This should be configured before heavy model fitting.
206
+ # ============================================================
207
+
208
+ Sys.setenv(
209
+ VECLIB_MAXIMUM_THREADS = "1",
210
+ OMP_NUM_THREADS = "1",
211
+ OPENBLAS_NUM_THREADS = "1",
212
+ MKL_NUM_THREADS = "1",
213
+ NUMEXPR_NUM_THREADS = "1"
214
+ )
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+ # ============================================================
226
+ # CELL 1.3 — CORRELATED RANDOM-SLOPE CONFIGURATION
227
+ # ============================================================
228
+ # Purpose:
229
+ # Define the random-effects configuration used during Step 2,
230
+ # which evaluates candidate participant-level random slopes.
231
+ #
232
+ # Step 1 established the random-intercept structure.
233
+ #
234
+ # Step 2 now evaluates whether lexical and affective
235
+ # fixed-effect predictors should additionally vary by
236
+ # participant as random slopes.
237
+ #
238
+ # ------------------------------------------------------------
239
+ # Additional Random Intercept
240
+ # ------------------------------------------------------------
241
+ # ADDITIONAL_INTERCEPT:
242
+ # Specifies the crossed random-intercept grouping factor
243
+ # retained alongside Participant_ID.
244
+ #
245
+ # USE_ADDITIONAL_INTERCEPT:
246
+ # TRUE → include the additional crossed random intercept
247
+ # FALSE → use participant grouping only
248
+ #
249
+ # With the current configuration:
250
+ #
251
+ # (1 + candidate slopes | Participant_ID)
252
+ # + (1 | Word_Unique_ID)
253
+ # ------------------------------------------------------------
254
+
255
+ ADDITIONAL_INTERCEPT <- "Word_Unique_ID"
256
+ USE_ADDITIONAL_INTERCEPT <- TRUE
257
+
258
+
259
+ # ------------------------------------------------------------
260
+ # Random-Slope Correlation Structure
261
+ # ------------------------------------------------------------
262
+ # USE_UNCORRELATED_SLOPES:
263
+ #
264
+ # FALSE:
265
+ # (1 + slopes | Participant_ID)
266
+ #
267
+ # Participant intercepts and random slopes are allowed
268
+ # to correlate.
269
+ #
270
+ # TRUE:
271
+ # (1 + slopes || Participant_ID)
272
+ #
273
+ # Participant intercepts and random slopes are modeled
274
+ # without correlation parameters.
275
+ #
276
+ # This Step 2 script evaluates CORRELATED random slopes, so the
277
+ # setting should remain FALSE.
278
+ # ------------------------------------------------------------
279
+
280
+ USE_UNCORRELATED_SLOPES <- FALSE
281
+
282
+
283
+ # ------------------------------------------------------------
284
+ # Candidate-Slope Complexity Limit
285
+ # ------------------------------------------------------------
286
+ # MAX_SLOPES_PER_CANDIDATE controls the maximum number of
287
+ # participant-level random slopes allowed in a candidate model.
288
+ #
289
+ # Inf:
290
+ # Do not impose an artificial maximum.
291
+ #
292
+ # A smaller value may be used in a separate sensitivity or
293
+ # stability analysis if highly complex structures prove
294
+ # computationally unstable.
295
+ # ------------------------------------------------------------
296
+
297
+ MAX_SLOPES_PER_CANDIDATE <- Inf
298
+
299
+
300
+ # ------------------------------------------------------------
301
+ # Console Confirmation
302
+ # ------------------------------------------------------------
303
+
304
+ if (USE_ADDITIONAL_INTERCEPT) {
305
+ message("Random-intercept structure: Participant_ID + ", ADDITIONAL_INTERCEPT)
306
+ } else {
307
+ message("Random-intercept structure: Participant_ID only")
308
+ }
309
+
310
+ message(
311
+ "Participant random slopes: ",
312
+ if (USE_UNCORRELATED_SLOPES) "UNCORRELATED" else "CORRELATED"
313
+ )
314
+
315
+ message("Maximum slopes per candidate: ", MAX_SLOPES_PER_CANDIDATE)
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+ # ============================================================
327
+ # CELL 1.4 — ROOT-ANCHORED PROJECT PATHS
328
+ # ============================================================
329
+ # Purpose:
330
+ # Define portable input and output paths using the 'here'
331
+ # package.
332
+ #
333
+ # Input:
334
+ # 02-Data/
335
+ # 03-Analysis_Ready/
336
+ # 03_Affective_Provo.csv
337
+ #
338
+ # Dataset:
339
+ # Affective Provo guarantees complete mandatory:
340
+ #
341
+ # Lexical predictors:
342
+ # - Word_Length
343
+ # - Response_Proportion
344
+ # - Lg10WF
345
+ #
346
+ # Affective predictors:
347
+ # - V.Mean.Y
348
+ # - A.Mean.Y
349
+ # - D.Mean.Y
350
+ #
351
+ # Important:
352
+ # Eye-tracking outcomes have NOT been used to determine
353
+ # inclusion in the exported Affective Provo dataset.
354
+ #
355
+ # DV-specific duration filtering therefore occurs later in
356
+ # this Step 2 analysis pipeline, as it did in Step 1.
357
+ #
358
+ # Output:
359
+ # 05-Research_Program-Affective_Provo/
360
+ # 01-LME_Model_Structure/
361
+ # 02-Results/
362
+ #
363
+ # Step 1 and Step 2 intentionally use the same results
364
+ # directory. Step-specific filenames distinguish their outputs.
365
+ # ============================================================
366
+
367
+ PROJECT_ROOT <- here()
368
+
369
+ RAW_DATA_PATH <- here(
370
+ "02-Data",
371
+ "03-Analysis_Ready",
372
+ "03_Affective_Provo.csv"
373
+ )
374
+
375
+ OUTPUT_DATA_DIR <- here(
376
+ "05-Research_Program-Affective_Provo",
377
+ "01-Fixation_Duration_Research",
378
+ "01-LME_Model_Structure",
379
+ "02-Results"
380
+ )
381
+
382
+ dir.create(
383
+ OUTPUT_DATA_DIR,
384
+ recursive = TRUE,
385
+ showWarnings = FALSE
386
+ )
387
+
388
+ stopifnot(
389
+ file.exists(RAW_DATA_PATH)
390
+ )
391
+
392
+ message("PROJECT_ROOT: ", PROJECT_ROOT)
393
+ message("RAW_DATA_PATH: ", RAW_DATA_PATH)
394
+ message("OUTPUT_DATA_DIR: ", OUTPUT_DATA_DIR)
395
+
396
+
397
+ # ============================================================
398
+ # 1.5 RUNTIME LOG — START
399
+ # ============================================================
400
+
401
+ LOG_PATH <- file.path(
402
+ OUTPUT_DATA_DIR,
403
+ "Step-2_Runtime_Log_Affective_Provo_Correlated_Slopes.txt"
404
+ )
405
+
406
+ log_con <- file(
407
+ LOG_PATH,
408
+ open = "wt"
409
+ )
410
+
411
+ sink(log_con, split = TRUE)
412
+ sink(log_con, type = "message")
413
+
414
+ cat(
415
+ paste0(
416
+ "\n",
417
+ strrep("=", 80), "\n",
418
+ "STEP 2 — CORRELATED RANDOM-SLOPE ANALYSIS\n",
419
+ "Dataset: Affective Provo\n",
420
+ "Started: ", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "\n",
421
+ "R version: ", R.version.string, "\n",
422
+ strrep("=", 80), "\n\n"
423
+ )
424
+ )
425
+
426
+
427
+
428
+
429
+
430
+
431
+ # ============================================================
432
+ # CELL 2 — SHARED HELPER FUNCTIONS
433
+ # ============================================================
434
+ # Purpose:
435
+ # Define reusable utility functions used throughout the
436
+ # correlated random-slope model-selection pipeline.
437
+ #
438
+ # Includes:
439
+ # - Random-slope candidate generation
440
+ # - Runtime formatting
441
+ # - Excel sheet-name sanitization
442
+ # - Row-count auditing for fair AIC/BIC comparison
443
+ # - Structured Excel export with safe sheet replacement
444
+ #
445
+ # Design principles:
446
+ # - Functions are reusable across DVs.
447
+ # - Functions are shared by Paper 1 (Affective Provo) and
448
+ # Paper 2 (Lexical Provo).
449
+ # - No model fitting occurs in this cell.
450
+ # - No analysis-specific row filtering occurs in this cell.
451
+ # - File-writing side effects occur only in the explicitly
452
+ # defined Excel-export function.
453
+ # ============================================================
454
+
455
+
456
+ # ------------------------------------------------------------
457
+ # 2.1 Random-Slope Candidate Generator
458
+ # ------------------------------------------------------------
459
+ # Purpose:
460
+ # Generate all candidate participant-level random-slope
461
+ # structures from a supplied set of slope variables.
462
+ #
463
+ # Behavior:
464
+ # - Always includes the random-intercept-only candidate:
465
+ #
466
+ # "1"
467
+ #
468
+ # - Generates every combination of the supplied slopes.
469
+ #
470
+ # - max_slopes can optionally restrict the maximum number
471
+ # of slopes included in any candidate structure.
472
+ #
473
+ # Example for the Len-Freq-Pred baseline:
474
+ #
475
+ # slope_vars = c(
476
+ # "Word_Length",
477
+ # "Response_Proportion",
478
+ # "Lg10WF"
479
+ # )
480
+ #
481
+ # Candidate structures include:
482
+ #
483
+ # "1"
484
+ # "1 + Word_Length"
485
+ # "1 + Response_Proportion"
486
+ # "1 + Lg10WF"
487
+ # "1 + Word_Length + Response_Proportion"
488
+ # ...
489
+ # "1 + Word_Length + Response_Proportion + Lg10WF"
490
+ #
491
+ # The generated strings are later inserted into the
492
+ # participant-level random-effects term.
493
+ #
494
+ # For correlated slopes:
495
+ #
496
+ # (1 + slopes | Participant_ID)
497
+ #
498
+ # For uncorrelated slopes:
499
+ #
500
+ # (1 + slopes || Participant_ID)
501
+ # ------------------------------------------------------------
502
+
503
+ generate_re_candidates <- function(slope_vars, max_slopes = Inf) {
504
+ candidates <- c("1")
505
+
506
+ if (length(slope_vars) == 0) return(candidates)
507
+
508
+ for (r in seq_along(slope_vars)) {
509
+ if (is.finite(max_slopes) && r > max_slopes) next
510
+
511
+ combos <- combn(slope_vars, r, simplify = FALSE)
512
+
513
+ candidates <- c(
514
+ candidates,
515
+ vapply(
516
+ combos,
517
+ function(x) paste("1 +", paste(x, collapse = " + ")),
518
+ character(1)
519
+ )
520
+ )
521
+ }
522
+
523
+ unique(candidates)
524
+ }
525
+
526
+
527
+ # ------------------------------------------------------------
528
+ # 2.2 Runtime Formatter
529
+ # ------------------------------------------------------------
530
+ # Purpose:
531
+ # Convert elapsed execution time in seconds into a compact
532
+ # human-readable representation.
533
+ #
534
+ # Output examples:
535
+ # 12.5 seconds → "12.5s"
536
+ # 492 seconds → "8.2m"
537
+ # 4860 seconds → "1.35h"
538
+ # ------------------------------------------------------------
539
+
540
+ fmt_secs <- function(s) {
541
+ if (is.null(s) || !is.finite(s)) return("NA")
542
+
543
+ s <- as.numeric(s)
544
+
545
+ if (s < 60) return(sprintf("%.1fs", s))
546
+ if (s < 3600) return(sprintf("%.1fm", s / 60))
547
+
548
+ sprintf("%.2fh", s / 3600)
549
+ }
550
+
551
+
552
+ # ------------------------------------------------------------
553
+ # 2.3 Excel Sheet-Name Sanitizer
554
+ # ------------------------------------------------------------
555
+ # Purpose:
556
+ # Ensure dynamically generated worksheet names comply with
557
+ # Microsoft Excel naming restrictions.
558
+ #
559
+ # Excel restrictions handled:
560
+ # - Maximum worksheet-name length = 31 characters
561
+ # - Prohibited characters:
562
+ #
563
+ # \ / * [ ] : ?
564
+ #
565
+ # This prevents worksheet-creation errors during repeated
566
+ # automated exports.
567
+ # ------------------------------------------------------------
568
+
569
+ safe_sheet_name <- function(name) {
570
+ name <- str_replace_all(name, "[\\\\/*\\[\\]:?]", "_")
571
+ str_sub(name, 1, 31)
572
+ }
573
+
574
+
575
+ # ------------------------------------------------------------
576
+ # 2.4 Row-Count Audit for Fair Model Comparison
577
+ # ------------------------------------------------------------
578
+ # Purpose:
579
+ # Audit the analysis sample used for AIC/BIC comparison.
580
+ #
581
+ # Why this matters:
582
+ # Candidate random-slope models for the SAME DV must be
583
+ # compared on exactly the same observations. Otherwise,
584
+ # differences in AIC/BIC could reflect differences in sample
585
+ # composition rather than differences in model structure.
586
+ #
587
+ # Reports:
588
+ # original_rows
589
+ # → rows supplied to the audit function
590
+ #
591
+ # dv_nonmissing_rows
592
+ # → rows with a non-missing value for the current DV
593
+ #
594
+ # complete_case_rows_used_for_AIC_BIC
595
+ # → rows complete across the current DV and all variables
596
+ # specified in required_cols
597
+ #
598
+ # rows_dropped_for_complete_case
599
+ # → rows removed because at least one required value
600
+ # was missing
601
+ #
602
+ # pct_dropped
603
+ # → percentage of supplied rows removed by complete-case
604
+ # filtering
605
+ #
606
+ # Important:
607
+ # This helper audits MISSINGNESS only.
608
+ #
609
+ # It does NOT automatically impose DV > 0.
610
+ #
611
+ # For duration-based analyses, the positive-duration
612
+ # restriction must be applied during the analysis-data
613
+ # preparation stage before candidate models are compared.
614
+ #
615
+ # Safety:
616
+ # Required columns are validated explicitly. Missing required
617
+ # variables cause the pipeline to stop rather than being
618
+ # silently omitted from the audit.
619
+ # ------------------------------------------------------------
620
+
621
+ dv_rowcount_summary <- function(df, dv, required_cols, label = "") {
622
+
623
+ cols_needed <- unique(c(dv, required_cols))
624
+
625
+ missing_required <- setdiff(cols_needed, names(df))
626
+
627
+ if (length(missing_required) > 0) {
628
+ stop(
629
+ "Row-count audit cannot proceed. Missing required variable(s): ",
630
+ paste(missing_required, collapse = ", ")
631
+ )
632
+ }
633
+
634
+ original_n <- nrow(df)
635
+ dv_nonmissing <- sum(!is.na(df[[dv]]))
636
+
637
+ complete_n <- df %>%
638
+ select(all_of(cols_needed)) %>%
639
+ drop_na() %>%
640
+ nrow()
641
+
642
+ dropped <- original_n - complete_n
643
+
644
+ tibble(
645
+ label = ifelse(nchar(label) > 0, label, dv),
646
+ dv = dv,
647
+ original_rows = original_n,
648
+ dv_nonmissing_rows = dv_nonmissing,
649
+ complete_case_rows_used_for_AIC_BIC = complete_n,
650
+ rows_dropped_for_complete_case = dropped,
651
+ pct_dropped = if (original_n > 0) dropped / original_n * 100 else NA_real_,
652
+ required_cols_used = paste(required_cols, collapse = ", ")
653
+ )
654
+ }
655
+
656
+
657
+ # ------------------------------------------------------------
658
+ # 2.5 Structured Excel Export
659
+ # ------------------------------------------------------------
660
+ # Purpose:
661
+ # Save correlated random-slope model-selection outputs to a
662
+ # structured multi-sheet Excel workbook.
663
+ #
664
+ # Sheets created for each DV:
665
+ #
666
+ # <DV>_ranking
667
+ # → candidate random-slope model ranking
668
+ #
669
+ # <DV>_audit
670
+ # → model-fitting / convergence audit information
671
+ #
672
+ # <DV>_rowcounts
673
+ # → sample-size and complete-case diagnostics
674
+ #
675
+ # Repeated-execution behavior:
676
+ # - Creates the workbook if it does not already exist.
677
+ # - Loads the existing workbook when rerunning the analysis.
678
+ # - Removes only the sheets corresponding to the current DV.
679
+ # - Recreates those sheets with the updated results.
680
+ # - Preserves sheets belonging to other DVs.
681
+ #
682
+ # Safety:
683
+ # - Normalizes the output path.
684
+ # - Creates the parent directory when necessary.
685
+ # - Sanitizes dynamically generated worksheet names.
686
+ # - Saves with overwrite = TRUE after the workbook has been
687
+ # updated in memory.
688
+ # ------------------------------------------------------------
689
+
690
+ save_re_outputs_to_excel <- function(
691
+ excel_path,
692
+ dv,
693
+ df_results,
694
+ df_audit,
695
+ rowcount_summary
696
+ ) {
697
+
698
+ excel_path <- normalizePath(
699
+ excel_path,
700
+ winslash = "/",
701
+ mustWork = FALSE
702
+ )
703
+
704
+ dir.create(
705
+ dirname(excel_path),
706
+ recursive = TRUE,
707
+ showWarnings = FALSE
708
+ )
709
+
710
+ rank_sheet <- safe_sheet_name(paste0(dv, "_ranking"))
711
+ audit_sheet <- safe_sheet_name(paste0(dv, "_audit"))
712
+ rows_sheet <- safe_sheet_name(paste0(dv, "_rowcounts"))
713
+
714
+ if (file.exists(excel_path)) {
715
+
716
+ wb <- loadWorkbook(excel_path)
717
+
718
+ if (rank_sheet %in% names(wb)) removeWorksheet(wb, rank_sheet)
719
+ if (audit_sheet %in% names(wb)) removeWorksheet(wb, audit_sheet)
720
+ if (rows_sheet %in% names(wb)) removeWorksheet(wb, rows_sheet)
721
+
722
+ } else {
723
+
724
+ wb <- createWorkbook()
725
+ }
726
+
727
+ addWorksheet(wb, rank_sheet)
728
+ writeData(wb, rank_sheet, df_results)
729
+
730
+ addWorksheet(wb, audit_sheet)
731
+ writeData(wb, audit_sheet, df_audit)
732
+
733
+ addWorksheet(wb, rows_sheet)
734
+ writeData(wb, rows_sheet, rowcount_summary)
735
+
736
+ saveWorkbook(
737
+ wb,
738
+ excel_path,
739
+ overwrite = TRUE
740
+ )
741
+
742
+ message(
743
+ "Saved correlated random-slope results: ",
744
+ excel_path
745
+ )
746
+ }
747
+
748
+
749
+
750
+
751
+
752
+
753
+
754
+
755
+
756
+ # ============================================================
757
+ # CELL 3 — LOAD AND VALIDATE AFFECTIVE PROVO
758
+ # ============================================================
759
+ # Purpose:
760
+ # Load the analysis-ready Affective Provo dataset and prepare
761
+ # variable names for the correlated random-slope pipeline.
762
+ #
763
+ # Input:
764
+ # 03_Affective_Provo.csv
765
+ #
766
+ # Dataset guarantees:
767
+ # Every observation has complete mandatory:
768
+ #
769
+ # Lexical predictors:
770
+ # - Word_Length
771
+ # - Response_Proportion
772
+ # - Lg10WF
773
+ #
774
+ # Affective predictors:
775
+ # - V.Mean.Y
776
+ # - A.Mean.Y
777
+ # - D.Mean.Y
778
+ #
779
+ # Procedure:
780
+ # 1. Load the Affective Provo dataset.
781
+ # 2. Preserve the loaded dataset in df_main.
782
+ # 3. Create df as the working modeling copy.
783
+ # 4. Rename VAD variables for model readability.
784
+ # 5. Validate mandatory predictors.
785
+ #
786
+ # IMPORTANT:
787
+ # No eye-tracking filtering occurs here.
788
+ #
789
+ # No DV > 0 filtering occurs here.
790
+ #
791
+ # No predictor standardization occurs here.
792
+ #
793
+ # Predictors will be standardized AFTER the DV-specific
794
+ # analysis sample has been constructed. This ensures that
795
+ # scaling is based on the observations actually entering
796
+ # each duration-DV model comparison.
797
+ #
798
+ # Consequently, FFD, GD, GPT, and TDT may be standardized
799
+ # using slightly different means/SDs if their eligible
800
+ # analysis samples differ.
801
+ # ============================================================
802
+
803
+
804
+ # ------------------------------------------------------------
805
+ # 3.1 Load Affective Provo
806
+ # ------------------------------------------------------------
807
+
808
+ df_main <- read_csv(
809
+ RAW_DATA_PATH,
810
+ show_col_types = FALSE
811
+ )
812
+
813
+ message(
814
+ "Affective Provo rows loaded: ",
815
+ format(nrow(df_main), big.mark = ",")
816
+ )
817
+
818
+
819
+ # ------------------------------------------------------------
820
+ # 3.2 Create Modeling Copy
821
+ # ------------------------------------------------------------
822
+ # df_main preserves the loaded analysis-ready dataset.
823
+ # Subsequent preparation occurs on df.
824
+ # ------------------------------------------------------------
825
+
826
+ df <- df_main
827
+
828
+
829
+ # ------------------------------------------------------------
830
+ # 3.3 Rename Affective Predictors
831
+ # ------------------------------------------------------------
832
+ # Rename the original VAD columns to concise names used in
833
+ # subsequent model formulas:
834
+ #
835
+ # V.Mean.Y → Valence
836
+ # A.Mean.Y → Arousal
837
+ # D.Mean.Y → Dominance
838
+ # ------------------------------------------------------------
839
+
840
+ rename_map <- c(
841
+ "V.Mean.Y" = "Valence",
842
+ "A.Mean.Y" = "Arousal",
843
+ "D.Mean.Y" = "Dominance",
844
+ "Word_Length" = "Length",
845
+ "Response_Proportion" = "Predictability",
846
+ "Lg10WF" = "Frequency"
847
+ )
848
+
849
+ for (k in names(rename_map)) {
850
+ if (k %in% names(df)) {
851
+ names(df)[names(df) == k] <- rename_map[[k]]
852
+ }
853
+ }
854
+
855
+
856
+ # ------------------------------------------------------------
857
+ # 3.4 Validate Mandatory LFP + VAD Predictors
858
+ # ------------------------------------------------------------
859
+ # Affective Provo should contain complete LFP + VAD predictors
860
+ # by construction. Missing columns or missing values therefore
861
+ # indicate an incorrect/incomplete input dataset and should
862
+ # stop the analysis rather than being silently filtered.
863
+ # ------------------------------------------------------------
864
+
865
+ REQUIRED_PREDICTORS <- c(
866
+ "Length",
867
+ "Predictability",
868
+ "Frequency",
869
+ "Valence",
870
+ "Arousal",
871
+ "Dominance"
872
+ )
873
+
874
+ missing_columns <- setdiff(
875
+ REQUIRED_PREDICTORS,
876
+ names(df)
877
+ )
878
+
879
+ if (length(missing_columns) > 0) {
880
+ stop(
881
+ "Missing mandatory Affective Provo predictor(s): ",
882
+ paste(missing_columns, collapse = ", ")
883
+ )
884
+ }
885
+
886
+ if (anyNA(df[REQUIRED_PREDICTORS])) {
887
+ stop(
888
+ "Affective Provo contains missing values in one or more ",
889
+ "mandatory LFP + VAD predictors."
890
+ )
891
+ }
892
+
893
+
894
+ # ------------------------------------------------------------
895
+ # 3.5 Confirm Dataset Readiness
896
+ # ------------------------------------------------------------
897
+
898
+ message("Mandatory LFP + VAD predictors: complete.")
899
+ message("Predictors remain UNSCALED at this stage.")
900
+ message("DV-specific filtering and standardization will occur later.")
901
+
902
+
903
+
904
+
905
+
906
+
907
+
908
+
909
+
910
+ # ============================================================
911
+ # CELL 4 — DVs, CORRELATED-SLOPE CANDIDATES, AND RESOURCE PLAN
912
+ # ============================================================
913
+ # Purpose:
914
+ # Define the duration-based dependent variables, generate all
915
+ # candidate participant-level correlated random-slope
916
+ # structures, and determine a conservative computational
917
+ # execution plan.
918
+ #
919
+ # Paper 1 candidate slopes:
920
+ #
921
+ # Lexical predictors:
922
+ # - Length
923
+ # - Predictability
924
+ # - Frequency
925
+ #
926
+ # Affective predictors:
927
+ # - Valence
928
+ # - Arousal
929
+ # - Dominance
930
+ #
931
+ # Random-slope framework:
932
+ #
933
+ # Candidate slopes are added at the Participant_ID level:
934
+ #
935
+ # (1 + candidate_slopes | Participant_ID)
936
+ #
937
+ # Because USE_UNCORRELATED_SLOPES = FALSE in Cell 1.3,
938
+ # participant intercepts and random slopes are allowed to
939
+ # correlate.
940
+ #
941
+ # The additional crossed random intercept configured in
942
+ # Cell 1.3 is retained separately:
943
+ #
944
+ # + (1 | Word_Unique_ID)
945
+ #
946
+ # Candidate generation:
947
+ # With 6 possible slopes and no complexity cap:
948
+ #
949
+ # 2^6 = 64 candidate structures
950
+ #
951
+ # including the participant random-intercept-only candidate.
952
+ #
953
+ # Computational planning:
954
+ # - Detect available logical CPUs.
955
+ # - Estimate available system RAM.
956
+ # - Reserve CPU and RAM headroom for system stability.
957
+ # - Limit process-level workers according to:
958
+ # TASKS_PER_DV
959
+ # CPU_BUDGET
960
+ # RAM_BUDGET_WORKERS
961
+ # - Restrict low-level numerical threading to prevent
962
+ # oversubscription.
963
+ #
964
+ # Important:
965
+ # - This cell defines candidate structures only.
966
+ # - No model fitting occurs here.
967
+ # - No DV-specific filtering occurs here.
968
+ # - No predictor standardization occurs here.
969
+ # - Standardization will occur after construction of each
970
+ # DV-specific analysis sample.
971
+ # ============================================================
972
+
973
+
974
+ # ------------------------------------------------------------
975
+ # 4.1 Define Duration-Based Dependent Variables
976
+ # ------------------------------------------------------------
977
+
978
+ DVS <- c(
979
+ "IA_FIRST_FIXATION_DURATION", # Stage 1: FFD
980
+ "IA_FIRST_RUN_DWELL_TIME", # Stage 2: GD
981
+ "IA_REGRESSION_PATH_DURATION", # Stage 3: GPT
982
+ "IA_DWELL_TIME" # Stage 4: TDT
983
+ )
984
+
985
+
986
+ # ------------------------------------------------------------
987
+ # 4.2 Define Candidate Participant-Level Random Slopes
988
+ # ------------------------------------------------------------
989
+ # Paper 1 evaluates whether lexical and/or affective predictor
990
+ # effects vary across participants.
991
+ # ------------------------------------------------------------
992
+
993
+ SLOPES <- c(
994
+ "Length",
995
+ "Predictability",
996
+ "Frequency",
997
+ "Valence",
998
+ "Arousal",
999
+ "Dominance"
1000
+ )
1001
+
1002
+
1003
+ # Validate candidate-slope variables before generating models
1004
+ missing_slopes <- setdiff(SLOPES, names(df))
1005
+
1006
+ if (length(missing_slopes) > 0) {
1007
+ stop(
1008
+ "Missing candidate random-slope variable(s): ",
1009
+ paste(missing_slopes, collapse = ", ")
1010
+ )
1011
+ }
1012
+
1013
+
1014
+
1015
+
1016
+ # ------------------------------------------------------------
1017
+ # 4.3 Generate Candidate Random-Slope Structures
1018
+ # ------------------------------------------------------------
1019
+
1020
+ CANDIDATES <- generate_re_candidates(
1021
+ SLOPES,
1022
+ max_slopes = MAX_SLOPES_PER_CANDIDATE
1023
+ )
1024
+
1025
+ NUM_MODELS <- length(CANDIDATES)
1026
+ NUM_DVS <- length(DVS)
1027
+
1028
+ # Full pipeline = all four DVs combined
1029
+ TOTAL_PIPELINE_MODELS <- NUM_DVS * NUM_MODELS
1030
+
1031
+ # Each DV is executed manually, one at a time
1032
+ TASKS_PER_DV <- NUM_MODELS
1033
+
1034
+ message("Candidate slope variables : ", length(SLOPES))
1035
+ message("Candidate structures / DV : ", NUM_MODELS)
1036
+ message("Duration DVs : ", NUM_DVS)
1037
+ message("Full pipeline models : ", TOTAL_PIPELINE_MODELS)
1038
+ message("Tasks per manual DV run : ", TASKS_PER_DV)
1039
+
1040
+
1041
+ # ------------------------------------------------------------
1042
+ # 4.4 System RAM Detection Helper
1043
+ # ------------------------------------------------------------
1044
+ # Detect total physical RAM in GB.
1045
+ #
1046
+ # Supported:
1047
+ # - macOS
1048
+ # - Linux
1049
+ #
1050
+ # Returns NA if RAM detection fails, in which case a conservative
1051
+ # fallback worker limit is used below.
1052
+ # ------------------------------------------------------------
1053
+
1054
+ get_total_ram_gb <- function() {
1055
+ out <- NA_real_
1056
+ os <- Sys.info()[["sysname"]]
1057
+
1058
+ suppressWarnings({
1059
+ if (os == "Darwin") {
1060
+ mem <- as.numeric(system("sysctl -n hw.memsize", intern = TRUE))
1061
+ if (is.finite(mem)) out <- mem / (1024^3)
1062
+
1063
+ } else if (os == "Linux") {
1064
+ memline <- system("grep MemTotal /proc/meminfo", intern = TRUE)
1065
+ memkb <- as.numeric(str_extract(memline, "\\d+"))
1066
+ if (is.finite(memkb)) out <- memkb / (1024^2)
1067
+ }
1068
+ })
1069
+
1070
+ if (length(out) == 0) out <- NA_real_
1071
+
1072
+ out
1073
+ }
1074
+
1075
+
1076
+ # ------------------------------------------------------------
1077
+ # 4.5 Initialize Hardware and Resource Assumptions
1078
+ # ------------------------------------------------------------
1079
+
1080
+ TOTAL_RAM_GB <- get_total_ram_gb()
1081
+
1082
+ # Approximate memory allowance per concurrent lmer task.
1083
+ # This is a planning heuristic rather than a measured guarantee.
1084
+ EST_RAM_PER_WORKER_GB <- 2.5
1085
+
1086
+ # Reserve RAM for the operating system and other processes.
1087
+ RAM_HEADROOM_GB <- NA_real_
1088
+
1089
+ # Conservative fallback if RAM detection fails.
1090
+ RAM_BUDGET_WORKERS <- 1
1091
+
1092
+
1093
+ # Detect logical CPUs
1094
+ TOTAL_CPUS <- parallel::detectCores(logical = TRUE)
1095
+
1096
+ if (is.na(TOTAL_CPUS)) TOTAL_CPUS <- 1
1097
+
1098
+
1099
+ # Reserve CPU capacity for the operating system.
1100
+ CPU_RESERVE <- if (TOTAL_CPUS >= 8) 2 else 1
1101
+ CPU_BUDGET <- max(1, TOTAL_CPUS - CPU_RESERVE)
1102
+
1103
+
1104
+ # ------------------------------------------------------------
1105
+ # 4.6 Determine RAM-Constrained Worker Budget
1106
+ # ------------------------------------------------------------
1107
+
1108
+ if (is.na(TOTAL_RAM_GB)) {
1109
+
1110
+ # Conservative fallback when physical RAM cannot be detected.
1111
+ RAM_BUDGET_WORKERS <- max(1, min(4, CPU_BUDGET))
1112
+ RAM_HEADROOM_GB <- NA_real_
1113
+
1114
+ } else {
1115
+
1116
+ # Reserve at least 20% of total RAM, with a minimum of 1 GB.
1117
+ RAM_HEADROOM_GB <- max(1.0, TOTAL_RAM_GB * 0.20)
1118
+
1119
+ usable_gb <- max(
1120
+ 1.0,
1121
+ TOTAL_RAM_GB - RAM_HEADROOM_GB
1122
+ )
1123
+
1124
+ RAM_BUDGET_WORKERS <- max(
1125
+ 1,
1126
+ floor(usable_gb / EST_RAM_PER_WORKER_GB)
1127
+ )
1128
+ }
1129
+
1130
+
1131
+ # ------------------------------------------------------------
1132
+ # 4.7 Determine Final Process-Level Worker Count
1133
+ # ------------------------------------------------------------
1134
+ # Worker count cannot exceed:
1135
+ # 1. Number of model-fitting tasks
1136
+ # 2. Available CPU budget
1137
+ # 3. Estimated RAM budget
1138
+ # ------------------------------------------------------------
1139
+
1140
+ N_JOBS <- max(
1141
+ 1,
1142
+ min(
1143
+ TASKS_PER_DV,
1144
+ CPU_BUDGET,
1145
+ RAM_BUDGET_WORKERS
1146
+ )
1147
+ )
1148
+
1149
+
1150
+ # ------------------------------------------------------------
1151
+ # 4.8 Configure Low-Level Numerical Threads
1152
+ # ------------------------------------------------------------
1153
+ # Low-level numerical libraries remain restricted to one
1154
+ # thread regardless of the number of R-process workers.
1155
+ #
1156
+ # This preserves the hard thread-cap policy established in
1157
+ # Cell 1.2 and prevents nested numerical threading from
1158
+ # producing CPU oversubscription.
1159
+ #
1160
+ # Intentional parallelism therefore occurs only through the
1161
+ # process-level future/multisession workers.
1162
+ # ------------------------------------------------------------
1163
+
1164
+ BLAS_THREADS <- 1
1165
+
1166
+
1167
+ Sys.setenv(
1168
+ OMP_NUM_THREADS = "1",
1169
+ OPENBLAS_NUM_THREADS = "1",
1170
+ MKL_NUM_THREADS = "1",
1171
+ VECLIB_MAXIMUM_THREADS = "1",
1172
+ NUMEXPR_NUM_THREADS = "1"
1173
+ )
1174
+
1175
+
1176
+ # ------------------------------------------------------------
1177
+ # 4.9 Resource-Plan Reporting
1178
+ # ------------------------------------------------------------
1179
+
1180
+ fmt_num <- function(x, nd = 1) {
1181
+ ifelse(
1182
+ is.na(x),
1183
+ "NA",
1184
+ sprintf(paste0("%.", nd, "f"), x)
1185
+ )
1186
+ }
1187
+
1188
+ est_peak_ram <- if (is.na(TOTAL_RAM_GB)) {
1189
+ NA_real_
1190
+ } else {
1191
+ N_JOBS * EST_RAM_PER_WORKER_GB
1192
+ }
1193
+
1194
+
1195
+ message("\n", strrep("=", 72))
1196
+ message("CORRELATED RANDOM-SLOPE RESOURCE PLAN — AFFECTIVE PROVO")
1197
+ message(strrep("=", 72))
1198
+
1199
+ message(
1200
+ "Full pipeline : ",
1201
+ TOTAL_PIPELINE_MODELS,
1202
+ " models (",
1203
+ NUM_DVS, " DVs × ",
1204
+ NUM_MODELS, " candidates)"
1205
+ )
1206
+
1207
+ message(
1208
+ "Current DV run : ",
1209
+ TASKS_PER_DV,
1210
+ " candidate models"
1211
+ )
1212
+
1213
+ message("Slope variables : ", length(SLOPES))
1214
+ message("CPUs detected : ", TOTAL_CPUS)
1215
+ message("CPU reserve : ", CPU_RESERVE, " → CPU budget=", CPU_BUDGET)
1216
+ message("RAM detected GB : ", fmt_num(TOTAL_RAM_GB))
1217
+ message("RAM headroom GB : ", fmt_num(RAM_HEADROOM_GB))
1218
+ message(
1219
+ "RAM/worker GB : ",
1220
+ sprintf("%.1f", EST_RAM_PER_WORKER_GB),
1221
+ " → RAM-limited workers=",
1222
+ RAM_BUDGET_WORKERS
1223
+ )
1224
+
1225
+ message(strrep("-", 72))
1226
+ message("N_JOBS (workers) : ", N_JOBS)
1227
+ message("BLAS threads : ", BLAS_THREADS, " per worker")
1228
+ message("Est. peak RAM GB : ", fmt_num(est_peak_ram))
1229
+ message(strrep("=", 72), "\n")
1230
+
1231
+
1232
+
1233
+
1234
+
1235
+
1236
+
1237
+
1238
+
1239
+ # ============================================================
1240
+ # CELL 5 — HIGH-RELIABILITY RANDOM-SLOPE MODEL FITTING WORKER
1241
+ # ============================================================
1242
+ # Purpose:
1243
+ # Fit one candidate participant-level random-slope structure
1244
+ # for a single duration DV using a tiered optimization strategy.
1245
+ #
1246
+ # Inputs:
1247
+ # dv
1248
+ # → current duration dependent variable
1249
+ #
1250
+ # fixed_formula
1251
+ # → fixed-effects specification held constant across all
1252
+ # candidate random-slope structures for the current DV
1253
+ #
1254
+ # model_df
1255
+ # → DV-specific analysis dataset prepared before this
1256
+ # function is called
1257
+ #
1258
+ # re_terms
1259
+ # → candidate participant random-effects specification,
1260
+ # e.g.:
1261
+ #
1262
+ # "1"
1263
+ # "1 + Length"
1264
+ # "1 + Length + Frequency"
1265
+ #
1266
+ # groups_col
1267
+ # → grouping factor receiving the candidate random slopes
1268
+ # (normally Participant_ID)
1269
+ #
1270
+ # Random-effects framework:
1271
+ #
1272
+ # Correlated slopes:
1273
+ #
1274
+ # (1 + candidate_slopes | Participant_ID)
1275
+ #
1276
+ # Uncorrelated slopes:
1277
+ #
1278
+ # (1 + candidate_slopes || Participant_ID)
1279
+ #
1280
+ # Optional crossed random intercept:
1281
+ #
1282
+ # + (1 | Word_Unique_ID)
1283
+ #
1284
+ # Reliability strategy:
1285
+ # 1. Construct the complete mixed-effects formula.
1286
+ # 2. Fit the candidate using high-precision bobyqa.
1287
+ # 3. Rewrite the stored model call so allFit() does not depend
1288
+ # on temporary local symbols created inside this function.
1289
+ # 4. Evaluate the actual lme4 convergence messages and the
1290
+ # numerical optimizer convergence code separately.
1291
+ # 5. Treat optimizer convergence code 0 as SUCCESS.
1292
+ # 6. Retain a clean bobyqa fit immediately.
1293
+ # 7. Run allFit() only when bobyqa has an actual convergence
1294
+ # problem.
1295
+ # 8. If allFit() produces one or more warning-free solutions,
1296
+ # retain the valid solution with the highest log-likelihood.
1297
+ # 9. If allFit() cannot rescue the model, retain the original
1298
+ # bobyqa fit and preserve its original convergence problem.
1299
+ # 10. Record convergence, singularity, likelihood criteria,
1300
+ # observation count, runtime, and diagnostic messages.
1301
+ #
1302
+ # Estimation:
1303
+ # REML = TRUE in the present Step 2 pipeline.
1304
+ #
1305
+ # This is appropriate here because candidate random-slope
1306
+ # structures for a given DV:
1307
+ #
1308
+ # - use the same fixed-effects specification
1309
+ # - use the same observations
1310
+ # - differ only in their random-effects structure
1311
+ #
1312
+ # allFit() robustness:
1313
+ # allFit() refits the original merMod object by updating its
1314
+ # stored model call.
1315
+ #
1316
+ # A model fitted inside a helper function can otherwise retain
1317
+ # references in its call to temporary local symbols such as:
1318
+ #
1319
+ # full_formula
1320
+ # model_df
1321
+ # reml
1322
+ #
1323
+ # Those symbols may no longer be resolvable when allFit()
1324
+ # performs an update/refit.
1325
+ #
1326
+ # Therefore, immediately after the primary lmer() fit, this
1327
+ # function rewrites the stored call so that:
1328
+ #
1329
+ # formula → the actual mixed-effects formula expression
1330
+ # data → the actual prepared model data
1331
+ # REML → literal TRUE/FALSE
1332
+ # control → the complete literal lmerControl() call
1333
+ #
1334
+ # The resulting merMod object is self-contained for the
1335
+ # allFit() rescue operation.
1336
+ #
1337
+ # Important:
1338
+ # - Optimizer code 0 means successful optimization.
1339
+ # - A clean optimizer code must NOT be interpreted as a
1340
+ # convergence warning.
1341
+ # - allFit() is a rescue/robustness procedure here, not a
1342
+ # mandatory refit of every successfully converged model.
1343
+ #
1344
+ # - maxfun = 1e6 is used for the primary bobyqa fit.
1345
+ #
1346
+ # - This function does NOT construct the analysis sample.
1347
+ # - This function does NOT remove missing observations.
1348
+ # - This function does NOT apply DV > 0 filtering.
1349
+ # - This function does NOT log-transform the DV.
1350
+ # - This function does NOT standardize predictors.
1351
+ #
1352
+ # Those operations must occur before model_df is supplied.
1353
+ #
1354
+ # Shared use:
1355
+ # The same fitting logic is used for:
1356
+ #
1357
+ # Paper 1 → Affective Provo candidate slopes
1358
+ # Paper 2 → Lexical Provo candidate slopes
1359
+ #
1360
+ # The difference between papers is determined upstream by
1361
+ # SLOPES and model_df, not by this fitting function.
1362
+ #
1363
+ # Output:
1364
+ # A structured list containing:
1365
+ #
1366
+ # winner
1367
+ # → statistics from the retained model fit
1368
+ #
1369
+ # audit
1370
+ # → model-fit diagnostic record
1371
+ #
1372
+ # full_formula
1373
+ # → complete lmer formula used
1374
+ # ============================================================
1375
+
1376
+
1377
+ fit_single_candidate_tiered <- function(
1378
+ dv,
1379
+ fixed_formula,
1380
+ model_df,
1381
+ re_terms,
1382
+ groups_col,
1383
+ use_additional_intercept = FALSE,
1384
+ additional_intercept_col = NULL,
1385
+ reml = TRUE
1386
+ ) {
1387
+
1388
+
1389
+ # ----------------------------------------------------------
1390
+ # 5.1 Construct Full Mixed-Effects Formula
1391
+ # ----------------------------------------------------------
1392
+
1393
+ bar <- if (
1394
+ isTRUE(USE_UNCORRELATED_SLOPES)
1395
+ ) {
1396
+ "||"
1397
+ } else {
1398
+ "|"
1399
+ }
1400
+
1401
+
1402
+ rand_part <- paste0(
1403
+ "(",
1404
+ re_terms,
1405
+ " ",
1406
+ bar,
1407
+ " ",
1408
+ groups_col,
1409
+ ")"
1410
+ )
1411
+
1412
+
1413
+ rand_other <- if (
1414
+ use_additional_intercept &&
1415
+ !is.null(additional_intercept_col)
1416
+ ) {
1417
+
1418
+ paste0(
1419
+ " + (1 | ",
1420
+ additional_intercept_col,
1421
+ ")"
1422
+ )
1423
+
1424
+ } else {
1425
+
1426
+ ""
1427
+ }
1428
+
1429
+
1430
+ full_formula <- as.formula(
1431
+ paste(
1432
+ deparse(fixed_formula),
1433
+ "+",
1434
+ rand_part,
1435
+ rand_other
1436
+ )
1437
+ )
1438
+
1439
+
1440
+ # ----------------------------------------------------------
1441
+ # 5.2 Primary Model-Fitting Wrapper
1442
+ # ----------------------------------------------------------
1443
+ # The complete lmerControl() specification is written
1444
+ # directly inside lmer().
1445
+ #
1446
+ # maxfun = 1e6 is literal rather than stored in a temporary
1447
+ # control-object symbol.
1448
+ # ----------------------------------------------------------
1449
+
1450
+ run_fit <- function() {
1451
+
1452
+ suppressWarnings(
1453
+ lmer(
1454
+ formula = full_formula,
1455
+ data = model_df,
1456
+ REML = reml,
1457
+ control = lmerControl(
1458
+ optimizer = "bobyqa",
1459
+ optCtrl = list(
1460
+ maxfun = 1e6
1461
+ ),
1462
+ calc.derivs = TRUE,
1463
+ check.conv.grad = .makeCC(
1464
+ "warning",
1465
+ tol = 2e-3
1466
+ ),
1467
+ check.conv.singular = .makeCC(
1468
+ "message",
1469
+ tol = 1e-5
1470
+ ),
1471
+ check.nobs.vs.nlev = "ignore",
1472
+ check.nobs.vs.nRE = "ignore"
1473
+ )
1474
+ )
1475
+ )
1476
+ }
1477
+
1478
+
1479
+ # ----------------------------------------------------------
1480
+ # 5.3 Start Runtime Tracking
1481
+ # ----------------------------------------------------------
1482
+
1483
+ t0 <- proc.time()[["elapsed"]]
1484
+
1485
+
1486
+ # ----------------------------------------------------------
1487
+ # 5.4 Primary High-Precision bobyqa Fit
1488
+ # ----------------------------------------------------------
1489
+
1490
+ primary_res <- try(
1491
+ run_fit(),
1492
+ silent = TRUE
1493
+ )
1494
+
1495
+
1496
+ # ----------------------------------------------------------
1497
+ # 5.5 Determine Whether Primary Model Initialized
1498
+ # ----------------------------------------------------------
1499
+
1500
+ primary_initialized <- (
1501
+ !inherits(primary_res, "try-error") &&
1502
+ inherits(primary_res, "merMod")
1503
+ )
1504
+
1505
+
1506
+ # ----------------------------------------------------------
1507
+ # 5.6 Handle Initial-Fit Failure
1508
+ # ----------------------------------------------------------
1509
+
1510
+ if (!primary_initialized) {
1511
+
1512
+ return(
1513
+ list(
1514
+
1515
+ winner = list(
1516
+ name = paste0(
1517
+ "RE=",
1518
+ re_terms
1519
+ ),
1520
+ re_formula = re_terms,
1521
+ optimizer = "FAILED",
1522
+ selected_via = "FAILED",
1523
+ converged = FALSE,
1524
+ singular = NA,
1525
+ aic = NA_real_,
1526
+ bic = NA_real_,
1527
+ llf = NA_real_,
1528
+ nobs = nrow(model_df),
1529
+ time_s =
1530
+ proc.time()[["elapsed"]] - t0,
1531
+ status_msg = "FAILED",
1532
+ warnings = paste(
1533
+ "Model failed during initial bobyqa fitting;",
1534
+ "allFit requires an initialized merMod model and",
1535
+ "could not provide a fallback.",
1536
+ as.character(primary_res)
1537
+ )
1538
+ ),
1539
+
1540
+ audit = list(),
1541
+
1542
+ full_formula = full_formula
1543
+ )
1544
+ )
1545
+ }
1546
+
1547
+
1548
+ # ----------------------------------------------------------
1549
+ # 5.7 Make Stored Model Call Self-Contained for allFit()
1550
+ # ----------------------------------------------------------
1551
+ # allFit() uses update() on the fitted merMod object.
1552
+ #
1553
+ # The original call generated inside run_fit() contains local
1554
+ # symbols such as:
1555
+ #
1556
+ # full_formula
1557
+ # model_df
1558
+ # reml
1559
+ #
1560
+ # Replace those references with their actual values so the
1561
+ # stored call can be evaluated independently of this helper's
1562
+ # local environment.
1563
+ #
1564
+ # substitute() converts the formula object into its language
1565
+ # representation for the stored call.
1566
+ #
1567
+ # The prepared data frame itself is inserted into the call.
1568
+ # This increases the size of the stored call but makes the
1569
+ # subsequent allFit() update/refit independent of model_df.
1570
+ # ----------------------------------------------------------
1571
+
1572
+ self_contained_call <- primary_res@call
1573
+
1574
+
1575
+ self_contained_call$formula <-
1576
+ substitute(
1577
+ FORMULA_VALUE,
1578
+ list(
1579
+ FORMULA_VALUE = full_formula
1580
+ )
1581
+ )
1582
+
1583
+
1584
+ self_contained_call$data <-
1585
+ substitute(
1586
+ DATA_VALUE,
1587
+ list(
1588
+ DATA_VALUE = model_df
1589
+ )
1590
+ )
1591
+
1592
+
1593
+ self_contained_call$REML <-
1594
+ isTRUE(reml)
1595
+
1596
+
1597
+ self_contained_call$control <- quote(
1598
+ lmerControl(
1599
+ optimizer = "bobyqa",
1600
+ optCtrl = list(
1601
+ maxfun = 1e6
1602
+ ),
1603
+ calc.derivs = TRUE,
1604
+ check.conv.grad = .makeCC(
1605
+ "warning",
1606
+ tol = 2e-3
1607
+ ),
1608
+ check.conv.singular = .makeCC(
1609
+ "message",
1610
+ tol = 1e-5
1611
+ ),
1612
+ check.nobs.vs.nlev = "ignore",
1613
+ check.nobs.vs.nRE = "ignore"
1614
+ )
1615
+ )
1616
+
1617
+
1618
+ primary_res@call <-
1619
+ self_contained_call
1620
+
1621
+
1622
+ # ----------------------------------------------------------
1623
+ # 5.8 Evaluate Initial bobyqa Convergence
1624
+ # ----------------------------------------------------------
1625
+ # lme4 stores two distinct forms of convergence information:
1626
+ #
1627
+ # @optinfo$conv$lme4$messages
1628
+ # → lme4 convergence diagnostics
1629
+ #
1630
+ # @optinfo$conv$opt
1631
+ # → numerical optimizer convergence code
1632
+ #
1633
+ # Optimizer code 0 means SUCCESS.
1634
+ # ----------------------------------------------------------
1635
+
1636
+ primary_msgs_lme4 <-
1637
+ primary_res@optinfo$conv$lme4$messages
1638
+
1639
+
1640
+ primary_opt_code <-
1641
+ primary_res@optinfo$conv$opt
1642
+
1643
+
1644
+ primary_lme4_msgs <- if (
1645
+ !is.null(primary_msgs_lme4)
1646
+ ) {
1647
+
1648
+ as.character(
1649
+ unlist(
1650
+ primary_msgs_lme4
1651
+ )
1652
+ )
1653
+
1654
+ } else {
1655
+
1656
+ character(0)
1657
+ }
1658
+
1659
+
1660
+ primary_opt_failed <- FALSE
1661
+
1662
+
1663
+ if (
1664
+ !is.null(primary_opt_code) &&
1665
+ length(primary_opt_code) > 0
1666
+ ) {
1667
+
1668
+ primary_opt_code_num <- suppressWarnings(
1669
+ as.numeric(
1670
+ unlist(
1671
+ primary_opt_code
1672
+ )
1673
+ )
1674
+ )
1675
+
1676
+
1677
+ primary_opt_failed <- any(
1678
+ is.na(primary_opt_code_num) |
1679
+ primary_opt_code_num != 0
1680
+ )
1681
+ }
1682
+
1683
+
1684
+ primary_is_good <- (
1685
+ length(primary_lme4_msgs) == 0 &&
1686
+ !primary_opt_failed
1687
+ )
1688
+
1689
+
1690
+ # ----------------------------------------------------------
1691
+ # 5.9 Retain Clean bobyqa Fit or Run allFit() Rescue
1692
+ # ----------------------------------------------------------
1693
+
1694
+ if (primary_is_good) {
1695
+
1696
+ res <- primary_res
1697
+
1698
+ selected_via <-
1699
+ "bobyqa"
1700
+
1701
+ retained_warning <-
1702
+ NA_character_
1703
+
1704
+
1705
+ } else {
1706
+
1707
+
1708
+ # --------------------------------------------------------
1709
+ # Preserve Original bobyqa Convergence Diagnostics
1710
+ # --------------------------------------------------------
1711
+
1712
+ primary_diagnostic_msgs <-
1713
+ primary_lme4_msgs
1714
+
1715
+
1716
+ if (primary_opt_failed) {
1717
+
1718
+ primary_diagnostic_msgs <- c(
1719
+ primary_diagnostic_msgs,
1720
+ paste0(
1721
+ "optimizer convergence code: ",
1722
+ paste(
1723
+ unlist(
1724
+ primary_opt_code
1725
+ ),
1726
+ collapse = ", "
1727
+ )
1728
+ )
1729
+ )
1730
+ }
1731
+
1732
+
1733
+ primary_warning_txt <- if (
1734
+ length(primary_diagnostic_msgs) > 0
1735
+ ) {
1736
+
1737
+ paste(
1738
+ primary_diagnostic_msgs,
1739
+ collapse = " | "
1740
+ )
1741
+
1742
+ } else {
1743
+
1744
+ NA_character_
1745
+ }
1746
+
1747
+
1748
+ # --------------------------------------------------------
1749
+ # Run allFit() as a Rescue Procedure
1750
+ # --------------------------------------------------------
1751
+
1752
+ message(
1753
+ " -> bobyqa convergence issue; running allFit() for ",
1754
+ re_terms,
1755
+ "..."
1756
+ )
1757
+
1758
+
1759
+ af <- try(
1760
+ suppressWarnings(
1761
+ lme4::allFit(
1762
+ primary_res,
1763
+ verbose = FALSE,
1764
+ parallel = "no"
1765
+ )
1766
+ ),
1767
+ silent = TRUE
1768
+ )
1769
+
1770
+
1771
+ # --------------------------------------------------------
1772
+ # 5.9A allFit() Itself Failed
1773
+ # --------------------------------------------------------
1774
+
1775
+ if (inherits(af, "try-error")) {
1776
+
1777
+ res <- primary_res
1778
+
1779
+ selected_via <-
1780
+ "bobyqa (allFit failed)"
1781
+
1782
+ retained_warning <- paste(
1783
+ primary_warning_txt,
1784
+ "allFit error:",
1785
+ as.character(af),
1786
+ sep = " | "
1787
+ )
1788
+
1789
+
1790
+ } else {
1791
+
1792
+
1793
+ ss <- summary(
1794
+ af
1795
+ )
1796
+
1797
+
1798
+ # ------------------------------------------------------
1799
+ # 5.9B Identify Warning-Free allFit Solutions
1800
+ # ------------------------------------------------------
1801
+
1802
+ valid_indices <- which(
1803
+ is.finite(
1804
+ ss$logLik
1805
+ ) &
1806
+ vapply(
1807
+ ss$msgs,
1808
+ function(x) {
1809
+ is.null(x) ||
1810
+ length(x) == 0
1811
+ },
1812
+ logical(1)
1813
+ )
1814
+ )
1815
+
1816
+
1817
+ # ------------------------------------------------------
1818
+ # 5.9C No Warning-Free allFit Solution
1819
+ # ------------------------------------------------------
1820
+
1821
+ if (length(valid_indices) == 0) {
1822
+
1823
+ res <- primary_res
1824
+
1825
+ selected_via <-
1826
+ "bobyqa (allFit found no warning-free solution)"
1827
+
1828
+ retained_warning <-
1829
+ primary_warning_txt
1830
+
1831
+
1832
+ } else {
1833
+
1834
+
1835
+ # ----------------------------------------------------
1836
+ # 5.9D Retain Best Clean allFit Solution
1837
+ # ----------------------------------------------------
1838
+ # allFit() optimizers estimate the same statistical
1839
+ # model. Among warning-free solutions, retain the one
1840
+ # with the highest reported log-likelihood.
1841
+ # ----------------------------------------------------
1842
+
1843
+ best_idx <- valid_indices[
1844
+ which.max(
1845
+ ss$logLik[
1846
+ valid_indices
1847
+ ]
1848
+ )
1849
+ ]
1850
+
1851
+
1852
+ res <- af[[best_idx]]
1853
+
1854
+
1855
+ selected_via <- paste0(
1856
+ "allFit: ",
1857
+ names(af)[best_idx]
1858
+ )
1859
+
1860
+
1861
+ retained_warning <-
1862
+ NA_character_
1863
+ }
1864
+ }
1865
+ }
1866
+
1867
+
1868
+ # ----------------------------------------------------------
1869
+ # 5.10 Extract Final Convergence Diagnostics
1870
+ # ----------------------------------------------------------
1871
+
1872
+ msgs_lme4 <-
1873
+ res@optinfo$conv$lme4$messages
1874
+
1875
+
1876
+ opt_code <-
1877
+ res@optinfo$conv$opt
1878
+
1879
+
1880
+ lme4_msgs <- if (
1881
+ !is.null(msgs_lme4)
1882
+ ) {
1883
+
1884
+ as.character(
1885
+ unlist(
1886
+ msgs_lme4
1887
+ )
1888
+ )
1889
+
1890
+ } else {
1891
+
1892
+ character(0)
1893
+ }
1894
+
1895
+
1896
+ opt_failed <- FALSE
1897
+
1898
+
1899
+ if (
1900
+ !is.null(opt_code) &&
1901
+ length(opt_code) > 0
1902
+ ) {
1903
+
1904
+ opt_code_num <- suppressWarnings(
1905
+ as.numeric(
1906
+ unlist(
1907
+ opt_code
1908
+ )
1909
+ )
1910
+ )
1911
+
1912
+
1913
+ opt_failed <- any(
1914
+ is.na(opt_code_num) |
1915
+ opt_code_num != 0
1916
+ )
1917
+ }
1918
+
1919
+
1920
+ final_diagnostic_msgs <-
1921
+ lme4_msgs
1922
+
1923
+
1924
+ if (opt_failed) {
1925
+
1926
+ final_diagnostic_msgs <- c(
1927
+ final_diagnostic_msgs,
1928
+ paste0(
1929
+ "optimizer convergence code: ",
1930
+ paste(
1931
+ unlist(
1932
+ opt_code
1933
+ ),
1934
+ collapse = ", "
1935
+ )
1936
+ )
1937
+ )
1938
+ }
1939
+
1940
+
1941
+ final_warning_txt <- if (
1942
+ length(final_diagnostic_msgs) > 0
1943
+ ) {
1944
+
1945
+ paste(
1946
+ final_diagnostic_msgs,
1947
+ collapse = " | "
1948
+ )
1949
+
1950
+ } else {
1951
+
1952
+ NA_character_
1953
+ }
1954
+
1955
+
1956
+ # ----------------------------------------------------------
1957
+ # 5.11 Combine Rescue Information and Final Diagnostics
1958
+ # ----------------------------------------------------------
1959
+
1960
+ warning_parts <- c(
1961
+
1962
+ if (!is.na(retained_warning)) {
1963
+ retained_warning
1964
+ } else {
1965
+ NULL
1966
+ },
1967
+
1968
+ if (!is.na(final_warning_txt)) {
1969
+ final_warning_txt
1970
+ } else {
1971
+ NULL
1972
+ }
1973
+ )
1974
+
1975
+
1976
+ warning_parts <- unique(
1977
+ warning_parts[
1978
+ nzchar(
1979
+ warning_parts
1980
+ )
1981
+ ]
1982
+ )
1983
+
1984
+
1985
+ warn_txt <- if (
1986
+ length(warning_parts) > 0
1987
+ ) {
1988
+
1989
+ paste(
1990
+ warning_parts,
1991
+ collapse = " | "
1992
+ )
1993
+
1994
+ } else {
1995
+
1996
+ NA_character_
1997
+ }
1998
+
1999
+
2000
+ converged <-
2001
+ is.na(warn_txt)
2002
+
2003
+
2004
+ # ----------------------------------------------------------
2005
+ # 5.12 Extract Final Model Statistics
2006
+ # ----------------------------------------------------------
2007
+
2008
+ final_stats <- list(
2009
+
2010
+ name = paste0(
2011
+ "RE=",
2012
+ re_terms
2013
+ ),
2014
+
2015
+ re_formula =
2016
+ re_terms,
2017
+
2018
+ optimizer =
2019
+ res@optinfo$optimizer,
2020
+
2021
+ selected_via =
2022
+ selected_via,
2023
+
2024
+ converged =
2025
+ converged,
2026
+
2027
+ singular =
2028
+ isSingular(
2029
+ res,
2030
+ tol = 1e-5
2031
+ ),
2032
+
2033
+ aic =
2034
+ AIC(res),
2035
+
2036
+ bic =
2037
+ BIC(res),
2038
+
2039
+ llf =
2040
+ as.numeric(
2041
+ logLik(res)
2042
+ ),
2043
+
2044
+ nobs =
2045
+ nobs(res),
2046
+
2047
+ time_s =
2048
+ proc.time()[["elapsed"]] - t0,
2049
+
2050
+ status_msg =
2051
+ if (converged) {
2052
+ "OK"
2053
+ } else {
2054
+ "WARN"
2055
+ },
2056
+
2057
+ warnings =
2058
+ warn_txt
2059
+ )
2060
+
2061
+
2062
+ # ----------------------------------------------------------
2063
+ # 5.13 Structured Return
2064
+ # ----------------------------------------------------------
2065
+
2066
+ list(
2067
+ winner =
2068
+ final_stats,
2069
+
2070
+ audit =
2071
+ list(
2072
+ final_stats
2073
+ ),
2074
+
2075
+ full_formula =
2076
+ full_formula
2077
+ )
2078
+ }
2079
+
2080
+
2081
+
2082
+
2083
+
2084
+
2085
+
2086
+
2087
+
2088
+ # ============================================================
2089
+ # CELL 6/7 — DV-SPECIFIC PREPARATION + PARALLEL MODEL RUNNER
2090
+ # ============================================================
2091
+ # Purpose:
2092
+ # Construct one analysis-ready dataset per duration DV and
2093
+ # compare all candidate correlated random-slope structures
2094
+ # using that identical dataset.
2095
+ #
2096
+ # Responsibilities:
2097
+ # 1. Validate all variables required for the current DV.
2098
+ # 2. Construct the DV-specific complete-case sample.
2099
+ # 3. Remove non-positive values of the current duration DV.
2100
+ # 4. Natural-log transform the current duration DV.
2101
+ # 5. Standardize predictors using population SD (DDOF = 0)
2102
+ # AFTER the final DV-specific sample has been established.
2103
+ # 6. Convert grouping variables to factors.
2104
+ # 7. Fit every candidate random-slope structure using the
2105
+ # exact same prepared dataset.
2106
+ # 8. Execute candidate models in parallel.
2107
+ # 9. Collect model diagnostics and fit statistics.
2108
+ # 10. Evaluate and order candidate structures using
2109
+ # convergence, singularity, and BIC/AIC.
2110
+ # 11. Produce a detailed sample-size audit.
2111
+ #
2112
+ # Paper 1 fixed-effects specification:
2113
+ #
2114
+ # Lexical predictors:
2115
+ # - Length
2116
+ # - Predictability
2117
+ # - Frequency
2118
+ #
2119
+ # Affective predictors:
2120
+ # - Valence
2121
+ # - Arousal
2122
+ # - Dominance
2123
+ #
2124
+ # Important:
2125
+ # Filtering is DV-specific.
2126
+ #
2127
+ # No global IA_DWELL_TIME > 0 restriction is imposed.
2128
+ # Instead, the CURRENT duration DV must be non-missing and > 0.
2129
+ #
2130
+ # Predictor standardization occurs only AFTER this DV-specific
2131
+ # sample has been established. All candidate random-slope
2132
+ # models for the same DV therefore receive:
2133
+ #
2134
+ # - identical observations
2135
+ # - identical transformed DV values
2136
+ # - identical standardized predictor values
2137
+ # - identical fixed-effects specification
2138
+ #
2139
+ # Only the participant-level random-slope structure changes.
2140
+ #
2141
+ # This is essential for fair AIC/BIC comparison.
2142
+ # ============================================================
2143
+
2144
+
2145
+ # ------------------------------------------------------------
2146
+ # 6.1 Population-SD Standardization Function (DDOF = 0)
2147
+ # ------------------------------------------------------------
2148
+ # R's sd() uses sample SD (n - 1). The conversion below yields
2149
+ # population SD (n), matching DDOF = 0 standardization used
2150
+ # elsewhere in the analysis pipeline.
2151
+ # ------------------------------------------------------------
2152
+
2153
+ zscore_ddof0 <- function(x) {
2154
+
2155
+ x <- suppressWarnings(
2156
+ as.numeric(x)
2157
+ )
2158
+
2159
+ n <- sum(
2160
+ !is.na(x)
2161
+ )
2162
+
2163
+ if (n <= 1) {
2164
+ return(x)
2165
+ }
2166
+
2167
+ s1 <- sd(
2168
+ x,
2169
+ na.rm = TRUE
2170
+ )
2171
+
2172
+ if (
2173
+ !is.finite(s1) ||
2174
+ s1 <= 0
2175
+ ) {
2176
+ return(x)
2177
+ }
2178
+
2179
+ s0 <- s1 * sqrt(
2180
+ (n - 1) / n
2181
+ )
2182
+
2183
+ (
2184
+ x - mean(
2185
+ x,
2186
+ na.rm = TRUE
2187
+ )
2188
+ ) / s0
2189
+ }
2190
+
2191
+
2192
+ # ------------------------------------------------------------
2193
+ # 6.2 DV-Specific Analysis-Data Preparation
2194
+ # ------------------------------------------------------------
2195
+
2196
+ prep_df_complete_cases <- function(
2197
+ df,
2198
+ dv,
2199
+ participant_col,
2200
+ required_cols,
2201
+ use_additional_intercept = FALSE,
2202
+ additional_intercept_col = NULL
2203
+ ) {
2204
+
2205
+ needed <- unique(
2206
+ c(
2207
+ dv,
2208
+ participant_col,
2209
+ required_cols,
2210
+ if (use_additional_intercept) {
2211
+ additional_intercept_col
2212
+ } else {
2213
+ NULL
2214
+ }
2215
+ )
2216
+ )
2217
+
2218
+
2219
+ # ----------------------------------------------------------
2220
+ # Validate Required Variables
2221
+ # ----------------------------------------------------------
2222
+
2223
+ missing_required <- setdiff(
2224
+ needed,
2225
+ names(df)
2226
+ )
2227
+
2228
+ if (length(missing_required) > 0) {
2229
+
2230
+ stop(
2231
+ "Missing required variable(s) for ",
2232
+ dv,
2233
+ ": ",
2234
+ paste(
2235
+ missing_required,
2236
+ collapse = ", "
2237
+ )
2238
+ )
2239
+ }
2240
+
2241
+
2242
+ # ----------------------------------------------------------
2243
+ # Select Required Variables
2244
+ # ----------------------------------------------------------
2245
+
2246
+ df_clean <- df %>%
2247
+ select(
2248
+ all_of(needed)
2249
+ )
2250
+
2251
+ n_source <- nrow(
2252
+ df_clean
2253
+ )
2254
+
2255
+
2256
+ # ----------------------------------------------------------
2257
+ # Coerce DV and Continuous Predictors to Numeric
2258
+ # ----------------------------------------------------------
2259
+
2260
+ numeric_cols <- unique(
2261
+ c(
2262
+ dv,
2263
+ required_cols
2264
+ )
2265
+ )
2266
+
2267
+ df_clean <- df_clean %>%
2268
+ mutate(
2269
+ across(
2270
+ all_of(numeric_cols),
2271
+ ~ suppressWarnings(
2272
+ as.numeric(.x)
2273
+ )
2274
+ )
2275
+ )
2276
+
2277
+
2278
+ # ----------------------------------------------------------
2279
+ # Remove Missing Values
2280
+ # ----------------------------------------------------------
2281
+
2282
+ df_clean <- df_clean %>%
2283
+ drop_na()
2284
+
2285
+ n_complete <- nrow(
2286
+ df_clean
2287
+ )
2288
+
2289
+ n_removed_missing <-
2290
+ n_source - n_complete
2291
+
2292
+
2293
+ # ----------------------------------------------------------
2294
+ # Retain Positive Values of the Current Duration DV
2295
+ # ----------------------------------------------------------
2296
+ # Zero/non-positive values are excluded because the present
2297
+ # models analyze positive duration observations.
2298
+ #
2299
+ # Do not interpret every zero here as equivalent to IA_SKIP.
2300
+ # ----------------------------------------------------------
2301
+
2302
+ df_clean <- df_clean %>%
2303
+ filter(
2304
+ .data[[dv]] > 0
2305
+ )
2306
+
2307
+ n_positive <- nrow(
2308
+ df_clean
2309
+ )
2310
+
2311
+ n_removed_nonpositive <-
2312
+ n_complete - n_positive
2313
+
2314
+
2315
+ # ----------------------------------------------------------
2316
+ # Natural-Log Transform Current DV
2317
+ # ----------------------------------------------------------
2318
+
2319
+ df_clean[[dv]] <- log(
2320
+ df_clean[[dv]]
2321
+ )
2322
+
2323
+
2324
+ # ----------------------------------------------------------
2325
+ # Standardize Predictors Within Final DV-Specific Sample
2326
+ # ----------------------------------------------------------
2327
+
2328
+ df_clean <- df_clean %>%
2329
+ mutate(
2330
+ across(
2331
+ all_of(required_cols),
2332
+ zscore_ddof0
2333
+ )
2334
+ )
2335
+
2336
+
2337
+ # ----------------------------------------------------------
2338
+ # Convert Grouping Variables to Factors
2339
+ # ----------------------------------------------------------
2340
+
2341
+ df_clean[[participant_col]] <- as.factor(
2342
+ as.character(
2343
+ df_clean[[participant_col]]
2344
+ )
2345
+ )
2346
+
2347
+
2348
+ if (
2349
+ use_additional_intercept &&
2350
+ !is.null(additional_intercept_col)
2351
+ ) {
2352
+
2353
+ df_clean[[additional_intercept_col]] <- as.factor(
2354
+ as.character(
2355
+ df_clean[[additional_intercept_col]]
2356
+ )
2357
+ )
2358
+ }
2359
+
2360
+
2361
+ # ----------------------------------------------------------
2362
+ # Attach Filtering Diagnostics
2363
+ # ----------------------------------------------------------
2364
+
2365
+ attr(
2366
+ df_clean,
2367
+ "filter_summary"
2368
+ ) <- tibble(
2369
+
2370
+ DV =
2371
+ dv,
2372
+
2373
+ N_Source =
2374
+ n_source,
2375
+
2376
+ N_Removed_Missing =
2377
+ n_removed_missing,
2378
+
2379
+ N_Complete =
2380
+ n_complete,
2381
+
2382
+ N_Removed_NonPositive =
2383
+ n_removed_nonpositive,
2384
+
2385
+ N_Final =
2386
+ n_positive,
2387
+
2388
+ Percent_Retained =
2389
+ if (n_source > 0) {
2390
+
2391
+ round(
2392
+ 100 * n_positive / n_source,
2393
+ 2
2394
+ )
2395
+
2396
+ } else {
2397
+
2398
+ NA_real_
2399
+ },
2400
+
2401
+ N_Participants =
2402
+ n_distinct(
2403
+ df_clean[[participant_col]]
2404
+ ),
2405
+
2406
+ N_Additional_Intercept =
2407
+ if (
2408
+ use_additional_intercept &&
2409
+ !is.null(additional_intercept_col)
2410
+ ) {
2411
+
2412
+ n_distinct(
2413
+ df_clean[[additional_intercept_col]]
2414
+ )
2415
+
2416
+ } else {
2417
+
2418
+ NA_integer_
2419
+ }
2420
+ )
2421
+
2422
+
2423
+ message(
2424
+ " Source observations : ",
2425
+ format(
2426
+ n_source,
2427
+ big.mark = ","
2428
+ )
2429
+ )
2430
+
2431
+ message(
2432
+ " Removed for missingness : ",
2433
+ format(
2434
+ n_removed_missing,
2435
+ big.mark = ","
2436
+ )
2437
+ )
2438
+
2439
+ message(
2440
+ " Removed DV <= 0 : ",
2441
+ format(
2442
+ n_removed_nonpositive,
2443
+ big.mark = ","
2444
+ )
2445
+ )
2446
+
2447
+ message(
2448
+ " Final modeling N : ",
2449
+ format(
2450
+ n_positive,
2451
+ big.mark = ","
2452
+ )
2453
+ )
2454
+
2455
+ message(
2456
+ " DV log transformation : APPLIED"
2457
+ )
2458
+
2459
+ message(
2460
+ " Predictor standardization : APPLIED (DDOF = 0)"
2461
+ )
2462
+
2463
+
2464
+ df_clean
2465
+ }
2466
+
2467
+
2468
+ # ------------------------------------------------------------
2469
+ # 6.3 Dynamic Correlated Random-Slope Selection Engine
2470
+ # ------------------------------------------------------------
2471
+
2472
+ select_re_structure_dynamic <- function(
2473
+ df,
2474
+ dv,
2475
+ re_candidates,
2476
+ participant_col = "Participant_ID",
2477
+ additional_intercept_col = NULL,
2478
+ use_additional_intercept = FALSE,
2479
+ controls = c(
2480
+ "Length",
2481
+ "Predictability",
2482
+ "Frequency"
2483
+ ),
2484
+ emotions = c(
2485
+ "Valence",
2486
+ "Arousal",
2487
+ "Dominance"
2488
+ ),
2489
+ rank_by = c(
2490
+ "BIC",
2491
+ "AIC"
2492
+ ),
2493
+ n_jobs = 1
2494
+ ) {
2495
+
2496
+
2497
+ # ----------------------------------------------------------
2498
+ # 6.3.1 Configuration
2499
+ # ----------------------------------------------------------
2500
+
2501
+ rank_by <- match.arg(
2502
+ toupper(rank_by),
2503
+ c(
2504
+ "BIC",
2505
+ "AIC"
2506
+ )
2507
+ )
2508
+
2509
+ n_jobs <- max(
2510
+ 1L,
2511
+ as.integer(n_jobs)
2512
+ )
2513
+
2514
+
2515
+ required_cols <- unique(
2516
+ c(
2517
+ controls,
2518
+ emotions
2519
+ )
2520
+ )
2521
+
2522
+
2523
+ # ----------------------------------------------------------
2524
+ # Validate Fixed-Effect Variables
2525
+ # ----------------------------------------------------------
2526
+
2527
+ missing_fixed <- setdiff(
2528
+ required_cols,
2529
+ names(df)
2530
+ )
2531
+
2532
+ if (length(missing_fixed) > 0) {
2533
+
2534
+ stop(
2535
+ "Missing fixed-effect variable(s) for ",
2536
+ dv,
2537
+ ": ",
2538
+ paste(
2539
+ missing_fixed,
2540
+ collapse = ", "
2541
+ )
2542
+ )
2543
+ }
2544
+
2545
+
2546
+ # ----------------------------------------------------------
2547
+ # Construct Fixed-Effects Formula
2548
+ # ----------------------------------------------------------
2549
+
2550
+ fixed_formula <- as.formula(
2551
+ paste0(
2552
+ dv,
2553
+ " ~ ",
2554
+ paste(
2555
+ required_cols,
2556
+ collapse = " + "
2557
+ )
2558
+ )
2559
+ )
2560
+
2561
+
2562
+ # ----------------------------------------------------------
2563
+ # 6.3.2 Prepare ONE Modeling Dataset for Current DV
2564
+ # ----------------------------------------------------------
2565
+
2566
+ model_df <- prep_df_complete_cases(
2567
+ df = df,
2568
+ dv = dv,
2569
+ participant_col = participant_col,
2570
+ required_cols = required_cols,
2571
+ use_additional_intercept =
2572
+ use_additional_intercept,
2573
+ additional_intercept_col =
2574
+ additional_intercept_col
2575
+ )
2576
+
2577
+
2578
+ filter_summary <- attr(
2579
+ model_df,
2580
+ "filter_summary"
2581
+ )
2582
+
2583
+
2584
+ # ----------------------------------------------------------
2585
+ # Safety Check: Final Modeling Dataset Must Be Nonempty
2586
+ # ----------------------------------------------------------
2587
+
2588
+ if (nrow(model_df) == 0) {
2589
+
2590
+ stop(
2591
+ "No eligible observations remain for ",
2592
+ dv,
2593
+ " after DV-specific preparation."
2594
+ )
2595
+ }
2596
+
2597
+
2598
+ # ----------------------------------------------------------
2599
+ # 6.3.3 Row-Count Audit
2600
+ # ----------------------------------------------------------
2601
+
2602
+ rowcounts <- dv_rowcount_summary(
2603
+ df = df,
2604
+ dv = dv,
2605
+ required_cols = c(
2606
+ required_cols,
2607
+ participant_col,
2608
+ if (use_additional_intercept) {
2609
+ additional_intercept_col
2610
+ } else {
2611
+ NULL
2612
+ }
2613
+ ),
2614
+ label = paste0(
2615
+ dv,
2616
+ "_AIC_BIC_rows"
2617
+ )
2618
+ ) %>%
2619
+ mutate(
2620
+
2621
+ rows_after_complete_case =
2622
+ filter_summary$N_Complete,
2623
+
2624
+ rows_removed_DV_nonpositive =
2625
+ filter_summary$N_Removed_NonPositive,
2626
+
2627
+ final_rows_used_for_AIC_BIC =
2628
+ filter_summary$N_Final,
2629
+
2630
+ pct_final_rows_retained =
2631
+ filter_summary$Percent_Retained
2632
+ )
2633
+
2634
+
2635
+ # ----------------------------------------------------------
2636
+ # 6.3.4 Candidate Execution Ordering
2637
+ # ----------------------------------------------------------
2638
+
2639
+ cand_list <- rev(
2640
+ re_candidates
2641
+ )
2642
+
2643
+
2644
+ indexed <- tibble(
2645
+ idx = seq_along(
2646
+ cand_list
2647
+ ),
2648
+ candidate = cand_list
2649
+ )
2650
+
2651
+
2652
+ # ----------------------------------------------------------
2653
+ # 6.3.5 Parallel Execution Setup
2654
+ # ----------------------------------------------------------
2655
+
2656
+ future::plan(
2657
+ future::multisession,
2658
+ workers = n_jobs
2659
+ )
2660
+
2661
+
2662
+ progressr::handlers(
2663
+ global = TRUE
2664
+ )
2665
+
2666
+
2667
+ # ----------------------------------------------------------
2668
+ # 6.3.6 Parallel Candidate-Model Execution
2669
+ # ----------------------------------------------------------
2670
+
2671
+ results_payload <- progressr::with_progress({
2672
+
2673
+ progressor_obj <- progressr::progressor(
2674
+ steps = nrow(indexed)
2675
+ )
2676
+
2677
+
2678
+ future.apply::future_lapply(
2679
+
2680
+ seq_len(
2681
+ nrow(indexed)
2682
+ ),
2683
+
2684
+ function(i) {
2685
+
2686
+ idx <- indexed$idx[i]
2687
+ cand <- indexed$candidate[i]
2688
+
2689
+
2690
+ t0 <- proc.time()[["elapsed"]]
2691
+
2692
+
2693
+ fit <- fit_single_candidate_tiered(
2694
+ dv = dv,
2695
+ fixed_formula = fixed_formula,
2696
+ model_df = model_df,
2697
+ re_terms = cand,
2698
+ groups_col = participant_col,
2699
+ use_additional_intercept =
2700
+ use_additional_intercept,
2701
+ additional_intercept_col =
2702
+ additional_intercept_col,
2703
+ reml = TRUE
2704
+ )
2705
+
2706
+
2707
+ progressor_obj(
2708
+ message = paste0(
2709
+ "[",
2710
+ idx,
2711
+ "/",
2712
+ nrow(indexed),
2713
+ "] ",
2714
+ cand
2715
+ )
2716
+ )
2717
+
2718
+
2719
+ list(
2720
+ idx = idx,
2721
+ candidate = cand,
2722
+ winner = fit$winner,
2723
+ audit = fit$audit,
2724
+ task_wall_s =
2725
+ proc.time()[["elapsed"]] - t0
2726
+ )
2727
+ },
2728
+
2729
+ future.seed = TRUE,
2730
+
2731
+ future.globals = list(
2732
+
2733
+ indexed =
2734
+ indexed,
2735
+
2736
+ dv =
2737
+ dv,
2738
+
2739
+ fixed_formula =
2740
+ fixed_formula,
2741
+
2742
+ model_df =
2743
+ model_df,
2744
+
2745
+ participant_col =
2746
+ participant_col,
2747
+
2748
+ additional_intercept_col =
2749
+ additional_intercept_col,
2750
+
2751
+ use_additional_intercept =
2752
+ use_additional_intercept,
2753
+
2754
+ fit_single_candidate_tiered =
2755
+ fit_single_candidate_tiered,
2756
+
2757
+ USE_UNCORRELATED_SLOPES =
2758
+ USE_UNCORRELATED_SLOPES
2759
+ ),
2760
+
2761
+ future.packages = c(
2762
+ "lme4"
2763
+ )
2764
+ )
2765
+ })
2766
+
2767
+
2768
+ # ----------------------------------------------------------
2769
+ # 6.3.7 Restore Deterministic Execution Order
2770
+ # ----------------------------------------------------------
2771
+
2772
+ results_payload <- results_payload[
2773
+ order(
2774
+ vapply(
2775
+ results_payload,
2776
+ `[[`,
2777
+ numeric(1),
2778
+ "idx"
2779
+ )
2780
+ )
2781
+ ]
2782
+
2783
+
2784
+ # ----------------------------------------------------------
2785
+ # 6.3.8 Collect Model Results and Audit Records
2786
+ # ----------------------------------------------------------
2787
+
2788
+ winner_rows <- list()
2789
+ audit_rows <- list()
2790
+
2791
+
2792
+ for (payload in results_payload) {
2793
+
2794
+ w <- payload$winner
2795
+
2796
+
2797
+ if (
2798
+ is.finite(w$aic) &&
2799
+ is.finite(w$bic)
2800
+ ) {
2801
+
2802
+ winner_rows <- append(
2803
+ winner_rows,
2804
+ list(
2805
+ tibble(
2806
+
2807
+ idx =
2808
+ payload$idx,
2809
+
2810
+ candidate =
2811
+ payload$candidate,
2812
+
2813
+ re_formula =
2814
+ w$re_formula,
2815
+
2816
+ optimizer =
2817
+ w$optimizer,
2818
+
2819
+ selected_via =
2820
+ w$selected_via,
2821
+
2822
+ converged =
2823
+ w$converged,
2824
+
2825
+ singular =
2826
+ w$singular,
2827
+
2828
+ aic =
2829
+ w$aic,
2830
+
2831
+ bic =
2832
+ w$bic,
2833
+
2834
+ llf =
2835
+ w$llf,
2836
+
2837
+ nobs =
2838
+ as.integer(
2839
+ w$nobs
2840
+ ),
2841
+
2842
+ winner_fit_time_s =
2843
+ as.numeric(
2844
+ w$time_s
2845
+ ),
2846
+
2847
+ candidate_task_time_s =
2848
+ as.numeric(
2849
+ payload$task_wall_s
2850
+ ),
2851
+
2852
+ warnings =
2853
+ w$warnings,
2854
+
2855
+ status =
2856
+ w$status_msg
2857
+ )
2858
+ )
2859
+ )
2860
+ }
2861
+
2862
+
2863
+ for (a in payload$audit) {
2864
+
2865
+ audit_rows <- append(
2866
+ audit_rows,
2867
+ list(
2868
+ tibble(
2869
+
2870
+ idx =
2871
+ payload$idx,
2872
+
2873
+ candidate =
2874
+ payload$candidate,
2875
+
2876
+ re_formula =
2877
+ a$re_formula,
2878
+
2879
+ optimizer =
2880
+ a$optimizer,
2881
+
2882
+ selected_via =
2883
+ a$selected_via,
2884
+
2885
+ status =
2886
+ a$status_msg,
2887
+
2888
+ converged =
2889
+ a$converged,
2890
+
2891
+ singular =
2892
+ a$singular,
2893
+
2894
+ aic =
2895
+ a$aic,
2896
+
2897
+ bic =
2898
+ a$bic,
2899
+
2900
+ llf =
2901
+ a$llf,
2902
+
2903
+ nobs =
2904
+ as.integer(
2905
+ a$nobs
2906
+ ),
2907
+
2908
+ time_s =
2909
+ as.numeric(
2910
+ a$time_s
2911
+ ),
2912
+
2913
+ warnings =
2914
+ a$warnings
2915
+ )
2916
+ )
2917
+ )
2918
+ }
2919
+ }
2920
+
2921
+
2922
+ # ----------------------------------------------------------
2923
+ # 6.3.9 Final Candidate Evaluation and Selection Ordering
2924
+ # ----------------------------------------------------------
2925
+
2926
+ df_results <- if (
2927
+ length(winner_rows) > 0
2928
+ ) {
2929
+
2930
+ bind_rows(
2931
+ winner_rows
2932
+ )
2933
+
2934
+ } else {
2935
+
2936
+ tibble()
2937
+ }
2938
+
2939
+
2940
+ df_audit <- if (
2941
+ length(audit_rows) > 0
2942
+ ) {
2943
+
2944
+ bind_rows(
2945
+ audit_rows
2946
+ )
2947
+
2948
+ } else {
2949
+
2950
+ tibble()
2951
+ }
2952
+
2953
+
2954
+ if (nrow(df_results) > 0) {
2955
+
2956
+ sort_col <- if (
2957
+ rank_by == "BIC"
2958
+ ) {
2959
+
2960
+ "bic"
2961
+
2962
+ } else {
2963
+
2964
+ "aic"
2965
+ }
2966
+
2967
+
2968
+ # --------------------------------------------------------
2969
+ # Identify Models Eligible for Primary Structure Selection
2970
+ # --------------------------------------------------------
2971
+
2972
+ df_results <- df_results %>%
2973
+ mutate(
2974
+ selection_eligible =
2975
+ converged %in% TRUE &
2976
+ singular %in% FALSE
2977
+ )
2978
+
2979
+
2980
+ # --------------------------------------------------------
2981
+ # Compute Raw Information-Criterion Differences
2982
+ # --------------------------------------------------------
2983
+
2984
+ df_results <- df_results %>%
2985
+ mutate(
2986
+
2987
+ delta_aic =
2988
+ aic - min(
2989
+ aic,
2990
+ na.rm = TRUE
2991
+ ),
2992
+
2993
+ delta_bic =
2994
+ bic - min(
2995
+ bic,
2996
+ na.rm = TRUE
2997
+ )
2998
+ )
2999
+
3000
+
3001
+ # --------------------------------------------------------
3002
+ # Rank Eligible Models First
3003
+ # --------------------------------------------------------
3004
+
3005
+ df_results <- df_results %>%
3006
+ arrange(
3007
+ desc(
3008
+ selection_eligible
3009
+ ),
3010
+ .data[[sort_col]]
3011
+ )
3012
+ }
3013
+
3014
+
3015
+ # ----------------------------------------------------------
3016
+ # 6.3.10 Verify Equal Observation Counts Across Candidates
3017
+ # ----------------------------------------------------------
3018
+
3019
+ if (nrow(df_results) > 0) {
3020
+
3021
+ unique_nobs <- unique(
3022
+ df_results$nobs
3023
+ )
3024
+
3025
+
3026
+ if (length(unique_nobs) != 1) {
3027
+
3028
+ warning(
3029
+ "Candidate models for ",
3030
+ dv,
3031
+ " were fitted with different observation counts."
3032
+ )
3033
+ }
3034
+ }
3035
+
3036
+
3037
+ # ----------------------------------------------------------
3038
+ # 6.3.11 Return Results
3039
+ # ----------------------------------------------------------
3040
+
3041
+ list(
3042
+
3043
+ df_results =
3044
+ df_results,
3045
+
3046
+ df_audit =
3047
+ df_audit,
3048
+
3049
+ rowcounts =
3050
+ rowcounts,
3051
+
3052
+ filter_summary =
3053
+ filter_summary
3054
+ )
3055
+ }
3056
+
3057
+
3058
+
3059
+
3060
+
3061
+
3062
+
3063
+
3064
+
3065
+ # ============================================================
3066
+ # CELL 8/9 — MANUAL DV-BY-DV CORRELATED-SLOPE EXECUTION
3067
+ # ============================================================
3068
+ # Purpose:
3069
+ # Run the correlated random-slope selection procedure
3070
+ # independently for each duration-based dependent variable.
3071
+ #
3072
+ # Execution strategy:
3073
+ # Each DV is defined in a separate execution block rather
3074
+ # than inside a single loop.
3075
+ #
3076
+ # When the full script is executed, the four DV blocks run
3077
+ # sequentially. Individual DV blocks can also be executed
3078
+ # independently when rerunning or recovering an analysis.
3079
+ #
3080
+ # Advantages:
3081
+ # - Limits the consequences of a long-running model failure.
3082
+ # - Allows each DV to be restarted independently.
3083
+ # - Simplifies monitoring of CPU/RAM use.
3084
+ # - Allows results to be inspected before proceeding.
3085
+ # - Produces a separate Excel workbook for each DV.
3086
+ #
3087
+ # For each DV:
3088
+ # 1. Construct the DV-specific analysis sample.
3089
+ # 2. Remove missing/non-positive duration observations.
3090
+ # 3. Log-transform the current duration DV.
3091
+ # 4. Standardize LFP + VAD predictors within that sample.
3092
+ # 5. Fit all candidate correlated random-slope structures.
3093
+ # 6. Evaluate candidates using BIC, convergence, and
3094
+ # singularity diagnostics.
3095
+ # 7. Order selection-eligible candidates first, ranked by BIC
3096
+ # within eligibility class.
3097
+ #
3098
+ # Paper 1:
3099
+ # Source dataset:
3100
+ # Affective Provo
3101
+ #
3102
+ # Fixed effects / candidate slopes:
3103
+ # Length
3104
+ # Predictability
3105
+ # Frequency
3106
+ # Valence
3107
+ # Arousal
3108
+ # Dominance
3109
+ #
3110
+ # Random-effects framework:
3111
+ # (1 + candidate slopes | Participant_ID)
3112
+ # + (1 | Word_Unique_ID)
3113
+ #
3114
+ # Important:
3115
+ # - Candidate models within a DV use exactly the same
3116
+ # DV-specific analysis sample.
3117
+ # - Filtering and standardization are performed once per DV,
3118
+ # before candidate-model fitting.
3119
+ # - BIC is the primary ranking criterion.
3120
+ # - Convergence and singularity diagnostics must also be
3121
+ # considered when selecting the final random-slope structure.
3122
+ #
3123
+ # Output:
3124
+ # One Step 2 Excel workbook per duration DV containing:
3125
+ # - candidate ranking
3126
+ # - model-fit audit
3127
+ # - sample-size / row-count audit
3128
+ #
3129
+ # Runtime:
3130
+ # Runtime depends on sample size, candidate complexity,
3131
+ # optimizer behavior, hardware, and number of workers.
3132
+ # Previous runtime estimates should therefore not be assumed
3133
+ # for the revised pipeline.
3134
+ # ============================================================
3135
+
3136
+
3137
+ # ------------------------------------------------------------
3138
+ # 8.1 DV Registry
3139
+ # ------------------------------------------------------------
3140
+
3141
+ DV_INFO <- list(
3142
+ IA_FIRST_FIXATION_DURATION = list(serial = 1, suffix = "FFD"),
3143
+ IA_FIRST_RUN_DWELL_TIME = list(serial = 2, suffix = "GD"),
3144
+ IA_REGRESSION_PATH_DURATION = list(serial = 3, suffix = "GPT"),
3145
+ IA_DWELL_TIME = list(serial = 4, suffix = "TDT")
3146
+ )
3147
+
3148
+
3149
+
3150
+ # ============================================================
3151
+ # DV 1 — FIRST FIXATION DURATION (FFD)
3152
+ # ============================================================
3153
+
3154
+ DV_TO_RUN <- "IA_FIRST_FIXATION_DURATION"
3155
+
3156
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3157
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3158
+ }
3159
+
3160
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3161
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3162
+
3163
+ message("\n", strrep("=", 80))
3164
+ message("STARTING CORRELATED-SLOPE ANALYSIS")
3165
+ message("DV: ", DV_TO_RUN, " | Stage=", DV_SERIAL, " | Measure=", DV_SUFFIX)
3166
+ message("Dataset: Affective Provo")
3167
+ message(strrep("=", 80))
3168
+
3169
+ t0 <- proc.time()[["elapsed"]]
3170
+
3171
+ res <- select_re_structure_dynamic(
3172
+ df = df,
3173
+ dv = DV_TO_RUN,
3174
+ re_candidates = CANDIDATES,
3175
+ rank_by = "BIC",
3176
+ n_jobs = N_JOBS,
3177
+ participant_col = "Participant_ID",
3178
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3179
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3180
+ )
3181
+
3182
+ out_path <- file.path(
3183
+ OUTPUT_DATA_DIR,
3184
+ paste0(
3185
+ "Step-2-",
3186
+ DV_SERIAL, "_",
3187
+ DV_SUFFIX,
3188
+ "_CorrelatedSlopes_Affective_Provo.xlsx"
3189
+ )
3190
+ )
3191
+
3192
+ save_re_outputs_to_excel(
3193
+ excel_path = out_path,
3194
+ dv = DV_TO_RUN,
3195
+ df_results = res$df_results,
3196
+ df_audit = res$df_audit,
3197
+ rowcount_summary = res$rowcounts
3198
+ )
3199
+
3200
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3201
+
3202
+ message("\nDV-SPECIFIC SAMPLE:")
3203
+ print(res$filter_summary)
3204
+
3205
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3206
+ message("Saved to: ", out_path)
3207
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3208
+
3209
+
3210
+
3211
+ # ============================================================
3212
+ # DV 2 — FIRST-RUN DWELL TIME / GAZE DURATION (GD)
3213
+ # ============================================================
3214
+
3215
+ DV_TO_RUN <- "IA_FIRST_RUN_DWELL_TIME"
3216
+
3217
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3218
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3219
+ }
3220
+
3221
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3222
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3223
+
3224
+ message("\n", strrep("=", 80))
3225
+ message("STARTING CORRELATED-SLOPE ANALYSIS")
3226
+ message("DV: ", DV_TO_RUN, " | Stage=", DV_SERIAL, " | Measure=", DV_SUFFIX)
3227
+ message("Dataset: Affective Provo")
3228
+ message(strrep("=", 80))
3229
+
3230
+ t0 <- proc.time()[["elapsed"]]
3231
+
3232
+ res <- select_re_structure_dynamic(
3233
+ df = df,
3234
+ dv = DV_TO_RUN,
3235
+ re_candidates = CANDIDATES,
3236
+ rank_by = "BIC",
3237
+ n_jobs = N_JOBS,
3238
+ participant_col = "Participant_ID",
3239
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3240
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3241
+ )
3242
+
3243
+ out_path <- file.path(
3244
+ OUTPUT_DATA_DIR,
3245
+ paste0(
3246
+ "Step-2-",
3247
+ DV_SERIAL, "_",
3248
+ DV_SUFFIX,
3249
+ "_CorrelatedSlopes_Affective_Provo.xlsx"
3250
+ )
3251
+ )
3252
+
3253
+ save_re_outputs_to_excel(
3254
+ excel_path = out_path,
3255
+ dv = DV_TO_RUN,
3256
+ df_results = res$df_results,
3257
+ df_audit = res$df_audit,
3258
+ rowcount_summary = res$rowcounts
3259
+ )
3260
+
3261
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3262
+
3263
+ message("\nDV-SPECIFIC SAMPLE:")
3264
+ print(res$filter_summary)
3265
+
3266
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3267
+ message("Saved to: ", out_path)
3268
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3269
+
3270
+
3271
+
3272
+ # ============================================================
3273
+ # DV 3 — REGRESSION PATH DURATION / GO-PAST TIME (GPT)
3274
+ # ============================================================
3275
+
3276
+ DV_TO_RUN <- "IA_REGRESSION_PATH_DURATION"
3277
+
3278
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3279
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3280
+ }
3281
+
3282
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3283
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3284
+
3285
+ message("\n", strrep("=", 80))
3286
+ message("STARTING CORRELATED-SLOPE ANALYSIS")
3287
+ message("DV: ", DV_TO_RUN, " | Stage=", DV_SERIAL, " | Measure=", DV_SUFFIX)
3288
+ message("Dataset: Affective Provo")
3289
+ message(strrep("=", 80))
3290
+
3291
+ t0 <- proc.time()[["elapsed"]]
3292
+
3293
+ res <- select_re_structure_dynamic(
3294
+ df = df,
3295
+ dv = DV_TO_RUN,
3296
+ re_candidates = CANDIDATES,
3297
+ rank_by = "BIC",
3298
+ n_jobs = N_JOBS,
3299
+ participant_col = "Participant_ID",
3300
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3301
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3302
+ )
3303
+
3304
+ out_path <- file.path(
3305
+ OUTPUT_DATA_DIR,
3306
+ paste0(
3307
+ "Step-2-",
3308
+ DV_SERIAL, "_",
3309
+ DV_SUFFIX,
3310
+ "_CorrelatedSlopes_Affective_Provo.xlsx"
3311
+ )
3312
+ )
3313
+
3314
+ save_re_outputs_to_excel(
3315
+ excel_path = out_path,
3316
+ dv = DV_TO_RUN,
3317
+ df_results = res$df_results,
3318
+ df_audit = res$df_audit,
3319
+ rowcount_summary = res$rowcounts
3320
+ )
3321
+
3322
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3323
+
3324
+ message("\nDV-SPECIFIC SAMPLE:")
3325
+ print(res$filter_summary)
3326
+
3327
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3328
+ message("Saved to: ", out_path)
3329
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3330
+
3331
+
3332
+
3333
+ # ============================================================
3334
+ # DV 4 — TOTAL DWELL TIME / TOTAL READING TIME (TDT)
3335
+ # ============================================================
3336
+
3337
+ DV_TO_RUN <- "IA_DWELL_TIME"
3338
+
3339
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3340
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3341
+ }
3342
+
3343
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3344
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3345
+
3346
+ message("\n", strrep("=", 80))
3347
+ message("STARTING CORRELATED-SLOPE ANALYSIS")
3348
+ message("DV: ", DV_TO_RUN, " | Stage=", DV_SERIAL, " | Measure=", DV_SUFFIX)
3349
+ message("Dataset: Affective Provo")
3350
+ message(strrep("=", 80))
3351
+
3352
+ t0 <- proc.time()[["elapsed"]]
3353
+
3354
+ res <- select_re_structure_dynamic(
3355
+ df = df,
3356
+ dv = DV_TO_RUN,
3357
+ re_candidates = CANDIDATES,
3358
+ rank_by = "BIC",
3359
+ n_jobs = N_JOBS,
3360
+ participant_col = "Participant_ID",
3361
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3362
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3363
+ )
3364
+
3365
+ out_path <- file.path(
3366
+ OUTPUT_DATA_DIR,
3367
+ paste0(
3368
+ "Step-2-",
3369
+ DV_SERIAL, "_",
3370
+ DV_SUFFIX,
3371
+ "_CorrelatedSlopes_Affective_Provo.xlsx"
3372
+ )
3373
+ )
3374
+
3375
+ save_re_outputs_to_excel(
3376
+ excel_path = out_path,
3377
+ dv = DV_TO_RUN,
3378
+ df_results = res$df_results,
3379
+ df_audit = res$df_audit,
3380
+ rowcount_summary = res$rowcounts
3381
+ )
3382
+
3383
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3384
+
3385
+ message("\nDV-SPECIFIC SAMPLE:")
3386
+ print(res$filter_summary)
3387
+
3388
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3389
+ message("Saved to: ", out_path)
3390
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3391
+
3392
+
3393
+
3394
+
3395
+
3396
+ # ============================================================
3397
+ # RUNTIME LOG — END
3398
+ # ============================================================
3399
+ # Purpose:
3400
+ # Finalize the Step 2 runtime log after all requested
3401
+ # correlated random-slope analyses have completed.
3402
+ #
3403
+ # Records:
3404
+ # - Analysis completion timestamp
3405
+ # - R session information
3406
+ #
3407
+ # Cleanup:
3408
+ # - Close the message sink
3409
+ # - Close the standard-output sink
3410
+ # - Close the runtime-log file connection
3411
+ #
3412
+ # Safety:
3413
+ # Sink and connection states are checked before closing so
3414
+ # this cell can be rerun without unnecessarily attempting
3415
+ # to close inactive sinks or an already-closed connection.
3416
+ # ============================================================
3417
+
3418
+
3419
+ # ------------------------------------------------------------
3420
+ # 1. Record Analysis Completion
3421
+ # ------------------------------------------------------------
3422
+
3423
+ cat(
3424
+ paste0(
3425
+ "\n",
3426
+ strrep("=", 80), "\n",
3427
+ "STEP 2 — CORRELATED RANDOM-SLOPE ANALYSIS COMPLETED\n",
3428
+ "Dataset: Affective Provo\n",
3429
+ "Finished: ", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "\n",
3430
+ strrep("=", 80), "\n\n"
3431
+ )
3432
+ )
3433
+
3434
+
3435
+ # ------------------------------------------------------------
3436
+ # 2. Record R Session Information
3437
+ # ------------------------------------------------------------
3438
+
3439
+ cat("SESSION INFORMATION\n")
3440
+ cat(strrep("-", 80), "\n")
3441
+
3442
+ print(sessionInfo())
3443
+
3444
+ cat(
3445
+ "\n",
3446
+ strrep("=", 80), "\n",
3447
+ "END OF RUNTIME LOG\n",
3448
+ strrep("=", 80), "\n"
3449
+ )
3450
+
3451
+
3452
+ # ------------------------------------------------------------
3453
+ # 3. Flush Runtime-Log Connection
3454
+ # ------------------------------------------------------------
3455
+ # Push any buffered output to disk before sinks are closed.
3456
+ # ------------------------------------------------------------
3457
+
3458
+ if (exists("log_con") && isOpen(log_con)) {
3459
+ flush(log_con)
3460
+ }
3461
+
3462
+
3463
+ # ------------------------------------------------------------
3464
+ # 4. Close Message Sink
3465
+ # ------------------------------------------------------------
3466
+ # Message output was redirected separately using:
3467
+ # sink(log_con, type = "message")
3468
+ # ------------------------------------------------------------
3469
+
3470
+ if (sink.number(type = "message") > 0) {
3471
+ sink(type = "message")
3472
+ }
3473
+
3474
+
3475
+ # ------------------------------------------------------------
3476
+ # 5. Close Standard-Output Sink
3477
+ # ------------------------------------------------------------
3478
+ # Standard output was redirected using:
3479
+ # sink(log_con, split = TRUE)
3480
+ # ------------------------------------------------------------
3481
+
3482
+ if (sink.number(type = "output") > 0) {
3483
+ sink(type = "output")
3484
+ }
3485
+
3486
+
3487
+ # ------------------------------------------------------------
3488
+ # 6. Close Runtime-Log Connection
3489
+ # ------------------------------------------------------------
3490
+
3491
+ if (exists("log_con") && isOpen(log_con)) {
3492
+ close(log_con)
3493
+ }
3494
+
3495
+
3496
+ # ------------------------------------------------------------
3497
+ # 7. Confirm Successful Log Export
3498
+ # ------------------------------------------------------------
3499
+ # This message is intentionally emitted AFTER the sinks have
3500
+ # been closed, so it appears only in the active R console.
3501
+ # ------------------------------------------------------------
3502
+
3503
+ message(
3504
+ "Runtime log saved successfully: ",
3505
+ LOG_PATH
3506
+ )
05-Research_Program-Affective_Provo/01-Fixation_Duration_Research/01-LME_Model_Structure/01-Scripts/Step-3-Testing_Best_UncorrelatedSlopes_for_Selected_Random_Intercept.R ADDED
@@ -0,0 +1,3925 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # COPYRIGHT, LICENSING, AND SCHOLARLY CITATION
3
+ # ============================================================
4
+ # Copyright (c) 2026 Mohit Gupta
5
+ # License: MIT
6
+ # SPDX-License-Identifier: MIT
7
+ #
8
+ # This script contains original computational software
9
+ # developed by Mohit Gupta for the AffLex-Provo
10
+ # Research Program.
11
+ #
12
+ # Citation:
13
+ # Researchers using this software in published research
14
+ # are strongly requested to cite the AffLex-Provo repository:
15
+ # https://huggingface.co/datasets/mohitg2/AffLex-Provo
16
+ #
17
+ # Third-party datasets and externally sourced materials
18
+ # remain subject to their respective original licenses.
19
+ #
20
+ # See the applicable repository LICENSE file for the
21
+ # complete MIT License terms.
22
+ # ============================================================
23
+
24
+ # ============================================================
25
+ # CELL 1.1 — PACKAGE INSTALLATION AND INITIALIZATION (Affective Provo)
26
+ # ============================================================
27
+ #
28
+ #
29
+ # REQUIRED R VERSION: R version 4.5.2 (2025-10-31)
30
+ #
31
+ #
32
+ # Purpose:
33
+ # Ensure that all R packages required by the Step 3 analysis
34
+ # pipeline are installed and loaded.
35
+ #
36
+ # Required packages:
37
+ # readr → CSV import
38
+ # readxl → Excel import
39
+ # openxlsx → Excel export and formatting
40
+ # dplyr → data manipulation
41
+ # tidyr → missing-data handling
42
+ # stringr → string utilities
43
+ # purrr → functional/list operations
44
+ # lme4 → linear mixed-effects models
45
+ # optimx → additional optimizers used by lme4::allFit()
46
+ # dfoptim → additional optimizers used by lme4::allFit()
47
+ # future → parallel-processing infrastructure
48
+ # future.apply → future-based apply functions
49
+ # progressr → progress-handling utilities
50
+ # here → portable project-root paths
51
+ #
52
+ # Procedure:
53
+ # 1. Define the complete set of required packages.
54
+ # 2. Identify packages that are not currently installed.
55
+ # 3. Install only the missing packages from CRAN.
56
+ # 4. Load all required packages.
57
+ #
58
+ # Notes:
59
+ # - Existing package installations are left unchanged.
60
+ # - Packages are installed only when absent.
61
+ # - suppressPackageStartupMessages() keeps notebook output clean.
62
+ # - Package versions are recorded later by sessionInfo() in
63
+ # the runtime log.
64
+ # ============================================================
65
+
66
+
67
+ # ------------------------------------------------------------
68
+ # 1. Define Required Packages
69
+ # ------------------------------------------------------------
70
+
71
+ REQUIRED_PACKAGES <- c(
72
+ "readr",
73
+ "readxl",
74
+ "openxlsx",
75
+ "dplyr",
76
+ "tidyr",
77
+ "stringr",
78
+ "purrr",
79
+ "lme4",
80
+ "optimx",
81
+ "dfoptim",
82
+ "future",
83
+ "future.apply",
84
+ "progressr",
85
+ "here"
86
+ )
87
+
88
+
89
+ # ------------------------------------------------------------
90
+ # 2. Identify Missing Packages
91
+ # ------------------------------------------------------------
92
+
93
+ MISSING_PACKAGES <- REQUIRED_PACKAGES[
94
+ !vapply(
95
+ REQUIRED_PACKAGES,
96
+ requireNamespace,
97
+ quietly = TRUE,
98
+ FUN.VALUE = logical(1)
99
+ )
100
+ ]
101
+
102
+
103
+ # ------------------------------------------------------------
104
+ # 3. Install Missing Packages
105
+ # ------------------------------------------------------------
106
+
107
+ if (length(MISSING_PACKAGES) > 0) {
108
+
109
+ message(
110
+ "Installing missing package(s): ",
111
+ paste(MISSING_PACKAGES, collapse = ", ")
112
+ )
113
+
114
+ install.packages(
115
+ MISSING_PACKAGES,
116
+ repos = "https://cloud.r-project.org",
117
+ dependencies = TRUE
118
+ )
119
+
120
+ } else {
121
+
122
+ message("All required packages are already installed.")
123
+ }
124
+
125
+
126
+ # ------------------------------------------------------------
127
+ # 4. Load Required Packages
128
+ # ------------------------------------------------------------
129
+
130
+ suppressPackageStartupMessages({
131
+
132
+ library(readr)
133
+ library(readxl)
134
+ library(openxlsx)
135
+
136
+ library(dplyr)
137
+ library(tidyr)
138
+ library(stringr)
139
+ library(purrr)
140
+
141
+ library(lme4)
142
+ library(optimx)
143
+ library(dfoptim)
144
+
145
+ library(future)
146
+ library(future.apply)
147
+
148
+ library(progressr)
149
+
150
+ library(here)
151
+ })
152
+
153
+
154
+ # ------------------------------------------------------------
155
+ # 5. Confirm Package Initialization
156
+ # ------------------------------------------------------------
157
+
158
+ message(
159
+ "Package initialization complete: ",
160
+ length(REQUIRED_PACKAGES),
161
+ " required packages available."
162
+ )
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+ # ============================================================
174
+ # CELL 1.2 — HARD THREAD CAPS
175
+ # ============================================================
176
+ # Purpose:
177
+ # Restrict low-level numerical libraries to a single thread.
178
+ #
179
+ # Rationale:
180
+ # Mixed-effects models and allFit() may perform substantial
181
+ # numerical computation. If process-level parallelism is used
182
+ # later, unrestricted BLAS/OpenMP threading inside individual
183
+ # workers can cause:
184
+ #
185
+ # - CPU oversubscription
186
+ # - memory contention
187
+ # - reduced performance
188
+ # - computational instability
189
+ #
190
+ # Strategy:
191
+ # Restrict low-level numerical libraries to one thread.
192
+ # Any intentional parallelism should occur at the R-process
193
+ # level rather than within each numerical operation.
194
+ #
195
+ # Controlled libraries:
196
+ # - VECLIB / macOS Accelerate
197
+ # - OpenMP
198
+ # - OpenBLAS
199
+ # - Intel MKL
200
+ # - NumExpr
201
+ #
202
+ # Notes:
203
+ # - This does NOT change the statistical model.
204
+ # - This does NOT change the analysis sample.
205
+ # - This should be configured before heavy model fitting.
206
+ # ============================================================
207
+
208
+ Sys.setenv(
209
+ VECLIB_MAXIMUM_THREADS = "1",
210
+ OMP_NUM_THREADS = "1",
211
+ OPENBLAS_NUM_THREADS = "1",
212
+ MKL_NUM_THREADS = "1",
213
+ NUMEXPR_NUM_THREADS = "1"
214
+ )
215
+
216
+
217
+
218
+
219
+
220
+
221
+ # ============================================================
222
+ # CELL 1.3 — UNCORRELATED RANDOM-SLOPE CONFIGURATION
223
+ # ============================================================
224
+ # Purpose:
225
+ # Define the random-effects configuration used during Step 3,
226
+ # which evaluates candidate participant-level random slopes
227
+ # without estimating correlations among the participant
228
+ # random intercept and random slopes.
229
+ #
230
+ # Step 1 established the random-intercept structure.
231
+ #
232
+ # Step 2 evaluated correlated participant-level random slopes.
233
+ #
234
+ # Step 3 evaluates the corresponding candidate random-slope
235
+ # structures using an UNCORRELATED parameterization.
236
+ #
237
+ # Lexical and affective fixed-effect predictors are therefore
238
+ # evaluated as potential participant-level random slopes while
239
+ # covariance parameters among those participant random effects
240
+ # are omitted.
241
+ #
242
+ # ------------------------------------------------------------
243
+ # Additional Random Intercept
244
+ # ------------------------------------------------------------
245
+ # ADDITIONAL_INTERCEPT:
246
+ # Specifies the crossed random-intercept grouping factor
247
+ # retained alongside Participant_ID.
248
+ #
249
+ # USE_ADDITIONAL_INTERCEPT:
250
+ # TRUE → include the additional crossed random intercept
251
+ # FALSE → use participant grouping only
252
+ #
253
+ # With the current configuration:
254
+ #
255
+ # (1 + candidate slopes || Participant_ID)
256
+ # + (1 | Word_Unique_ID)
257
+ #
258
+ # Thus, Step 3 retains the same crossed random-intercept
259
+ # structure used in Step 2 while changing only the participant
260
+ # random-slope correlation structure.
261
+ # ------------------------------------------------------------
262
+
263
+ ADDITIONAL_INTERCEPT <- "Word_Unique_ID"
264
+ USE_ADDITIONAL_INTERCEPT <- TRUE
265
+
266
+
267
+ # ------------------------------------------------------------
268
+ # Random-Slope Correlation Structure
269
+ # ------------------------------------------------------------
270
+ # USE_UNCORRELATED_SLOPES:
271
+ #
272
+ # FALSE:
273
+ # (1 + slopes | Participant_ID)
274
+ #
275
+ # Participant intercepts and random slopes are allowed
276
+ # to correlate.
277
+ #
278
+ # TRUE:
279
+ # (1 + slopes || Participant_ID)
280
+ #
281
+ # Participant random-effect covariance parameters are
282
+ # omitted, producing the uncorrelated parameterization
283
+ # evaluated in this Step 3 analysis.
284
+ #
285
+ # This Step 3 script evaluates UNCORRELATED random slopes, so
286
+ # the setting must remain TRUE.
287
+ # ------------------------------------------------------------
288
+
289
+ USE_UNCORRELATED_SLOPES <- TRUE
290
+
291
+
292
+ # ------------------------------------------------------------
293
+ # Candidate-Slope Complexity Limit
294
+ # ------------------------------------------------------------
295
+ # MAX_SLOPES_PER_CANDIDATE controls the maximum number of
296
+ # participant-level random slopes allowed in a candidate model.
297
+ #
298
+ # Inf:
299
+ # Do not impose an artificial maximum.
300
+ #
301
+ # The same candidate-slope search space used in Step 2 is
302
+ # retained so that correlated and uncorrelated structures are
303
+ # evaluated using equivalent sets of candidate slopes.
304
+ #
305
+ # A smaller value should be used only in a separately defined
306
+ # sensitivity or stability analysis.
307
+ # ------------------------------------------------------------
308
+
309
+ MAX_SLOPES_PER_CANDIDATE <- Inf
310
+
311
+
312
+ # ------------------------------------------------------------
313
+ # Console Confirmation
314
+ # ------------------------------------------------------------
315
+
316
+ if (USE_ADDITIONAL_INTERCEPT) {
317
+ message(
318
+ "Random-intercept structure: Participant_ID + ",
319
+ ADDITIONAL_INTERCEPT
320
+ )
321
+ } else {
322
+ message("Random-intercept structure: Participant_ID only")
323
+ }
324
+
325
+ message(
326
+ "Participant random slopes: ",
327
+ if (USE_UNCORRELATED_SLOPES) "UNCORRELATED" else "CORRELATED"
328
+ )
329
+
330
+ message(
331
+ "Maximum slopes per candidate: ",
332
+ MAX_SLOPES_PER_CANDIDATE
333
+ )
334
+
335
+
336
+
337
+
338
+
339
+ # ============================================================
340
+ # CELL 1.4 — ROOT-ANCHORED PROJECT PATHS
341
+ # ============================================================
342
+ # Purpose:
343
+ # Define portable input and output paths using the 'here'
344
+ # package.
345
+ #
346
+ # Input:
347
+ # 02-Data/
348
+ # 03-Analysis_Ready/
349
+ # 03_Affective_Provo.csv
350
+ #
351
+ # Dataset:
352
+ # Affective Provo guarantees complete mandatory:
353
+ #
354
+ # Lexical predictors:
355
+ # - Word_Length
356
+ # - Response_Proportion
357
+ # - Lg10WF
358
+ #
359
+ # Affective predictors:
360
+ # - V.Mean.Y
361
+ # - A.Mean.Y
362
+ # - D.Mean.Y
363
+ #
364
+ # Important:
365
+ # Eye-tracking outcomes have NOT been used to determine
366
+ # inclusion in the exported Affective Provo dataset.
367
+ #
368
+ # DV-specific duration filtering therefore occurs later in
369
+ # this Step 3 analysis pipeline, using the same preparation
370
+ # principles as Step 2.
371
+ #
372
+ # Output:
373
+ # 05-Research_Program-Affective_Provo/
374
+ # 01-LME_Model_Structure/
375
+ # 02-Results/
376
+ #
377
+ # Steps 1, 2, and 3 intentionally use the same results
378
+ # directory. Step-specific filenames distinguish their outputs.
379
+ #
380
+ # This ensures that the correlated and uncorrelated random-
381
+ # slope analyses use the same source dataset and repository
382
+ # location while remaining distinguishable by output filename.
383
+ # ============================================================
384
+
385
+ PROJECT_ROOT <- here()
386
+
387
+ RAW_DATA_PATH <- here(
388
+ "02-Data",
389
+ "03-Analysis_Ready",
390
+ "03_Affective_Provo.csv"
391
+ )
392
+
393
+ OUTPUT_DATA_DIR <- here(
394
+ "05-Research_Program-Affective_Provo",
395
+ "01-Fixation_Duration_Research",
396
+ "01-LME_Model_Structure",
397
+ "02-Results"
398
+ )
399
+
400
+
401
+ # ------------------------------------------------------------
402
+ # Create Output Directory if Necessary
403
+ # ------------------------------------------------------------
404
+
405
+ dir.create(
406
+ OUTPUT_DATA_DIR,
407
+ recursive = TRUE,
408
+ showWarnings = FALSE
409
+ )
410
+
411
+
412
+ # ------------------------------------------------------------
413
+ # Verify Input Dataset
414
+ # ------------------------------------------------------------
415
+
416
+ stopifnot(
417
+ file.exists(RAW_DATA_PATH)
418
+ )
419
+
420
+
421
+ # ------------------------------------------------------------
422
+ # Report Resolved Project Paths
423
+ # ------------------------------------------------------------
424
+
425
+ message("PROJECT_ROOT: ", PROJECT_ROOT)
426
+ message("RAW_DATA_PATH: ", RAW_DATA_PATH)
427
+ message("OUTPUT_DATA_DIR: ", OUTPUT_DATA_DIR)
428
+
429
+
430
+
431
+
432
+
433
+
434
+
435
+
436
+
437
+ # ============================================================
438
+ # CELL 1.5 — RUNTIME LOG — START
439
+ # ============================================================
440
+ # Purpose:
441
+ # Initialize the runtime log for the Step 3 uncorrelated
442
+ # random-slope analysis.
443
+ #
444
+ # Records:
445
+ # - Analysis identity
446
+ # - Dataset identity
447
+ # - Analysis start timestamp
448
+ # - R version
449
+ #
450
+ # Output:
451
+ # Step-3_Runtime_Log_Affective_Provo_Uncorrelated_Slopes.txt
452
+ #
453
+ # Important:
454
+ # Step 2 and Step 3 use the same results directory, but
455
+ # distinct runtime-log filenames prevent the correlated and
456
+ # uncorrelated analyses from overwriting one another.
457
+ # ============================================================
458
+
459
+ LOG_PATH <- file.path(
460
+ OUTPUT_DATA_DIR,
461
+ "Step-3_Runtime_Log_Affective_Provo_Uncorrelated_Slopes.txt"
462
+ )
463
+
464
+ log_con <- file(
465
+ LOG_PATH,
466
+ open = "wt"
467
+ )
468
+
469
+ sink(log_con, split = TRUE)
470
+ sink(log_con, type = "message")
471
+
472
+ cat(
473
+ paste0(
474
+ "\n",
475
+ strrep("=", 80), "\n",
476
+ "STEP 3 — UNCORRELATED RANDOM-SLOPE ANALYSIS\n",
477
+ "Dataset: Affective Provo\n",
478
+ "Started: ", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), "\n",
479
+ "R version: ", R.version.string, "\n",
480
+ strrep("=", 80), "\n\n"
481
+ )
482
+ )
483
+
484
+
485
+
486
+
487
+
488
+
489
+
490
+
491
+
492
+
493
+ # ============================================================
494
+ # CELL 2 — SHARED HELPER FUNCTIONS
495
+ # ============================================================
496
+ # Purpose:
497
+ # Define reusable utility functions used throughout the
498
+ # uncorrelated random-slope model-selection pipeline.
499
+ #
500
+ # Includes:
501
+ # - Random-slope candidate generation
502
+ # - Runtime formatting
503
+ # - Excel sheet-name sanitization
504
+ # - Row-count auditing for fair AIC/BIC comparison
505
+ # - Structured Excel export with safe sheet replacement
506
+ #
507
+ # Design principles:
508
+ # - Functions are reusable across DVs.
509
+ # - Functions are shared by Paper 1 (Affective Provo) and
510
+ # Paper 2 (Lexical Provo).
511
+ # - Candidate generation is independent of whether slopes are
512
+ # correlated or uncorrelated; the correlation structure is
513
+ # imposed later when the lmer formula is constructed.
514
+ # - No model fitting occurs in this cell.
515
+ # - No analysis-specific row filtering occurs in this cell.
516
+ # - File-writing side effects occur only in the explicitly
517
+ # defined Excel-export function.
518
+ # ============================================================
519
+
520
+
521
+ # ------------------------------------------------------------
522
+ # 2.1 Random-Slope Candidate Generator
523
+ # ------------------------------------------------------------
524
+ # Purpose:
525
+ # Generate all candidate participant-level random-slope
526
+ # structures from a supplied set of slope variables.
527
+ #
528
+ # Behavior:
529
+ # - Always includes the random-intercept-only candidate:
530
+ #
531
+ # "1"
532
+ #
533
+ # - Generates every combination of the supplied slopes.
534
+ #
535
+ # - max_slopes can optionally restrict the maximum number
536
+ # of slopes included in any candidate structure.
537
+ #
538
+ # Example for the Affective Provo Step 3 analysis:
539
+ #
540
+ # slope_vars = c(
541
+ # "Length",
542
+ # "Predictability",
543
+ # "Frequency",
544
+ # "Valence",
545
+ # "Arousal",
546
+ # "Dominance"
547
+ # )
548
+ #
549
+ # Candidate structures include:
550
+ #
551
+ # "1"
552
+ # "1 + Length"
553
+ # "1 + Predictability"
554
+ # "1 + Frequency"
555
+ # "1 + Valence"
556
+ # ...
557
+ # "1 + Length + Predictability + Frequency + Valence + Arousal + Dominance"
558
+ #
559
+ # The generated strings contain only the random-intercept /
560
+ # random-slope portion of the participant random-effects term.
561
+ #
562
+ # The correlation structure is imposed later:
563
+ #
564
+ # Correlated:
565
+ # (1 + slopes | Participant_ID)
566
+ #
567
+ # Uncorrelated:
568
+ # (1 + slopes || Participant_ID)
569
+ #
570
+ # Step 3 uses the latter parameterization.
571
+ # ------------------------------------------------------------
572
+
573
+ generate_re_candidates <- function(slope_vars, max_slopes = Inf) {
574
+
575
+ candidates <- c("1")
576
+
577
+ if (length(slope_vars) == 0) return(candidates)
578
+
579
+ for (r in seq_along(slope_vars)) {
580
+
581
+ if (is.finite(max_slopes) && r > max_slopes) next
582
+
583
+ combos <- combn(
584
+ slope_vars,
585
+ r,
586
+ simplify = FALSE
587
+ )
588
+
589
+ candidates <- c(
590
+ candidates,
591
+ vapply(
592
+ combos,
593
+ function(x) {
594
+ paste(
595
+ "1 +",
596
+ paste(x, collapse = " + ")
597
+ )
598
+ },
599
+ character(1)
600
+ )
601
+ )
602
+ }
603
+
604
+ unique(candidates)
605
+ }
606
+
607
+
608
+ # ------------------------------------------------------------
609
+ # 2.2 Runtime Formatter
610
+ # ------------------------------------------------------------
611
+ # Purpose:
612
+ # Convert elapsed execution time in seconds into a compact
613
+ # human-readable representation.
614
+ #
615
+ # Output examples:
616
+ # 12.5 seconds → "12.5s"
617
+ # 492 seconds → "8.2m"
618
+ # 4860 seconds → "1.35h"
619
+ # ------------------------------------------------------------
620
+
621
+ fmt_secs <- function(s) {
622
+
623
+ if (is.null(s) || !is.finite(s)) return("NA")
624
+
625
+ s <- as.numeric(s)
626
+
627
+ if (s < 60) {
628
+ return(sprintf("%.1fs", s))
629
+ }
630
+
631
+ if (s < 3600) {
632
+ return(sprintf("%.1fm", s / 60))
633
+ }
634
+
635
+ sprintf("%.2fh", s / 3600)
636
+ }
637
+
638
+
639
+ # ------------------------------------------------------------
640
+ # 2.3 Excel Sheet-Name Sanitizer
641
+ # ------------------------------------------------------------
642
+ # Purpose:
643
+ # Ensure dynamically generated worksheet names comply with
644
+ # Microsoft Excel naming restrictions.
645
+ #
646
+ # Excel restrictions handled:
647
+ # - Maximum worksheet-name length = 31 characters
648
+ # - Prohibited characters:
649
+ #
650
+ # \ / * [ ] : ?
651
+ #
652
+ # This prevents worksheet-creation errors during repeated
653
+ # automated exports.
654
+ # ------------------------------------------------------------
655
+
656
+ safe_sheet_name <- function(name) {
657
+
658
+ name <- str_replace_all(
659
+ name,
660
+ "[\\\\/*\\[\\]:?]",
661
+ "_"
662
+ )
663
+
664
+ str_sub(
665
+ name,
666
+ 1,
667
+ 31
668
+ )
669
+ }
670
+
671
+
672
+ # ------------------------------------------------------------
673
+ # 2.4 Row-Count Audit for Fair Model Comparison
674
+ # ------------------------------------------------------------
675
+ # Purpose:
676
+ # Audit the analysis sample used for AIC/BIC comparison.
677
+ #
678
+ # Why this matters:
679
+ # Candidate random-slope models for the SAME DV must be
680
+ # compared on exactly the same observations. Otherwise,
681
+ # differences in AIC/BIC could reflect differences in sample
682
+ # composition rather than differences in model structure.
683
+ #
684
+ # Reports:
685
+ # original_rows
686
+ # → rows supplied to the audit function
687
+ #
688
+ # dv_nonmissing_rows
689
+ # → rows with a non-missing value for the current DV
690
+ #
691
+ # complete_case_rows_used_for_AIC_BIC
692
+ # → rows complete across the current DV and all variables
693
+ # specified in required_cols
694
+ #
695
+ # rows_dropped_for_complete_case
696
+ # → rows removed because at least one required value
697
+ # was missing
698
+ #
699
+ # pct_dropped
700
+ # → percentage of supplied rows removed by complete-case
701
+ # filtering
702
+ #
703
+ # Important:
704
+ # This helper audits MISSINGNESS only.
705
+ #
706
+ # It does NOT automatically impose DV > 0.
707
+ #
708
+ # For duration-based analyses, the positive-duration
709
+ # restriction must be applied during the analysis-data
710
+ # preparation stage before candidate models are compared.
711
+ #
712
+ # Safety:
713
+ # Required columns are validated explicitly. Missing required
714
+ # variables cause the pipeline to stop rather than being
715
+ # silently omitted from the audit.
716
+ #
717
+ # This behavior is intentionally retained from Step 2 so that
718
+ # Step 2 and Step 3 use identical sample-validation rules.
719
+ # ------------------------------------------------------------
720
+
721
+ dv_rowcount_summary <- function(
722
+ df,
723
+ dv,
724
+ required_cols,
725
+ label = ""
726
+ ) {
727
+
728
+ cols_needed <- unique(
729
+ c(
730
+ dv,
731
+ required_cols
732
+ )
733
+ )
734
+
735
+ missing_required <- setdiff(
736
+ cols_needed,
737
+ names(df)
738
+ )
739
+
740
+ if (length(missing_required) > 0) {
741
+
742
+ stop(
743
+ "Row-count audit cannot proceed. Missing required variable(s): ",
744
+ paste(
745
+ missing_required,
746
+ collapse = ", "
747
+ )
748
+ )
749
+ }
750
+
751
+
752
+ # ----------------------------------------------------------
753
+ # Source-Data Row Counts
754
+ # ----------------------------------------------------------
755
+
756
+ original_n <- nrow(df)
757
+
758
+ dv_nonmissing <- sum(
759
+ !is.na(df[[dv]])
760
+ )
761
+
762
+
763
+ # ----------------------------------------------------------
764
+ # Complete-Case Count
765
+ # ----------------------------------------------------------
766
+
767
+ complete_n <- df %>%
768
+ select(
769
+ all_of(cols_needed)
770
+ ) %>%
771
+ drop_na() %>%
772
+ nrow()
773
+
774
+
775
+ # ----------------------------------------------------------
776
+ # Removal Diagnostics
777
+ # ----------------------------------------------------------
778
+
779
+ dropped <- original_n - complete_n
780
+
781
+
782
+ # ----------------------------------------------------------
783
+ # Return Audit Record
784
+ # ----------------------------------------------------------
785
+
786
+ tibble(
787
+ label = ifelse(
788
+ nchar(label) > 0,
789
+ label,
790
+ dv
791
+ ),
792
+ dv = dv,
793
+ original_rows = original_n,
794
+ dv_nonmissing_rows = dv_nonmissing,
795
+ complete_case_rows_used_for_AIC_BIC = complete_n,
796
+ rows_dropped_for_complete_case = dropped,
797
+ pct_dropped = if (original_n > 0) {
798
+ dropped / original_n * 100
799
+ } else {
800
+ NA_real_
801
+ },
802
+ required_cols_used = paste(
803
+ required_cols,
804
+ collapse = ", "
805
+ )
806
+ )
807
+ }
808
+
809
+
810
+ # ------------------------------------------------------------
811
+ # 2.5 Structured Excel Export
812
+ # ------------------------------------------------------------
813
+ # Purpose:
814
+ # Save uncorrelated random-slope model-selection outputs to a
815
+ # structured multi-sheet Excel workbook.
816
+ #
817
+ # Sheets created for each DV:
818
+ #
819
+ # <DV>_ranking
820
+ # → candidate random-slope model ranking
821
+ #
822
+ # <DV>_audit
823
+ # → model-fitting / convergence audit information
824
+ #
825
+ # <DV>_rowcounts
826
+ # → sample-size and complete-case diagnostics
827
+ #
828
+ # Repeated-execution behavior:
829
+ # - Creates the workbook if it does not already exist.
830
+ # - Loads the existing workbook when rerunning the analysis.
831
+ # - Removes only the sheets corresponding to the current DV.
832
+ # - Recreates those sheets with the updated results.
833
+ # - Preserves any other sheets already present in the workbook.
834
+ #
835
+ # Safety:
836
+ # - Normalizes the output path.
837
+ # - Creates the parent directory when necessary.
838
+ # - Sanitizes dynamically generated worksheet names.
839
+ # - Saves with overwrite = TRUE after the workbook has been
840
+ # updated in memory.
841
+ #
842
+ # Important:
843
+ # The export mechanism itself is identical to Step 2.
844
+ # Step 3 output filenames defined later distinguish the
845
+ # uncorrelated results from the correlated Step 2 results.
846
+ # ------------------------------------------------------------
847
+
848
+ save_re_outputs_to_excel <- function(
849
+ excel_path,
850
+ dv,
851
+ df_results,
852
+ df_audit,
853
+ rowcount_summary
854
+ ) {
855
+
856
+ excel_path <- normalizePath(
857
+ excel_path,
858
+ winslash = "/",
859
+ mustWork = FALSE
860
+ )
861
+
862
+ dir.create(
863
+ dirname(excel_path),
864
+ recursive = TRUE,
865
+ showWarnings = FALSE
866
+ )
867
+
868
+
869
+ # ----------------------------------------------------------
870
+ # Construct Excel-Safe Worksheet Names
871
+ # ----------------------------------------------------------
872
+
873
+ rank_sheet <- safe_sheet_name(
874
+ paste0(dv, "_ranking")
875
+ )
876
+
877
+ audit_sheet <- safe_sheet_name(
878
+ paste0(dv, "_audit")
879
+ )
880
+
881
+ rows_sheet <- safe_sheet_name(
882
+ paste0(dv, "_rowcounts")
883
+ )
884
+
885
+
886
+ # ----------------------------------------------------------
887
+ # Create or Load Workbook
888
+ # ----------------------------------------------------------
889
+
890
+ if (file.exists(excel_path)) {
891
+
892
+ wb <- loadWorkbook(
893
+ excel_path
894
+ )
895
+
896
+ if (rank_sheet %in% names(wb)) {
897
+ removeWorksheet(
898
+ wb,
899
+ rank_sheet
900
+ )
901
+ }
902
+
903
+ if (audit_sheet %in% names(wb)) {
904
+ removeWorksheet(
905
+ wb,
906
+ audit_sheet
907
+ )
908
+ }
909
+
910
+ if (rows_sheet %in% names(wb)) {
911
+ removeWorksheet(
912
+ wb,
913
+ rows_sheet
914
+ )
915
+ }
916
+
917
+ } else {
918
+
919
+ wb <- createWorkbook()
920
+ }
921
+
922
+
923
+ # ----------------------------------------------------------
924
+ # Write Candidate Ranking
925
+ # ----------------------------------------------------------
926
+
927
+ addWorksheet(
928
+ wb,
929
+ rank_sheet
930
+ )
931
+
932
+ writeData(
933
+ wb,
934
+ rank_sheet,
935
+ df_results
936
+ )
937
+
938
+
939
+ # ----------------------------------------------------------
940
+ # Write Model-Fit Audit
941
+ # ----------------------------------------------------------
942
+
943
+ addWorksheet(
944
+ wb,
945
+ audit_sheet
946
+ )
947
+
948
+ writeData(
949
+ wb,
950
+ audit_sheet,
951
+ df_audit
952
+ )
953
+
954
+
955
+ # ----------------------------------------------------------
956
+ # Write Row-Count Audit
957
+ # ----------------------------------------------------------
958
+
959
+ addWorksheet(
960
+ wb,
961
+ rows_sheet
962
+ )
963
+
964
+ writeData(
965
+ wb,
966
+ rows_sheet,
967
+ rowcount_summary
968
+ )
969
+
970
+
971
+ # ----------------------------------------------------------
972
+ # Save Workbook
973
+ # ----------------------------------------------------------
974
+
975
+ saveWorkbook(
976
+ wb,
977
+ excel_path,
978
+ overwrite = TRUE
979
+ )
980
+
981
+
982
+ # ----------------------------------------------------------
983
+ # Confirm Export
984
+ # ----------------------------------------------------------
985
+
986
+ message(
987
+ "Saved uncorrelated random-slope results: ",
988
+ excel_path
989
+ )
990
+ }
991
+
992
+
993
+
994
+
995
+
996
+
997
+
998
+
999
+
1000
+ # ============================================================
1001
+ # CELL 3 — LOAD AND VALIDATE AFFECTIVE PROVO
1002
+ # ============================================================
1003
+ # Purpose:
1004
+ # Load the analysis-ready Affective Provo dataset and prepare
1005
+ # variable names for the uncorrelated random-slope pipeline.
1006
+ #
1007
+ # Input:
1008
+ # 03_Affective_Provo.csv
1009
+ #
1010
+ # Dataset guarantees:
1011
+ # Every observation has complete mandatory:
1012
+ #
1013
+ # Lexical predictors:
1014
+ # - Word_Length
1015
+ # - Response_Proportion
1016
+ # - Lg10WF
1017
+ #
1018
+ # Affective predictors:
1019
+ # - V.Mean.Y
1020
+ # - A.Mean.Y
1021
+ # - D.Mean.Y
1022
+ #
1023
+ # Procedure:
1024
+ # 1. Load the Affective Provo dataset.
1025
+ # 2. Preserve the loaded dataset in df_main.
1026
+ # 3. Create df as the working modeling copy.
1027
+ # 4. Rename VAD variables for model readability.
1028
+ # 5. Validate mandatory predictors.
1029
+ #
1030
+ # IMPORTANT:
1031
+ # No eye-tracking filtering occurs here.
1032
+ #
1033
+ # No DV > 0 filtering occurs here.
1034
+ #
1035
+ # No predictor standardization occurs here.
1036
+ #
1037
+ # Predictors will be standardized AFTER the DV-specific
1038
+ # analysis sample has been constructed. This ensures that
1039
+ # scaling is based on the observations actually entering
1040
+ # each duration-DV model comparison.
1041
+ #
1042
+ # Consequently, FFD, GD, GPT, and TDT may be standardized
1043
+ # using slightly different means/SDs if their eligible
1044
+ # analysis samples differ.
1045
+ #
1046
+ # This preparation procedure is intentionally identical to
1047
+ # Step 2. The distinction between Step 2 and Step 3 concerns
1048
+ # the participant-level random-slope correlation structure,
1049
+ # not data preprocessing.
1050
+ # ============================================================
1051
+
1052
+
1053
+ # ------------------------------------------------------------
1054
+ # 3.1 Load Affective Provo
1055
+ # ------------------------------------------------------------
1056
+
1057
+ df_main <- read_csv(
1058
+ RAW_DATA_PATH,
1059
+ show_col_types = FALSE
1060
+ )
1061
+
1062
+ message(
1063
+ "Affective Provo rows loaded: ",
1064
+ format(nrow(df_main), big.mark = ",")
1065
+ )
1066
+
1067
+
1068
+ # ------------------------------------------------------------
1069
+ # 3.2 Create Modeling Copy
1070
+ # ------------------------------------------------------------
1071
+ # df_main preserves the loaded analysis-ready dataset.
1072
+ # Subsequent preparation occurs on df.
1073
+ # ------------------------------------------------------------
1074
+
1075
+ df <- df_main
1076
+
1077
+
1078
+ # ------------------------------------------------------------
1079
+ # 3.3 Rename Affective Predictors
1080
+ # ------------------------------------------------------------
1081
+ # Rename the original VAD columns to concise names used in
1082
+ # subsequent model formulas:
1083
+ #
1084
+ # V.Mean.Y → Valence
1085
+ # A.Mean.Y → Arousal
1086
+ # D.Mean.Y → Dominance
1087
+ # ------------------------------------------------------------
1088
+
1089
+ rename_map <- c(
1090
+ "V.Mean.Y" = "Valence",
1091
+ "A.Mean.Y" = "Arousal",
1092
+ "D.Mean.Y" = "Dominance",
1093
+ "Word_Length" = "Length",
1094
+ "Response_Proportion" = "Predictability",
1095
+ "Lg10WF" = "Frequency"
1096
+ )
1097
+
1098
+ for (k in names(rename_map)) {
1099
+
1100
+ if (k %in% names(df)) {
1101
+
1102
+ names(df)[
1103
+ names(df) == k
1104
+ ] <- rename_map[[k]]
1105
+ }
1106
+ }
1107
+
1108
+
1109
+ # ------------------------------------------------------------
1110
+ # 3.4 Validate Mandatory LFP + VAD Predictors
1111
+ # ------------------------------------------------------------
1112
+ # Affective Provo should contain complete LFP + VAD predictors
1113
+ # by construction. Missing columns or missing values therefore
1114
+ # indicate an incorrect/incomplete input dataset and should
1115
+ # stop the analysis rather than being silently filtered.
1116
+ # ------------------------------------------------------------
1117
+
1118
+ REQUIRED_PREDICTORS <- c(
1119
+ "Length",
1120
+ "Predictability",
1121
+ "Frequency",
1122
+ "Valence",
1123
+ "Arousal",
1124
+ "Dominance"
1125
+ )
1126
+
1127
+ missing_columns <- setdiff(
1128
+ REQUIRED_PREDICTORS,
1129
+ names(df)
1130
+ )
1131
+
1132
+ if (length(missing_columns) > 0) {
1133
+
1134
+ stop(
1135
+ "Missing mandatory Affective Provo predictor(s): ",
1136
+ paste(
1137
+ missing_columns,
1138
+ collapse = ", "
1139
+ )
1140
+ )
1141
+ }
1142
+
1143
+ if (anyNA(df[REQUIRED_PREDICTORS])) {
1144
+
1145
+ stop(
1146
+ "Affective Provo contains missing values in one or more ",
1147
+ "mandatory LFP + VAD predictors."
1148
+ )
1149
+ }
1150
+
1151
+
1152
+ # ------------------------------------------------------------
1153
+ # 3.5 Confirm Dataset Readiness
1154
+ # ------------------------------------------------------------
1155
+
1156
+ message(
1157
+ "Mandatory LFP + VAD predictors: complete."
1158
+ )
1159
+
1160
+ message(
1161
+ "Predictors remain UNSCALED at this stage."
1162
+ )
1163
+
1164
+ message(
1165
+ "DV-specific filtering and standardization will occur later."
1166
+ )
1167
+
1168
+
1169
+
1170
+
1171
+
1172
+
1173
+
1174
+
1175
+ # ============================================================
1176
+ # CELL 4 — DVs, UNCORRELATED-SLOPE CANDIDATES, AND RESOURCE PLAN
1177
+ # ============================================================
1178
+ # Purpose:
1179
+ # Define the duration-based dependent variables, generate all
1180
+ # candidate participant-level uncorrelated random-slope
1181
+ # structures, and determine a conservative computational
1182
+ # execution plan.
1183
+ #
1184
+ # Paper 1 candidate slopes:
1185
+ #
1186
+ # Lexical predictors:
1187
+ # - Length
1188
+ # - Predictability
1189
+ # - Frequency
1190
+ #
1191
+ # Affective predictors:
1192
+ # - Valence
1193
+ # - Arousal
1194
+ # - Dominance
1195
+ #
1196
+ # Random-slope framework:
1197
+ #
1198
+ # Candidate slopes are added at the Participant_ID level:
1199
+ #
1200
+ # (1 + candidate_slopes || Participant_ID)
1201
+ #
1202
+ # Because USE_UNCORRELATED_SLOPES = TRUE in Cell 1.3,
1203
+ # participant intercepts and random slopes are modeled
1204
+ # without correlation parameters.
1205
+ #
1206
+ # The additional crossed random intercept configured in
1207
+ # Cell 1.3 is retained separately:
1208
+ #
1209
+ # + (1 | Word_Unique_ID)
1210
+ #
1211
+ # Candidate generation:
1212
+ # With 6 possible slopes and no complexity cap:
1213
+ #
1214
+ # 2^6 = 64 candidate structures
1215
+ #
1216
+ # including the participant random-intercept-only candidate.
1217
+ #
1218
+ # Computational planning:
1219
+ # - Detect available logical CPUs.
1220
+ # - Estimate available system RAM.
1221
+ # - Reserve CPU and RAM headroom for system stability.
1222
+ # - Limit process-level workers according to:
1223
+ # TASKS_PER_DV
1224
+ # CPU_BUDGET
1225
+ # RAM_BUDGET_WORKERS
1226
+ # - Restrict low-level numerical threading to prevent
1227
+ # oversubscription.
1228
+ #
1229
+ # Important:
1230
+ # - This cell defines candidate structures only.
1231
+ # - No model fitting occurs here.
1232
+ # - No DV-specific filtering occurs here.
1233
+ # - No predictor standardization occurs here.
1234
+ # - Standardization will occur after construction of each
1235
+ # DV-specific analysis sample.
1236
+ #
1237
+ # The candidate slope combinations are intentionally identical
1238
+ # to Step 2. The difference is that Step 3 estimates these
1239
+ # candidate slopes without participant intercept-slope or
1240
+ # slope-slope correlation parameters.
1241
+ # ============================================================
1242
+
1243
+
1244
+ # ------------------------------------------------------------
1245
+ # 4.1 Define Duration-Based Dependent Variables
1246
+ # ------------------------------------------------------------
1247
+
1248
+ DVS <- c(
1249
+ "IA_FIRST_FIXATION_DURATION", # Stage 1: FFD
1250
+ "IA_FIRST_RUN_DWELL_TIME", # Stage 2: GD
1251
+ "IA_REGRESSION_PATH_DURATION", # Stage 3: GPT
1252
+ "IA_DWELL_TIME" # Stage 4: TDT
1253
+ )
1254
+
1255
+
1256
+ # ------------------------------------------------------------
1257
+ # 4.2 Define Candidate Participant-Level Random Slopes
1258
+ # ------------------------------------------------------------
1259
+ # Paper 1 evaluates whether lexical and/or affective predictor
1260
+ # effects vary across participants.
1261
+ #
1262
+ # Step 3 uses the same candidate slope variables as Step 2.
1263
+ # The distinction is the uncorrelated random-effects
1264
+ # parameterization configured in Cell 1.3.
1265
+ # ------------------------------------------------------------
1266
+
1267
+ SLOPES <- c(
1268
+ "Length",
1269
+ "Predictability",
1270
+ "Frequency",
1271
+ "Valence",
1272
+ "Arousal",
1273
+ "Dominance"
1274
+ )
1275
+
1276
+
1277
+ # Validate candidate-slope variables before generating models
1278
+
1279
+ missing_slopes <- setdiff(
1280
+ SLOPES,
1281
+ names(df)
1282
+ )
1283
+
1284
+ if (length(missing_slopes) > 0) {
1285
+
1286
+ stop(
1287
+ "Missing candidate random-slope variable(s): ",
1288
+ paste(
1289
+ missing_slopes,
1290
+ collapse = ", "
1291
+ )
1292
+ )
1293
+ }
1294
+
1295
+
1296
+ # ------------------------------------------------------------
1297
+ # 4.3 Generate Candidate Random-Slope Structures
1298
+ # ------------------------------------------------------------
1299
+
1300
+ CANDIDATES <- generate_re_candidates(
1301
+ SLOPES,
1302
+ max_slopes = MAX_SLOPES_PER_CANDIDATE
1303
+ )
1304
+
1305
+ NUM_MODELS <- length(CANDIDATES)
1306
+ NUM_DVS <- length(DVS)
1307
+
1308
+ # Full pipeline = all four DVs combined
1309
+
1310
+ TOTAL_PIPELINE_MODELS <- NUM_DVS * NUM_MODELS
1311
+
1312
+ # Each DV is executed manually, one at a time
1313
+
1314
+ TASKS_PER_DV <- NUM_MODELS
1315
+
1316
+
1317
+ message(
1318
+ "Candidate slope variables : ",
1319
+ length(SLOPES)
1320
+ )
1321
+
1322
+ message(
1323
+ "Candidate structures / DV : ",
1324
+ NUM_MODELS
1325
+ )
1326
+
1327
+ message(
1328
+ "Duration DVs : ",
1329
+ NUM_DVS
1330
+ )
1331
+
1332
+ message(
1333
+ "Full pipeline models : ",
1334
+ TOTAL_PIPELINE_MODELS
1335
+ )
1336
+
1337
+ message(
1338
+ "Tasks per manual DV run : ",
1339
+ TASKS_PER_DV
1340
+ )
1341
+
1342
+
1343
+ # ------------------------------------------------------------
1344
+ # 4.4 System RAM Detection Helper
1345
+ # ------------------------------------------------------------
1346
+ # Detect total physical RAM in GB.
1347
+ #
1348
+ # Supported:
1349
+ # - macOS
1350
+ # - Linux
1351
+ #
1352
+ # Returns NA if RAM detection fails, in which case a conservative
1353
+ # fallback worker limit is used below.
1354
+ # ------------------------------------------------------------
1355
+
1356
+ get_total_ram_gb <- function() {
1357
+
1358
+ out <- NA_real_
1359
+ os <- Sys.info()[["sysname"]]
1360
+
1361
+ suppressWarnings({
1362
+
1363
+ if (os == "Darwin") {
1364
+
1365
+ mem <- as.numeric(
1366
+ system(
1367
+ "sysctl -n hw.memsize",
1368
+ intern = TRUE
1369
+ )
1370
+ )
1371
+
1372
+ if (is.finite(mem)) {
1373
+ out <- mem / (1024^3)
1374
+ }
1375
+
1376
+ } else if (os == "Linux") {
1377
+
1378
+ memline <- system(
1379
+ "grep MemTotal /proc/meminfo",
1380
+ intern = TRUE
1381
+ )
1382
+
1383
+ memkb <- as.numeric(
1384
+ str_extract(
1385
+ memline,
1386
+ "\\d+"
1387
+ )
1388
+ )
1389
+
1390
+ if (is.finite(memkb)) {
1391
+ out <- memkb / (1024^2)
1392
+ }
1393
+ }
1394
+ })
1395
+
1396
+ if (length(out) == 0) {
1397
+ out <- NA_real_
1398
+ }
1399
+
1400
+ out
1401
+ }
1402
+
1403
+
1404
+ # ------------------------------------------------------------
1405
+ # 4.5 Initialize Hardware and Resource Assumptions
1406
+ # ------------------------------------------------------------
1407
+
1408
+ TOTAL_RAM_GB <- get_total_ram_gb()
1409
+
1410
+
1411
+ # Approximate memory allowance per concurrent lmer task.
1412
+ # This is a planning heuristic rather than a measured guarantee.
1413
+
1414
+ EST_RAM_PER_WORKER_GB <- 2.5
1415
+
1416
+
1417
+ # Reserve RAM for the operating system and other processes.
1418
+
1419
+ RAM_HEADROOM_GB <- NA_real_
1420
+
1421
+
1422
+ # Conservative fallback if RAM detection fails.
1423
+
1424
+ RAM_BUDGET_WORKERS <- 1
1425
+
1426
+
1427
+ # Detect logical CPUs
1428
+
1429
+ TOTAL_CPUS <- parallel::detectCores(
1430
+ logical = TRUE
1431
+ )
1432
+
1433
+ if (is.na(TOTAL_CPUS)) {
1434
+ TOTAL_CPUS <- 1
1435
+ }
1436
+
1437
+
1438
+ # Reserve CPU capacity for the operating system.
1439
+
1440
+ CPU_RESERVE <- if (TOTAL_CPUS >= 8) {
1441
+ 2
1442
+ } else {
1443
+ 1
1444
+ }
1445
+
1446
+ CPU_BUDGET <- max(
1447
+ 1,
1448
+ TOTAL_CPUS - CPU_RESERVE
1449
+ )
1450
+
1451
+
1452
+ # ------------------------------------------------------------
1453
+ # 4.6 Determine RAM-Constrained Worker Budget
1454
+ # ------------------------------------------------------------
1455
+
1456
+ if (is.na(TOTAL_RAM_GB)) {
1457
+
1458
+ # Conservative fallback when physical RAM cannot be detected.
1459
+
1460
+ RAM_BUDGET_WORKERS <- max(
1461
+ 1,
1462
+ min(
1463
+ 4,
1464
+ CPU_BUDGET
1465
+ )
1466
+ )
1467
+
1468
+ RAM_HEADROOM_GB <- NA_real_
1469
+
1470
+ } else {
1471
+
1472
+ # Reserve at least 20% of total RAM, with a minimum of 1 GB.
1473
+
1474
+ RAM_HEADROOM_GB <- max(
1475
+ 1.0,
1476
+ TOTAL_RAM_GB * 0.20
1477
+ )
1478
+
1479
+ usable_gb <- max(
1480
+ 1.0,
1481
+ TOTAL_RAM_GB - RAM_HEADROOM_GB
1482
+ )
1483
+
1484
+ RAM_BUDGET_WORKERS <- max(
1485
+ 1,
1486
+ floor(
1487
+ usable_gb / EST_RAM_PER_WORKER_GB
1488
+ )
1489
+ )
1490
+ }
1491
+
1492
+
1493
+ # ------------------------------------------------------------
1494
+ # 4.7 Determine Final Process-Level Worker Count
1495
+ # ------------------------------------------------------------
1496
+ # Worker count cannot exceed:
1497
+ #
1498
+ # 1. Number of candidate models in the current DV run
1499
+ # 2. Available CPU budget
1500
+ # 3. Estimated RAM budget
1501
+ #
1502
+ # The current analysis executes one DV at a time, so the
1503
+ # relevant task count is TASKS_PER_DV rather than the total
1504
+ # number of models across all four DVs.
1505
+ # ------------------------------------------------------------
1506
+
1507
+ N_JOBS <- max(
1508
+ 1,
1509
+ min(
1510
+ TASKS_PER_DV,
1511
+ CPU_BUDGET,
1512
+ RAM_BUDGET_WORKERS
1513
+ )
1514
+ )
1515
+
1516
+
1517
+ # ------------------------------------------------------------
1518
+ # 4.8 Configure Low-Level Numerical Threads
1519
+ # ------------------------------------------------------------
1520
+ # Low-level numerical libraries remain restricted to one
1521
+ # thread regardless of the number of R-process workers.
1522
+ #
1523
+ # This preserves the hard thread-cap policy established in
1524
+ # Cell 1.2 and prevents nested numerical threading from
1525
+ # producing CPU oversubscription.
1526
+ #
1527
+ # Intentional parallelism therefore occurs only through the
1528
+ # process-level future/multisession workers.
1529
+ # ------------------------------------------------------------
1530
+
1531
+ BLAS_THREADS <- 1
1532
+
1533
+
1534
+ Sys.setenv(
1535
+ OMP_NUM_THREADS = "1",
1536
+ OPENBLAS_NUM_THREADS = "1",
1537
+ MKL_NUM_THREADS = "1",
1538
+ VECLIB_MAXIMUM_THREADS = "1",
1539
+ NUMEXPR_NUM_THREADS = "1"
1540
+ )
1541
+
1542
+
1543
+ # ------------------------------------------------------------
1544
+ # 4.9 Resource-Plan Reporting
1545
+ # ------------------------------------------------------------
1546
+
1547
+ fmt_num <- function(x, nd = 1) {
1548
+
1549
+ ifelse(
1550
+ is.na(x),
1551
+ "NA",
1552
+ sprintf(
1553
+ paste0(
1554
+ "%.",
1555
+ nd,
1556
+ "f"
1557
+ ),
1558
+ x
1559
+ )
1560
+ )
1561
+ }
1562
+
1563
+
1564
+ est_peak_ram <- if (is.na(TOTAL_RAM_GB)) {
1565
+
1566
+ NA_real_
1567
+
1568
+ } else {
1569
+
1570
+ N_JOBS * EST_RAM_PER_WORKER_GB
1571
+ }
1572
+
1573
+
1574
+ message(
1575
+ "\n",
1576
+ strrep("=", 72)
1577
+ )
1578
+
1579
+ message(
1580
+ "UNCORRELATED RANDOM-SLOPE RESOURCE PLAN — AFFECTIVE PROVO"
1581
+ )
1582
+
1583
+ message(
1584
+ strrep("=", 72)
1585
+ )
1586
+
1587
+
1588
+ message(
1589
+ "Full pipeline : ",
1590
+ TOTAL_PIPELINE_MODELS,
1591
+ " models (",
1592
+ NUM_DVS,
1593
+ " DVs × ",
1594
+ NUM_MODELS,
1595
+ " candidates)"
1596
+ )
1597
+
1598
+
1599
+ message(
1600
+ "Current DV run : ",
1601
+ TASKS_PER_DV,
1602
+ " candidate models"
1603
+ )
1604
+
1605
+
1606
+ message(
1607
+ "Slope variables : ",
1608
+ length(SLOPES)
1609
+ )
1610
+
1611
+ message(
1612
+ "CPUs detected : ",
1613
+ TOTAL_CPUS
1614
+ )
1615
+
1616
+ message(
1617
+ "CPU reserve : ",
1618
+ CPU_RESERVE,
1619
+ " → CPU budget=",
1620
+ CPU_BUDGET
1621
+ )
1622
+
1623
+ message(
1624
+ "RAM detected GB : ",
1625
+ fmt_num(TOTAL_RAM_GB)
1626
+ )
1627
+
1628
+ message(
1629
+ "RAM headroom GB : ",
1630
+ fmt_num(RAM_HEADROOM_GB)
1631
+ )
1632
+
1633
+ message(
1634
+ "RAM/worker GB : ",
1635
+ sprintf(
1636
+ "%.1f",
1637
+ EST_RAM_PER_WORKER_GB
1638
+ ),
1639
+ " → RAM-limited workers=",
1640
+ RAM_BUDGET_WORKERS
1641
+ )
1642
+
1643
+
1644
+ message(
1645
+ strrep("-", 72)
1646
+ )
1647
+
1648
+ message(
1649
+ "N_JOBS (workers) : ",
1650
+ N_JOBS
1651
+ )
1652
+
1653
+ message(
1654
+ "BLAS threads : ",
1655
+ BLAS_THREADS,
1656
+ " per worker"
1657
+ )
1658
+
1659
+ message(
1660
+ "Est. peak RAM GB : ",
1661
+ fmt_num(est_peak_ram)
1662
+ )
1663
+
1664
+ message(
1665
+ strrep("=", 72),
1666
+ "\n"
1667
+ )
1668
+
1669
+
1670
+
1671
+
1672
+
1673
+
1674
+
1675
+
1676
+
1677
+ # ============================================================
1678
+ # CELL 5 — HIGH-RELIABILITY UNCORRELATED RANDOM-SLOPE
1679
+ # MODEL FITTING WORKER
1680
+ # ============================================================
1681
+ # Purpose:
1682
+ # Fit one candidate participant-level uncorrelated random-
1683
+ # slope structure for a single duration DV using a tiered
1684
+ # optimization strategy.
1685
+ #
1686
+ # Inputs:
1687
+ # dv
1688
+ # → current duration dependent variable
1689
+ #
1690
+ # fixed_formula
1691
+ # → fixed-effects specification held constant across all
1692
+ # candidate random-slope structures for the current DV
1693
+ #
1694
+ # model_df
1695
+ # → DV-specific analysis dataset prepared before this
1696
+ # function is called
1697
+ #
1698
+ # re_terms
1699
+ # → candidate participant random-effects specification,
1700
+ # e.g.:
1701
+ #
1702
+ # "1"
1703
+ # "1 + Length"
1704
+ # "1 + Length + Frequency"
1705
+ #
1706
+ # groups_col
1707
+ # → grouping factor receiving the candidate random slopes
1708
+ # (normally Participant_ID)
1709
+ #
1710
+ # Random-effects framework:
1711
+ #
1712
+ # Step 3 uses UNCORRELATED participant-level random slopes:
1713
+ #
1714
+ # (1 + candidate_slopes || Participant_ID)
1715
+ #
1716
+ # This removes participant intercept-slope and slope-slope
1717
+ # correlation parameters from the candidate structures.
1718
+ #
1719
+ # The optional crossed random intercept is retained:
1720
+ #
1721
+ # + (1 | Word_Unique_ID)
1722
+ #
1723
+ # USE_UNCORRELATED_SLOPES is configured globally in Cell 1.3
1724
+ # and must remain TRUE for this Step 3 analysis.
1725
+ #
1726
+ # Reliability strategy:
1727
+ # 1. Construct the complete mixed-effects formula.
1728
+ # 2. Fit the candidate using high-precision bobyqa.
1729
+ # 3. Rewrite the stored model call so allFit() does not depend
1730
+ # on temporary local symbols created inside this function.
1731
+ # 4. Evaluate the actual lme4 convergence messages and the
1732
+ # numerical optimizer convergence code separately.
1733
+ # 5. Treat optimizer convergence code 0 as SUCCESS.
1734
+ # 6. Retain a clean bobyqa fit immediately.
1735
+ # 7. Run allFit() only when bobyqa has an actual convergence
1736
+ # problem.
1737
+ # 8. If allFit() produces one or more warning-free solutions,
1738
+ # retain the valid solution with the highest log-likelihood.
1739
+ # 9. If allFit() cannot rescue the model, retain the original
1740
+ # bobyqa fit and preserve its original convergence problem.
1741
+ # 10. Re-evaluate convergence diagnostics for the retained fit.
1742
+ # 11. Record convergence, singularity, likelihood criteria,
1743
+ # observation count, runtime, and diagnostic messages.
1744
+ #
1745
+ # Estimation:
1746
+ # REML = TRUE in the present Step 3 pipeline.
1747
+ #
1748
+ # REML-based information-criterion comparisons are used here
1749
+ # because candidate models for a given DV:
1750
+ #
1751
+ # - have identical fixed-effects specifications
1752
+ # - use identical observations
1753
+ # - differ only in random-effects structure
1754
+ #
1755
+ # REML-based AIC/BIC should not be used to compare models
1756
+ # having different fixed-effects specifications.
1757
+ #
1758
+ # allFit() robustness:
1759
+ # allFit() refits the original merMod object by updating its
1760
+ # stored model call.
1761
+ #
1762
+ # A model fitted inside a helper function can otherwise retain
1763
+ # references in its call to temporary local symbols such as:
1764
+ #
1765
+ # full_formula
1766
+ # model_df
1767
+ # reml
1768
+ #
1769
+ # Those symbols may no longer be resolvable when allFit()
1770
+ # performs an update/refit.
1771
+ #
1772
+ # Therefore, immediately after the primary lmer() fit, this
1773
+ # function rewrites the stored call so that:
1774
+ #
1775
+ # formula → the actual mixed-effects formula expression
1776
+ # data → the actual prepared model data
1777
+ # REML → literal TRUE/FALSE
1778
+ # control → the complete literal lmerControl() call
1779
+ #
1780
+ # The resulting merMod object is self-contained for the
1781
+ # allFit() rescue operation.
1782
+ #
1783
+ # Important:
1784
+ # - Optimizer convergence code 0 means successful
1785
+ # optimization and must NOT be treated as a warning.
1786
+ #
1787
+ # - allFit() is used as a rescue/robustness procedure rather
1788
+ # than automatically refitting every clean bobyqa model.
1789
+ #
1790
+ # - maxfun = 1e6 is used for the primary bobyqa fit.
1791
+ #
1792
+ # - This function does NOT construct the analysis sample.
1793
+ # - This function does NOT remove missing observations.
1794
+ # - This function does NOT apply DV > 0 filtering.
1795
+ # - This function does NOT log-transform the DV.
1796
+ # - This function does NOT standardize predictors.
1797
+ #
1798
+ # Those operations occur before model_df is supplied.
1799
+ #
1800
+ # Output:
1801
+ # A structured list containing:
1802
+ #
1803
+ # winner
1804
+ # → statistics from the retained model fit
1805
+ #
1806
+ # audit
1807
+ # → model-fit diagnostic record
1808
+ #
1809
+ # full_formula
1810
+ # → complete lmer formula used
1811
+ # ============================================================
1812
+
1813
+
1814
+ fit_single_candidate_tiered <- function(
1815
+ dv,
1816
+ fixed_formula,
1817
+ model_df,
1818
+ re_terms,
1819
+ groups_col,
1820
+ use_additional_intercept = FALSE,
1821
+ additional_intercept_col = NULL,
1822
+ reml = TRUE
1823
+ ) {
1824
+
1825
+
1826
+ # ----------------------------------------------------------
1827
+ # 5.1 Construct Full Mixed-Effects Formula
1828
+ # ----------------------------------------------------------
1829
+
1830
+ bar <- if (
1831
+ isTRUE(USE_UNCORRELATED_SLOPES)
1832
+ ) {
1833
+ "||"
1834
+ } else {
1835
+ "|"
1836
+ }
1837
+
1838
+
1839
+ rand_part <- paste0(
1840
+ "(",
1841
+ re_terms,
1842
+ " ",
1843
+ bar,
1844
+ " ",
1845
+ groups_col,
1846
+ ")"
1847
+ )
1848
+
1849
+
1850
+ rand_other <- if (
1851
+ use_additional_intercept &&
1852
+ !is.null(additional_intercept_col)
1853
+ ) {
1854
+
1855
+ paste0(
1856
+ " + (1 | ",
1857
+ additional_intercept_col,
1858
+ ")"
1859
+ )
1860
+
1861
+ } else {
1862
+
1863
+ ""
1864
+ }
1865
+
1866
+
1867
+ full_formula <- as.formula(
1868
+ paste(
1869
+ deparse(fixed_formula),
1870
+ "+",
1871
+ rand_part,
1872
+ rand_other
1873
+ )
1874
+ )
1875
+
1876
+
1877
+ # ----------------------------------------------------------
1878
+ # 5.2 Primary Model-Fitting Wrapper
1879
+ # ----------------------------------------------------------
1880
+
1881
+ run_fit <- function() {
1882
+
1883
+ suppressWarnings(
1884
+ lmer(
1885
+ formula = full_formula,
1886
+ data = model_df,
1887
+ REML = reml,
1888
+ control = lmerControl(
1889
+ optimizer = "bobyqa",
1890
+ optCtrl = list(
1891
+ maxfun = 1e6
1892
+ ),
1893
+ calc.derivs = TRUE,
1894
+ check.conv.grad = .makeCC(
1895
+ "warning",
1896
+ tol = 2e-3
1897
+ ),
1898
+ check.conv.singular = .makeCC(
1899
+ "message",
1900
+ tol = 1e-5
1901
+ ),
1902
+ check.nobs.vs.nlev = "ignore",
1903
+ check.nobs.vs.nRE = "ignore"
1904
+ )
1905
+ )
1906
+ )
1907
+ }
1908
+
1909
+
1910
+ # ----------------------------------------------------------
1911
+ # 5.3 Start Runtime Tracking
1912
+ # ----------------------------------------------------------
1913
+
1914
+ t0 <- proc.time()[["elapsed"]]
1915
+
1916
+
1917
+ # ----------------------------------------------------------
1918
+ # 5.4 Primary High-Precision bobyqa Fit
1919
+ # ----------------------------------------------------------
1920
+
1921
+ primary_res <- try(
1922
+ run_fit(),
1923
+ silent = TRUE
1924
+ )
1925
+
1926
+
1927
+ # ----------------------------------------------------------
1928
+ # 5.5 Determine Whether Primary Model Initialized
1929
+ # ----------------------------------------------------------
1930
+
1931
+ primary_initialized <- (
1932
+ !inherits(primary_res, "try-error") &&
1933
+ inherits(primary_res, "merMod")
1934
+ )
1935
+
1936
+
1937
+ # ----------------------------------------------------------
1938
+ # 5.6 Handle Initial-Fit Failure
1939
+ # ----------------------------------------------------------
1940
+ # allFit() requires an initialized merMod object.
1941
+ #
1942
+ # Therefore, if bobyqa fails before model initialization,
1943
+ # there is no fitted model available for allFit() to rescue.
1944
+ #
1945
+ # The failed candidate is retained explicitly in the audit
1946
+ # output so that catastrophic fitting failures remain visible
1947
+ # in the exported model-fit diagnostics.
1948
+ #
1949
+ # Because AIC and BIC are NA for a failed candidate, it will
1950
+ # not enter the successful-candidate ranking in Cell 6/7.
1951
+ # ----------------------------------------------------------
1952
+
1953
+ if (!primary_initialized) {
1954
+
1955
+ failed_stats <- list(
1956
+
1957
+ name = paste0(
1958
+ "RE=",
1959
+ re_terms
1960
+ ),
1961
+
1962
+ re_formula =
1963
+ re_terms,
1964
+
1965
+ optimizer =
1966
+ "FAILED",
1967
+
1968
+ selected_via =
1969
+ "FAILED",
1970
+
1971
+ converged =
1972
+ FALSE,
1973
+
1974
+ singular =
1975
+ NA,
1976
+
1977
+ aic =
1978
+ NA_real_,
1979
+
1980
+ bic =
1981
+ NA_real_,
1982
+
1983
+ llf =
1984
+ NA_real_,
1985
+
1986
+ nobs =
1987
+ nrow(model_df),
1988
+
1989
+ time_s =
1990
+ proc.time()[["elapsed"]] - t0,
1991
+
1992
+ status_msg =
1993
+ "FAILED",
1994
+
1995
+ warnings = paste(
1996
+ "Model failed during initial bobyqa fitting;",
1997
+ "allFit requires an initialized merMod model and",
1998
+ "could not provide a fallback.",
1999
+ as.character(primary_res)
2000
+ )
2001
+ )
2002
+
2003
+
2004
+ return(
2005
+ list(
2006
+
2007
+ winner =
2008
+ failed_stats,
2009
+
2010
+ audit =
2011
+ list(
2012
+ failed_stats
2013
+ ),
2014
+
2015
+ full_formula =
2016
+ full_formula
2017
+ )
2018
+ )
2019
+ }
2020
+
2021
+
2022
+ # ----------------------------------------------------------
2023
+ # 5.7 Make Stored Model Call Self-Contained for allFit()
2024
+ # ----------------------------------------------------------
2025
+
2026
+ self_contained_call <- primary_res@call
2027
+
2028
+
2029
+ self_contained_call$formula <-
2030
+ substitute(
2031
+ FORMULA_VALUE,
2032
+ list(
2033
+ FORMULA_VALUE = full_formula
2034
+ )
2035
+ )
2036
+
2037
+
2038
+ self_contained_call$data <-
2039
+ substitute(
2040
+ DATA_VALUE,
2041
+ list(
2042
+ DATA_VALUE = model_df
2043
+ )
2044
+ )
2045
+
2046
+
2047
+ self_contained_call$REML <-
2048
+ isTRUE(reml)
2049
+
2050
+
2051
+ self_contained_call$control <- quote(
2052
+ lmerControl(
2053
+ optimizer = "bobyqa",
2054
+ optCtrl = list(
2055
+ maxfun = 1e6
2056
+ ),
2057
+ calc.derivs = TRUE,
2058
+ check.conv.grad = .makeCC(
2059
+ "warning",
2060
+ tol = 2e-3
2061
+ ),
2062
+ check.conv.singular = .makeCC(
2063
+ "message",
2064
+ tol = 1e-5
2065
+ ),
2066
+ check.nobs.vs.nlev = "ignore",
2067
+ check.nobs.vs.nRE = "ignore"
2068
+ )
2069
+ )
2070
+
2071
+
2072
+ primary_res@call <-
2073
+ self_contained_call
2074
+
2075
+
2076
+ # ----------------------------------------------------------
2077
+ # 5.8 Evaluate Initial bobyqa Convergence
2078
+ # ----------------------------------------------------------
2079
+
2080
+ primary_msgs_lme4 <-
2081
+ primary_res@optinfo$conv$lme4$messages
2082
+
2083
+
2084
+ primary_opt_code <-
2085
+ primary_res@optinfo$conv$opt
2086
+
2087
+
2088
+ primary_lme4_msgs <- if (
2089
+ !is.null(primary_msgs_lme4)
2090
+ ) {
2091
+
2092
+ as.character(
2093
+ unlist(
2094
+ primary_msgs_lme4
2095
+ )
2096
+ )
2097
+
2098
+ } else {
2099
+
2100
+ character(0)
2101
+ }
2102
+
2103
+
2104
+ primary_opt_failed <- FALSE
2105
+
2106
+
2107
+ if (
2108
+ !is.null(primary_opt_code) &&
2109
+ length(primary_opt_code) > 0
2110
+ ) {
2111
+
2112
+ primary_opt_code_num <- suppressWarnings(
2113
+ as.numeric(
2114
+ unlist(
2115
+ primary_opt_code
2116
+ )
2117
+ )
2118
+ )
2119
+
2120
+
2121
+ primary_opt_failed <- any(
2122
+ is.na(primary_opt_code_num) |
2123
+ primary_opt_code_num != 0
2124
+ )
2125
+ }
2126
+
2127
+
2128
+ primary_is_good <- (
2129
+ length(primary_lme4_msgs) == 0 &&
2130
+ !primary_opt_failed
2131
+ )
2132
+
2133
+
2134
+ # ----------------------------------------------------------
2135
+ # 5.9 Retain Clean bobyqa Fit or Run allFit() Rescue
2136
+ # ----------------------------------------------------------
2137
+
2138
+ if (primary_is_good) {
2139
+
2140
+ res <- primary_res
2141
+
2142
+ selected_via <-
2143
+ "bobyqa"
2144
+
2145
+ retained_warning <-
2146
+ NA_character_
2147
+
2148
+
2149
+ } else {
2150
+
2151
+
2152
+ # --------------------------------------------------------
2153
+ # Preserve Original bobyqa Convergence Diagnostics
2154
+ # --------------------------------------------------------
2155
+
2156
+ primary_diagnostic_msgs <-
2157
+ primary_lme4_msgs
2158
+
2159
+
2160
+ if (primary_opt_failed) {
2161
+
2162
+ primary_diagnostic_msgs <- c(
2163
+ primary_diagnostic_msgs,
2164
+ paste0(
2165
+ "optimizer convergence code: ",
2166
+ paste(
2167
+ unlist(
2168
+ primary_opt_code
2169
+ ),
2170
+ collapse = ", "
2171
+ )
2172
+ )
2173
+ )
2174
+ }
2175
+
2176
+
2177
+ primary_warning_txt <- if (
2178
+ length(primary_diagnostic_msgs) > 0
2179
+ ) {
2180
+
2181
+ paste(
2182
+ primary_diagnostic_msgs,
2183
+ collapse = " | "
2184
+ )
2185
+
2186
+ } else {
2187
+
2188
+ NA_character_
2189
+ }
2190
+
2191
+
2192
+ # --------------------------------------------------------
2193
+ # Run allFit() as Multi-Optimizer Rescue
2194
+ # --------------------------------------------------------
2195
+
2196
+ message(
2197
+ " -> bobyqa convergence issue; running allFit() for ",
2198
+ re_terms,
2199
+ "..."
2200
+ )
2201
+
2202
+
2203
+ af <- try(
2204
+ suppressWarnings(
2205
+ lme4::allFit(
2206
+ primary_res,
2207
+ verbose = FALSE,
2208
+ parallel = "no"
2209
+ )
2210
+ ),
2211
+ silent = TRUE
2212
+ )
2213
+
2214
+
2215
+ # --------------------------------------------------------
2216
+ # 5.9A allFit() Itself Failed
2217
+ # --------------------------------------------------------
2218
+
2219
+ if (inherits(af, "try-error")) {
2220
+
2221
+ res <- primary_res
2222
+
2223
+ selected_via <-
2224
+ "bobyqa (allFit failed)"
2225
+
2226
+ retained_warning <- paste(
2227
+ primary_warning_txt,
2228
+ "allFit error:",
2229
+ as.character(af),
2230
+ sep = " | "
2231
+ )
2232
+
2233
+
2234
+ } else {
2235
+
2236
+
2237
+ ss <- summary(
2238
+ af
2239
+ )
2240
+
2241
+
2242
+ # ------------------------------------------------------
2243
+ # 5.9B Identify Warning-Free allFit Solutions
2244
+ # ------------------------------------------------------
2245
+
2246
+ valid_indices <- which(
2247
+ is.finite(
2248
+ ss$logLik
2249
+ ) &
2250
+ vapply(
2251
+ ss$msgs,
2252
+ function(x) {
2253
+ is.null(x) ||
2254
+ length(x) == 0
2255
+ },
2256
+ logical(1)
2257
+ )
2258
+ )
2259
+
2260
+
2261
+ # ------------------------------------------------------
2262
+ # 5.9C No Warning-Free allFit Solution
2263
+ # ------------------------------------------------------
2264
+
2265
+ if (length(valid_indices) == 0) {
2266
+
2267
+ res <- primary_res
2268
+
2269
+ selected_via <-
2270
+ "bobyqa (allFit found no warning-free solution)"
2271
+
2272
+ retained_warning <-
2273
+ primary_warning_txt
2274
+
2275
+
2276
+ } else {
2277
+
2278
+
2279
+ # ----------------------------------------------------
2280
+ # 5.9D Retain Best Clean allFit Solution
2281
+ # ----------------------------------------------------
2282
+
2283
+ best_idx <- valid_indices[
2284
+ which.max(
2285
+ ss$logLik[
2286
+ valid_indices
2287
+ ]
2288
+ )
2289
+ ]
2290
+
2291
+
2292
+ res <- af[[best_idx]]
2293
+
2294
+
2295
+ selected_via <- paste0(
2296
+ "allFit: ",
2297
+ names(af)[best_idx]
2298
+ )
2299
+
2300
+
2301
+ retained_warning <-
2302
+ NA_character_
2303
+ }
2304
+ }
2305
+ }
2306
+
2307
+
2308
+ # ----------------------------------------------------------
2309
+ # 5.10 Extract Final Convergence Diagnostics
2310
+ # ----------------------------------------------------------
2311
+
2312
+ msgs_lme4 <-
2313
+ res@optinfo$conv$lme4$messages
2314
+
2315
+
2316
+ opt_code <-
2317
+ res@optinfo$conv$opt
2318
+
2319
+
2320
+ lme4_msgs <- if (
2321
+ !is.null(msgs_lme4)
2322
+ ) {
2323
+
2324
+ as.character(
2325
+ unlist(
2326
+ msgs_lme4
2327
+ )
2328
+ )
2329
+
2330
+ } else {
2331
+
2332
+ character(0)
2333
+ }
2334
+
2335
+
2336
+ opt_failed <- FALSE
2337
+
2338
+
2339
+ if (
2340
+ !is.null(opt_code) &&
2341
+ length(opt_code) > 0
2342
+ ) {
2343
+
2344
+ opt_code_num <- suppressWarnings(
2345
+ as.numeric(
2346
+ unlist(
2347
+ opt_code
2348
+ )
2349
+ )
2350
+ )
2351
+
2352
+
2353
+ opt_failed <- any(
2354
+ is.na(opt_code_num) |
2355
+ opt_code_num != 0
2356
+ )
2357
+ }
2358
+
2359
+
2360
+ final_diagnostic_msgs <-
2361
+ lme4_msgs
2362
+
2363
+
2364
+ if (opt_failed) {
2365
+
2366
+ final_diagnostic_msgs <- c(
2367
+ final_diagnostic_msgs,
2368
+ paste0(
2369
+ "optimizer convergence code: ",
2370
+ paste(
2371
+ unlist(
2372
+ opt_code
2373
+ ),
2374
+ collapse = ", "
2375
+ )
2376
+ )
2377
+ )
2378
+ }
2379
+
2380
+
2381
+ final_warning_txt <- if (
2382
+ length(final_diagnostic_msgs) > 0
2383
+ ) {
2384
+
2385
+ paste(
2386
+ final_diagnostic_msgs,
2387
+ collapse = " | "
2388
+ )
2389
+
2390
+ } else {
2391
+
2392
+ NA_character_
2393
+ }
2394
+
2395
+
2396
+ # ----------------------------------------------------------
2397
+ # 5.11 Combine Rescue Information and Final Diagnostics
2398
+ # ----------------------------------------------------------
2399
+
2400
+ warning_parts <- c(
2401
+
2402
+ if (!is.na(retained_warning)) {
2403
+ retained_warning
2404
+ } else {
2405
+ NULL
2406
+ },
2407
+
2408
+ if (!is.na(final_warning_txt)) {
2409
+ final_warning_txt
2410
+ } else {
2411
+ NULL
2412
+ }
2413
+ )
2414
+
2415
+
2416
+ warning_parts <- unique(
2417
+ warning_parts[
2418
+ nzchar(
2419
+ warning_parts
2420
+ )
2421
+ ]
2422
+ )
2423
+
2424
+
2425
+ warn_txt <- if (
2426
+ length(warning_parts) > 0
2427
+ ) {
2428
+
2429
+ paste(
2430
+ warning_parts,
2431
+ collapse = " | "
2432
+ )
2433
+
2434
+ } else {
2435
+
2436
+ NA_character_
2437
+ }
2438
+
2439
+
2440
+ converged <-
2441
+ is.na(warn_txt)
2442
+
2443
+
2444
+ # ----------------------------------------------------------
2445
+ # 5.12 Extract Final Model Statistics
2446
+ # ----------------------------------------------------------
2447
+
2448
+ final_stats <- list(
2449
+
2450
+ name = paste0(
2451
+ "RE=",
2452
+ re_terms
2453
+ ),
2454
+
2455
+ re_formula =
2456
+ re_terms,
2457
+
2458
+ optimizer =
2459
+ res@optinfo$optimizer,
2460
+
2461
+ selected_via =
2462
+ selected_via,
2463
+
2464
+ converged =
2465
+ converged,
2466
+
2467
+ singular =
2468
+ isSingular(
2469
+ res,
2470
+ tol = 1e-5
2471
+ ),
2472
+
2473
+ aic =
2474
+ AIC(res),
2475
+
2476
+ bic =
2477
+ BIC(res),
2478
+
2479
+ llf =
2480
+ as.numeric(
2481
+ logLik(res)
2482
+ ),
2483
+
2484
+ nobs =
2485
+ nobs(res),
2486
+
2487
+ time_s =
2488
+ proc.time()[["elapsed"]] - t0,
2489
+
2490
+ status_msg =
2491
+ if (converged) {
2492
+ "OK"
2493
+ } else {
2494
+ "WARN"
2495
+ },
2496
+
2497
+ warnings =
2498
+ warn_txt
2499
+ )
2500
+
2501
+
2502
+ # ----------------------------------------------------------
2503
+ # 5.13 Structured Return
2504
+ # ----------------------------------------------------------
2505
+
2506
+ list(
2507
+
2508
+ winner =
2509
+ final_stats,
2510
+
2511
+ audit =
2512
+ list(
2513
+ final_stats
2514
+ ),
2515
+
2516
+ full_formula =
2517
+ full_formula
2518
+ )
2519
+ }
2520
+
2521
+
2522
+
2523
+
2524
+
2525
+
2526
+
2527
+
2528
+
2529
+ # ============================================================
2530
+ # CELL 6/7 — DV-SPECIFIC PREPARATION + PARALLEL MODEL RUNNER
2531
+ # FOR UNCORRELATED RANDOM SLOPES
2532
+ # ============================================================
2533
+ # Purpose:
2534
+ # Construct one analysis-ready dataset per duration DV and
2535
+ # compare all candidate uncorrelated random-slope structures
2536
+ # using that identical dataset.
2537
+ #
2538
+ # Responsibilities:
2539
+ # 1. Validate all variables required for the current DV.
2540
+ # 2. Construct the DV-specific complete-case sample.
2541
+ # 3. Remove non-positive values of the current duration DV.
2542
+ # 4. Natural-log transform the current duration DV.
2543
+ # 5. Standardize predictors using population SD (DDOF = 0)
2544
+ # AFTER the final DV-specific sample has been established.
2545
+ # 6. Convert grouping variables to factors.
2546
+ # 7. Fit every candidate uncorrelated random-slope structure
2547
+ # using the exact same prepared dataset.
2548
+ # 8. Execute candidate models in parallel.
2549
+ # 9. Collect model diagnostics and fit statistics.
2550
+ # 10. Evaluate and order candidate structures using
2551
+ # convergence, singularity, and BIC/AIC.
2552
+ # 11. Produce a detailed sample-size audit.
2553
+ #
2554
+ # Paper 1 fixed-effects specification:
2555
+ #
2556
+ # Lexical predictors:
2557
+ # - Length
2558
+ # - Predictability
2559
+ # - Frequency
2560
+ #
2561
+ # Affective predictors:
2562
+ # - Valence
2563
+ # - Arousal
2564
+ # - Dominance
2565
+ #
2566
+ # Random-effects framework:
2567
+ #
2568
+ # Step 3 evaluates participant-level UNCORRELATED random
2569
+ # slopes:
2570
+ #
2571
+ # (1 + candidate slopes || Participant_ID)
2572
+ #
2573
+ # while retaining the crossed random intercept:
2574
+ #
2575
+ # + (1 | Word_Unique_ID)
2576
+ #
2577
+ # The use of || rather than | is controlled globally by:
2578
+ #
2579
+ # USE_UNCORRELATED_SLOPES <- TRUE
2580
+ #
2581
+ # Important:
2582
+ # Filtering is DV-specific.
2583
+ #
2584
+ # No global IA_DWELL_TIME > 0 restriction is imposed.
2585
+ # Instead, the CURRENT duration DV must be non-missing and > 0.
2586
+ #
2587
+ # Predictor standardization occurs only AFTER this DV-specific
2588
+ # sample has been established. All candidate random-slope
2589
+ # models for the same DV therefore receive:
2590
+ #
2591
+ # - identical observations
2592
+ # - identical transformed DV values
2593
+ # - identical standardized predictor values
2594
+ # - identical fixed-effects specification
2595
+ #
2596
+ # Only the participant-level uncorrelated random-slope
2597
+ # structure changes across candidates.
2598
+ #
2599
+ # This is essential for fair AIC/BIC comparison.
2600
+ # ============================================================
2601
+
2602
+
2603
+ # ------------------------------------------------------------
2604
+ # 6.1 Population-SD Standardization Function (DDOF = 0)
2605
+ # ------------------------------------------------------------
2606
+
2607
+ zscore_ddof0 <- function(x) {
2608
+
2609
+ x <- suppressWarnings(
2610
+ as.numeric(x)
2611
+ )
2612
+
2613
+ n <- sum(
2614
+ !is.na(x)
2615
+ )
2616
+
2617
+ if (n <= 1) {
2618
+ return(x)
2619
+ }
2620
+
2621
+ s1 <- sd(
2622
+ x,
2623
+ na.rm = TRUE
2624
+ )
2625
+
2626
+ if (
2627
+ !is.finite(s1) ||
2628
+ s1 <= 0
2629
+ ) {
2630
+ return(x)
2631
+ }
2632
+
2633
+ s0 <- s1 * sqrt(
2634
+ (n - 1) / n
2635
+ )
2636
+
2637
+ (
2638
+ x - mean(
2639
+ x,
2640
+ na.rm = TRUE
2641
+ )
2642
+ ) / s0
2643
+ }
2644
+
2645
+
2646
+ # ------------------------------------------------------------
2647
+ # 6.2 DV-Specific Analysis-Data Preparation
2648
+ # ------------------------------------------------------------
2649
+
2650
+ prep_df_complete_cases <- function(
2651
+ df,
2652
+ dv,
2653
+ participant_col,
2654
+ required_cols,
2655
+ use_additional_intercept = FALSE,
2656
+ additional_intercept_col = NULL
2657
+ ) {
2658
+
2659
+ needed <- unique(
2660
+ c(
2661
+ dv,
2662
+ participant_col,
2663
+ required_cols,
2664
+ if (use_additional_intercept) {
2665
+ additional_intercept_col
2666
+ } else {
2667
+ NULL
2668
+ }
2669
+ )
2670
+ )
2671
+
2672
+
2673
+ # ----------------------------------------------------------
2674
+ # Validate Required Variables
2675
+ # ----------------------------------------------------------
2676
+
2677
+ missing_required <- setdiff(
2678
+ needed,
2679
+ names(df)
2680
+ )
2681
+
2682
+ if (length(missing_required) > 0) {
2683
+
2684
+ stop(
2685
+ "Missing required variable(s) for ",
2686
+ dv,
2687
+ ": ",
2688
+ paste(
2689
+ missing_required,
2690
+ collapse = ", "
2691
+ )
2692
+ )
2693
+ }
2694
+
2695
+
2696
+ # ----------------------------------------------------------
2697
+ # Select Required Variables
2698
+ # ----------------------------------------------------------
2699
+
2700
+ df_clean <- df %>%
2701
+ select(
2702
+ all_of(needed)
2703
+ )
2704
+
2705
+ n_source <- nrow(
2706
+ df_clean
2707
+ )
2708
+
2709
+
2710
+ # ----------------------------------------------------------
2711
+ # Coerce DV and Continuous Predictors to Numeric
2712
+ # ----------------------------------------------------------
2713
+
2714
+ numeric_cols <- unique(
2715
+ c(
2716
+ dv,
2717
+ required_cols
2718
+ )
2719
+ )
2720
+
2721
+ df_clean <- df_clean %>%
2722
+ mutate(
2723
+ across(
2724
+ all_of(numeric_cols),
2725
+ ~ suppressWarnings(
2726
+ as.numeric(.x)
2727
+ )
2728
+ )
2729
+ )
2730
+
2731
+
2732
+ # ----------------------------------------------------------
2733
+ # Remove Missing Values
2734
+ # ----------------------------------------------------------
2735
+
2736
+ df_clean <- df_clean %>%
2737
+ drop_na()
2738
+
2739
+ n_complete <- nrow(
2740
+ df_clean
2741
+ )
2742
+
2743
+ n_removed_missing <- (
2744
+ n_source -
2745
+ n_complete
2746
+ )
2747
+
2748
+
2749
+ # ----------------------------------------------------------
2750
+ # Retain Positive Values of the Current Duration DV
2751
+ # ----------------------------------------------------------
2752
+
2753
+ df_clean <- df_clean %>%
2754
+ filter(
2755
+ .data[[dv]] > 0
2756
+ )
2757
+
2758
+ n_positive <- nrow(
2759
+ df_clean
2760
+ )
2761
+
2762
+ n_removed_nonpositive <- (
2763
+ n_complete -
2764
+ n_positive
2765
+ )
2766
+
2767
+
2768
+ # ----------------------------------------------------------
2769
+ # Natural-Log Transform Current DV
2770
+ # ----------------------------------------------------------
2771
+
2772
+ df_clean[[dv]] <- log(
2773
+ df_clean[[dv]]
2774
+ )
2775
+
2776
+
2777
+ # ----------------------------------------------------------
2778
+ # Standardize Predictors Within Final DV-Specific Sample
2779
+ # ----------------------------------------------------------
2780
+
2781
+ df_clean <- df_clean %>%
2782
+ mutate(
2783
+ across(
2784
+ all_of(required_cols),
2785
+ zscore_ddof0
2786
+ )
2787
+ )
2788
+
2789
+
2790
+ # ----------------------------------------------------------
2791
+ # Convert Grouping Variables to Factors
2792
+ # ----------------------------------------------------------
2793
+
2794
+ df_clean[[participant_col]] <- as.factor(
2795
+ as.character(
2796
+ df_clean[[participant_col]]
2797
+ )
2798
+ )
2799
+
2800
+ if (
2801
+ use_additional_intercept &&
2802
+ !is.null(additional_intercept_col)
2803
+ ) {
2804
+
2805
+ df_clean[[additional_intercept_col]] <- as.factor(
2806
+ as.character(
2807
+ df_clean[[additional_intercept_col]]
2808
+ )
2809
+ )
2810
+ }
2811
+
2812
+
2813
+ # ----------------------------------------------------------
2814
+ # Attach Filtering Diagnostics
2815
+ # ----------------------------------------------------------
2816
+
2817
+ attr(
2818
+ df_clean,
2819
+ "filter_summary"
2820
+ ) <- tibble(
2821
+
2822
+ DV = dv,
2823
+
2824
+ N_Source = n_source,
2825
+
2826
+ N_Removed_Missing =
2827
+ n_removed_missing,
2828
+
2829
+ N_Complete =
2830
+ n_complete,
2831
+
2832
+ N_Removed_NonPositive =
2833
+ n_removed_nonpositive,
2834
+
2835
+ N_Final =
2836
+ n_positive,
2837
+
2838
+ Percent_Retained =
2839
+ if (n_source > 0) {
2840
+ round(
2841
+ 100 * n_positive / n_source,
2842
+ 2
2843
+ )
2844
+ } else {
2845
+ NA_real_
2846
+ },
2847
+
2848
+ N_Participants =
2849
+ n_distinct(
2850
+ df_clean[[participant_col]]
2851
+ ),
2852
+
2853
+ N_Additional_Intercept =
2854
+ if (
2855
+ use_additional_intercept &&
2856
+ !is.null(additional_intercept_col)
2857
+ ) {
2858
+
2859
+ n_distinct(
2860
+ df_clean[[additional_intercept_col]]
2861
+ )
2862
+
2863
+ } else {
2864
+
2865
+ NA_integer_
2866
+ }
2867
+ )
2868
+
2869
+
2870
+ # ----------------------------------------------------------
2871
+ # Report Preparation Summary
2872
+ # ----------------------------------------------------------
2873
+
2874
+ message(
2875
+ " Source observations : ",
2876
+ format(
2877
+ n_source,
2878
+ big.mark = ","
2879
+ )
2880
+ )
2881
+
2882
+ message(
2883
+ " Removed for missingness : ",
2884
+ format(
2885
+ n_removed_missing,
2886
+ big.mark = ","
2887
+ )
2888
+ )
2889
+
2890
+ message(
2891
+ " Removed DV <= 0 : ",
2892
+ format(
2893
+ n_removed_nonpositive,
2894
+ big.mark = ","
2895
+ )
2896
+ )
2897
+
2898
+ message(
2899
+ " Final modeling N : ",
2900
+ format(
2901
+ n_positive,
2902
+ big.mark = ","
2903
+ )
2904
+ )
2905
+
2906
+ message(
2907
+ " DV log transformation : APPLIED"
2908
+ )
2909
+
2910
+ message(
2911
+ " Predictor standardization : APPLIED (DDOF = 0)"
2912
+ )
2913
+
2914
+
2915
+ df_clean
2916
+ }
2917
+
2918
+
2919
+ # ------------------------------------------------------------
2920
+ # 6.3 Dynamic Uncorrelated Random-Slope Selection Engine
2921
+ # ------------------------------------------------------------
2922
+
2923
+ select_re_structure_dynamic <- function(
2924
+ df,
2925
+ dv,
2926
+ re_candidates,
2927
+ participant_col = "Participant_ID",
2928
+ additional_intercept_col = NULL,
2929
+ use_additional_intercept = FALSE,
2930
+ controls = c(
2931
+ "Length",
2932
+ "Predictability",
2933
+ "Frequency"
2934
+ ),
2935
+ emotions = c(
2936
+ "Valence",
2937
+ "Arousal",
2938
+ "Dominance"
2939
+ ),
2940
+ rank_by = c(
2941
+ "BIC",
2942
+ "AIC"
2943
+ ),
2944
+ n_jobs = 1
2945
+ ) {
2946
+
2947
+
2948
+ # ----------------------------------------------------------
2949
+ # 6.3.1 Configuration
2950
+ # ----------------------------------------------------------
2951
+
2952
+ rank_by <- match.arg(
2953
+ toupper(rank_by),
2954
+ c(
2955
+ "BIC",
2956
+ "AIC"
2957
+ )
2958
+ )
2959
+
2960
+ n_jobs <- max(
2961
+ 1L,
2962
+ as.integer(n_jobs)
2963
+ )
2964
+
2965
+ required_cols <- unique(
2966
+ c(
2967
+ controls,
2968
+ emotions
2969
+ )
2970
+ )
2971
+
2972
+
2973
+ # ----------------------------------------------------------
2974
+ # Validate Fixed-Effect Variables
2975
+ # ----------------------------------------------------------
2976
+
2977
+ missing_fixed <- setdiff(
2978
+ required_cols,
2979
+ names(df)
2980
+ )
2981
+
2982
+ if (length(missing_fixed) > 0) {
2983
+
2984
+ stop(
2985
+ "Missing fixed-effect variable(s) for ",
2986
+ dv,
2987
+ ": ",
2988
+ paste(
2989
+ missing_fixed,
2990
+ collapse = ", "
2991
+ )
2992
+ )
2993
+ }
2994
+
2995
+
2996
+ # ----------------------------------------------------------
2997
+ # Construct Fixed-Effects Formula
2998
+ # ----------------------------------------------------------
2999
+
3000
+ fixed_formula <- as.formula(
3001
+ paste0(
3002
+ dv,
3003
+ " ~ ",
3004
+ paste(
3005
+ required_cols,
3006
+ collapse = " + "
3007
+ )
3008
+ )
3009
+ )
3010
+
3011
+
3012
+ # ----------------------------------------------------------
3013
+ # 6.3.2 Prepare ONE Modeling Dataset for Current DV
3014
+ # ----------------------------------------------------------
3015
+
3016
+ model_df <- prep_df_complete_cases(
3017
+ df = df,
3018
+ dv = dv,
3019
+ participant_col = participant_col,
3020
+ required_cols = required_cols,
3021
+ use_additional_intercept =
3022
+ use_additional_intercept,
3023
+ additional_intercept_col =
3024
+ additional_intercept_col
3025
+ )
3026
+
3027
+ filter_summary <- attr(
3028
+ model_df,
3029
+ "filter_summary"
3030
+ )
3031
+
3032
+
3033
+ # ----------------------------------------------------------
3034
+ # Safety Check: Final Modeling Dataset Must Be Nonempty
3035
+ # ----------------------------------------------------------
3036
+
3037
+ if (nrow(model_df) == 0) {
3038
+
3039
+ stop(
3040
+ "No eligible observations remain for ",
3041
+ dv,
3042
+ " after DV-specific preparation."
3043
+ )
3044
+ }
3045
+
3046
+
3047
+ # ----------------------------------------------------------
3048
+ # 6.3.3 Row-Count Audit
3049
+ # ----------------------------------------------------------
3050
+
3051
+ rowcounts <- dv_rowcount_summary(
3052
+ df = df,
3053
+ dv = dv,
3054
+ required_cols = c(
3055
+ required_cols,
3056
+ participant_col,
3057
+ if (use_additional_intercept) {
3058
+ additional_intercept_col
3059
+ } else {
3060
+ NULL
3061
+ }
3062
+ ),
3063
+ label = paste0(
3064
+ dv,
3065
+ "_AIC_BIC_rows"
3066
+ )
3067
+ ) %>%
3068
+ mutate(
3069
+ rows_after_complete_case =
3070
+ filter_summary$N_Complete,
3071
+
3072
+ rows_removed_DV_nonpositive =
3073
+ filter_summary$N_Removed_NonPositive,
3074
+
3075
+ final_rows_used_for_AIC_BIC =
3076
+ filter_summary$N_Final,
3077
+
3078
+ pct_final_rows_retained =
3079
+ filter_summary$Percent_Retained
3080
+ )
3081
+
3082
+
3083
+ # ----------------------------------------------------------
3084
+ # 6.3.4 Candidate Execution Ordering
3085
+ # ----------------------------------------------------------
3086
+
3087
+ cand_list <- rev(
3088
+ re_candidates
3089
+ )
3090
+
3091
+ indexed <- tibble(
3092
+ idx = seq_along(
3093
+ cand_list
3094
+ ),
3095
+ candidate = cand_list
3096
+ )
3097
+
3098
+
3099
+ # ----------------------------------------------------------
3100
+ # 6.3.5 Parallel Execution Setup
3101
+ # ----------------------------------------------------------
3102
+ # Preserve the future strategy that was active before this
3103
+ # function was called.
3104
+ #
3105
+ # The current DV is evaluated using a multisession plan with
3106
+ # the resource-constrained worker count determined earlier.
3107
+ #
3108
+ # on.exit() guarantees restoration of the previous future
3109
+ # strategy when this function terminates, including after an
3110
+ # error. This prevents the DV-specific multisession plan from
3111
+ # leaking into subsequent analysis code.
3112
+ # ----------------------------------------------------------
3113
+
3114
+ old_plan <- future::plan()
3115
+
3116
+
3117
+ on.exit(
3118
+ {
3119
+ future::plan(
3120
+ old_plan
3121
+ )
3122
+ },
3123
+ add = TRUE
3124
+ )
3125
+
3126
+
3127
+ future::plan(
3128
+ future::multisession,
3129
+ workers = n_jobs
3130
+ )
3131
+
3132
+
3133
+ progressr::handlers(
3134
+ global = TRUE
3135
+ )
3136
+
3137
+
3138
+ # ----------------------------------------------------------
3139
+ # 6.3.6 Parallel Candidate-Model Execution
3140
+ # ----------------------------------------------------------
3141
+
3142
+ results_payload <- progressr::with_progress({
3143
+
3144
+ progressor_obj <- progressr::progressor(
3145
+ steps = nrow(indexed)
3146
+ )
3147
+
3148
+ future.apply::future_lapply(
3149
+ seq_len(
3150
+ nrow(indexed)
3151
+ ),
3152
+ function(i) {
3153
+
3154
+ idx <- indexed$idx[i]
3155
+ cand <- indexed$candidate[i]
3156
+
3157
+ t0 <- proc.time()[["elapsed"]]
3158
+
3159
+ fit <- fit_single_candidate_tiered(
3160
+ dv = dv,
3161
+ fixed_formula = fixed_formula,
3162
+ model_df = model_df,
3163
+ re_terms = cand,
3164
+ groups_col = participant_col,
3165
+ use_additional_intercept =
3166
+ use_additional_intercept,
3167
+ additional_intercept_col =
3168
+ additional_intercept_col,
3169
+ reml = TRUE
3170
+ )
3171
+
3172
+ progressor_obj(
3173
+ message = paste0(
3174
+ "[",
3175
+ idx,
3176
+ "/",
3177
+ nrow(indexed),
3178
+ "] ",
3179
+ cand
3180
+ )
3181
+ )
3182
+
3183
+ list(
3184
+ idx = idx,
3185
+ candidate = cand,
3186
+ winner = fit$winner,
3187
+ audit = fit$audit,
3188
+ task_wall_s =
3189
+ proc.time()[["elapsed"]] - t0
3190
+ )
3191
+ },
3192
+
3193
+ future.seed = TRUE,
3194
+
3195
+ future.globals = list(
3196
+ indexed = indexed,
3197
+ dv = dv,
3198
+ fixed_formula = fixed_formula,
3199
+ model_df = model_df,
3200
+ participant_col = participant_col,
3201
+ additional_intercept_col =
3202
+ additional_intercept_col,
3203
+ use_additional_intercept =
3204
+ use_additional_intercept,
3205
+ fit_single_candidate_tiered =
3206
+ fit_single_candidate_tiered,
3207
+ USE_UNCORRELATED_SLOPES =
3208
+ USE_UNCORRELATED_SLOPES
3209
+ ),
3210
+
3211
+ future.packages = c(
3212
+ "lme4"
3213
+ )
3214
+ )
3215
+ })
3216
+
3217
+
3218
+ # ----------------------------------------------------------
3219
+ # 6.3.7 Restore Deterministic Execution Order
3220
+ # ----------------------------------------------------------
3221
+
3222
+ results_payload <- results_payload[
3223
+ order(
3224
+ vapply(
3225
+ results_payload,
3226
+ `[[`,
3227
+ numeric(1),
3228
+ "idx"
3229
+ )
3230
+ )
3231
+ ]
3232
+
3233
+
3234
+ # ----------------------------------------------------------
3235
+ # 6.3.8 Collect Model Results and Audit Records
3236
+ # ----------------------------------------------------------
3237
+
3238
+ winner_rows <- list()
3239
+ audit_rows <- list()
3240
+
3241
+
3242
+ for (payload in results_payload) {
3243
+
3244
+ w <- payload$winner
3245
+
3246
+ if (
3247
+ is.finite(w$aic) &&
3248
+ is.finite(w$bic)
3249
+ ) {
3250
+
3251
+ winner_rows <- append(
3252
+ winner_rows,
3253
+ list(
3254
+ tibble(
3255
+ idx = payload$idx,
3256
+ candidate = payload$candidate,
3257
+ re_formula = w$re_formula,
3258
+ optimizer = w$optimizer,
3259
+ selected_via = w$selected_via,
3260
+ converged = w$converged,
3261
+ singular = w$singular,
3262
+ aic = w$aic,
3263
+ bic = w$bic,
3264
+ llf = w$llf,
3265
+ nobs = as.integer(
3266
+ w$nobs
3267
+ ),
3268
+ winner_fit_time_s = as.numeric(
3269
+ w$time_s
3270
+ ),
3271
+ candidate_task_time_s = as.numeric(
3272
+ payload$task_wall_s
3273
+ ),
3274
+ warnings = w$warnings,
3275
+ status = w$status_msg
3276
+ )
3277
+ )
3278
+ )
3279
+ }
3280
+
3281
+
3282
+ for (a in payload$audit) {
3283
+
3284
+ audit_rows <- append(
3285
+ audit_rows,
3286
+ list(
3287
+ tibble(
3288
+ idx = payload$idx,
3289
+ candidate = payload$candidate,
3290
+ re_formula = a$re_formula,
3291
+ optimizer = a$optimizer,
3292
+ selected_via = a$selected_via,
3293
+ status = a$status_msg,
3294
+ converged = a$converged,
3295
+ singular = a$singular,
3296
+ aic = a$aic,
3297
+ bic = a$bic,
3298
+ llf = a$llf,
3299
+ nobs = as.integer(
3300
+ a$nobs
3301
+ ),
3302
+ time_s = as.numeric(
3303
+ a$time_s
3304
+ ),
3305
+ warnings = a$warnings
3306
+ )
3307
+ )
3308
+ )
3309
+ }
3310
+ }
3311
+
3312
+
3313
+ # ----------------------------------------------------------
3314
+ # 6.3.9 Final Candidate Evaluation and Selection Ordering
3315
+ # ----------------------------------------------------------
3316
+
3317
+ df_results <- if (
3318
+ length(winner_rows) > 0
3319
+ ) {
3320
+
3321
+ bind_rows(
3322
+ winner_rows
3323
+ )
3324
+
3325
+ } else {
3326
+
3327
+ tibble()
3328
+ }
3329
+
3330
+
3331
+ df_audit <- if (
3332
+ length(audit_rows) > 0
3333
+ ) {
3334
+
3335
+ bind_rows(
3336
+ audit_rows
3337
+ )
3338
+
3339
+ } else {
3340
+
3341
+ tibble()
3342
+ }
3343
+
3344
+
3345
+ if (nrow(df_results) > 0) {
3346
+
3347
+ sort_col <- if (
3348
+ rank_by == "BIC"
3349
+ ) {
3350
+
3351
+ "bic"
3352
+
3353
+ } else {
3354
+
3355
+ "aic"
3356
+ }
3357
+
3358
+
3359
+ # --------------------------------------------------------
3360
+ # Identify Models Eligible for Primary Structure Selection
3361
+ # --------------------------------------------------------
3362
+
3363
+ df_results <- df_results %>%
3364
+ mutate(
3365
+ selection_eligible =
3366
+ converged %in% TRUE &
3367
+ singular %in% FALSE
3368
+ )
3369
+
3370
+
3371
+ # --------------------------------------------------------
3372
+ # Compute Raw Information-Criterion Differences
3373
+ # --------------------------------------------------------
3374
+
3375
+ df_results <- df_results %>%
3376
+ mutate(
3377
+ delta_aic =
3378
+ aic - min(
3379
+ aic,
3380
+ na.rm = TRUE
3381
+ ),
3382
+
3383
+ delta_bic =
3384
+ bic - min(
3385
+ bic,
3386
+ na.rm = TRUE
3387
+ )
3388
+ )
3389
+
3390
+
3391
+ # --------------------------------------------------------
3392
+ # Rank Eligible Models First
3393
+ # --------------------------------------------------------
3394
+
3395
+ df_results <- df_results %>%
3396
+ arrange(
3397
+ desc(
3398
+ selection_eligible
3399
+ ),
3400
+ .data[[sort_col]]
3401
+ )
3402
+ }
3403
+
3404
+
3405
+ # ----------------------------------------------------------
3406
+ # 6.3.10 Verify Equal Observation Counts Across Candidates
3407
+ # ----------------------------------------------------------
3408
+
3409
+ if (nrow(df_results) > 0) {
3410
+
3411
+ unique_nobs <- unique(
3412
+ df_results$nobs
3413
+ )
3414
+
3415
+ if (length(unique_nobs) != 1) {
3416
+
3417
+ warning(
3418
+ "Candidate models for ",
3419
+ dv,
3420
+ " were fitted with different observation counts."
3421
+ )
3422
+ }
3423
+ }
3424
+
3425
+
3426
+ # ----------------------------------------------------------
3427
+ # 6.3.11 Return Results
3428
+ # ----------------------------------------------------------
3429
+
3430
+ list(
3431
+ df_results = df_results,
3432
+ df_audit = df_audit,
3433
+ rowcounts = rowcounts,
3434
+ filter_summary = filter_summary
3435
+ )
3436
+ }
3437
+
3438
+
3439
+
3440
+
3441
+
3442
+
3443
+
3444
+
3445
+
3446
+ # ============================================================
3447
+ # CELL 8/9 — MANUAL DV-BY-DV UNCORRELATED-SLOPE EXECUTION
3448
+ # ============================================================
3449
+ # Purpose:
3450
+ # Run the uncorrelated random-slope selection procedure
3451
+ # independently for each duration-based dependent variable.
3452
+ #
3453
+ # Execution strategy:
3454
+ # Each DV is defined in a separate execution block rather
3455
+ # than inside a single loop.
3456
+ #
3457
+ # When the full script is executed, the four DV blocks run
3458
+ # sequentially. Individual DV blocks can also be executed
3459
+ # independently when rerunning or recovering an analysis.
3460
+ #
3461
+ # Advantages:
3462
+ # - Limits the consequences of a long-running model failure.
3463
+ # - Allows each DV to be restarted independently.
3464
+ # - Simplifies monitoring of CPU/RAM use.
3465
+ # - Allows results to be inspected before proceeding.
3466
+ # - Produces a separate Excel workbook for each DV.
3467
+ #
3468
+ # For each DV:
3469
+ # 1. Construct the DV-specific analysis sample.
3470
+ # 2. Remove missing/non-positive duration observations.
3471
+ # 3. Log-transform the current duration DV.
3472
+ # 4. Standardize LFP + VAD predictors within that sample.
3473
+ # 5. Fit all candidate uncorrelated random-slope structures.
3474
+ # 6. Evaluate candidates using BIC, convergence, and
3475
+ # singularity diagnostics.
3476
+ # 7. Order selection-eligible candidates first, ranked by BIC
3477
+ # within eligibility class.
3478
+ #
3479
+ # Paper 1:
3480
+ # Source dataset:
3481
+ # Affective Provo
3482
+ #
3483
+ # Fixed effects / candidate slopes:
3484
+ # Length
3485
+ # Predictability
3486
+ # Frequency
3487
+ # Valence
3488
+ # Arousal
3489
+ # Dominance
3490
+ #
3491
+ # Random-effects framework:
3492
+ # (1 + candidate slopes || Participant_ID)
3493
+ # + (1 | Word_Unique_ID)
3494
+ #
3495
+ # Important:
3496
+ # - Candidate models within a DV use exactly the same
3497
+ # DV-specific analysis sample.
3498
+ # - Filtering and standardization are performed once per DV,
3499
+ # before candidate-model fitting.
3500
+ # - BIC is the primary ranking criterion.
3501
+ # - Convergence and singularity diagnostics must also be
3502
+ # considered when selecting the final random-slope structure.
3503
+ # - The distinction from Step 2 is the participant-level
3504
+ # covariance structure:
3505
+ #
3506
+ # Step 2: (1 + slopes | Participant_ID)
3507
+ # Step 3: (1 + slopes || Participant_ID)
3508
+ #
3509
+ # Output:
3510
+ # One Step 3 Excel workbook per duration DV containing:
3511
+ # - candidate ranking
3512
+ # - model-fit audit
3513
+ # - sample-size / row-count audit
3514
+ #
3515
+ # Runtime:
3516
+ # Runtime depends on sample size, candidate complexity,
3517
+ # optimizer behavior, hardware, and number of workers.
3518
+ # Runtime estimates from earlier versions should therefore
3519
+ # not be assumed for the revised pipeline.
3520
+ # ============================================================
3521
+
3522
+
3523
+ # ------------------------------------------------------------
3524
+ # 8.1 DV Registry
3525
+ # ------------------------------------------------------------
3526
+
3527
+ DV_INFO <- list(
3528
+ IA_FIRST_FIXATION_DURATION = list(serial = 1, suffix = "FFD"),
3529
+ IA_FIRST_RUN_DWELL_TIME = list(serial = 2, suffix = "GD"),
3530
+ IA_REGRESSION_PATH_DURATION = list(serial = 3, suffix = "GPT"),
3531
+ IA_DWELL_TIME = list(serial = 4, suffix = "TDT")
3532
+ )
3533
+
3534
+
3535
+
3536
+ # ============================================================
3537
+ # DV 1 — FIRST FIXATION DURATION (FFD)
3538
+ # ============================================================
3539
+
3540
+ DV_TO_RUN <- "IA_FIRST_FIXATION_DURATION"
3541
+
3542
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3543
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3544
+ }
3545
+
3546
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3547
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3548
+
3549
+ message("\n", strrep("=", 80))
3550
+ message("STARTING UNCORRELATED-SLOPE ANALYSIS")
3551
+ message(
3552
+ "DV: ",
3553
+ DV_TO_RUN,
3554
+ " | Stage=",
3555
+ DV_SERIAL,
3556
+ " | Measure=",
3557
+ DV_SUFFIX
3558
+ )
3559
+ message("Dataset: Affective Provo")
3560
+ message(strrep("=", 80))
3561
+
3562
+ t0 <- proc.time()[["elapsed"]]
3563
+
3564
+ res <- select_re_structure_dynamic(
3565
+ df = df,
3566
+ dv = DV_TO_RUN,
3567
+ re_candidates = CANDIDATES,
3568
+ rank_by = "BIC",
3569
+ n_jobs = N_JOBS,
3570
+ participant_col = "Participant_ID",
3571
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3572
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3573
+ )
3574
+
3575
+ out_path <- file.path(
3576
+ OUTPUT_DATA_DIR,
3577
+ paste0(
3578
+ "Step-3-",
3579
+ DV_SERIAL, "_",
3580
+ DV_SUFFIX,
3581
+ "_UncorrelatedSlopes_Affective_Provo.xlsx"
3582
+ )
3583
+ )
3584
+
3585
+ save_re_outputs_to_excel(
3586
+ excel_path = out_path,
3587
+ dv = DV_TO_RUN,
3588
+ df_results = res$df_results,
3589
+ df_audit = res$df_audit,
3590
+ rowcount_summary = res$rowcounts
3591
+ )
3592
+
3593
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3594
+
3595
+ message("\nDV-SPECIFIC SAMPLE:")
3596
+ print(res$filter_summary)
3597
+
3598
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3599
+ message("Saved to: ", out_path)
3600
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3601
+
3602
+
3603
+
3604
+ # ============================================================
3605
+ # DV 2 — FIRST-RUN DWELL TIME / GAZE DURATION (GD)
3606
+ # ============================================================
3607
+
3608
+ DV_TO_RUN <- "IA_FIRST_RUN_DWELL_TIME"
3609
+
3610
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3611
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3612
+ }
3613
+
3614
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3615
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3616
+
3617
+ message("\n", strrep("=", 80))
3618
+ message("STARTING UNCORRELATED-SLOPE ANALYSIS")
3619
+ message(
3620
+ "DV: ",
3621
+ DV_TO_RUN,
3622
+ " | Stage=",
3623
+ DV_SERIAL,
3624
+ " | Measure=",
3625
+ DV_SUFFIX
3626
+ )
3627
+ message("Dataset: Affective Provo")
3628
+ message(strrep("=", 80))
3629
+
3630
+ t0 <- proc.time()[["elapsed"]]
3631
+
3632
+ res <- select_re_structure_dynamic(
3633
+ df = df,
3634
+ dv = DV_TO_RUN,
3635
+ re_candidates = CANDIDATES,
3636
+ rank_by = "BIC",
3637
+ n_jobs = N_JOBS,
3638
+ participant_col = "Participant_ID",
3639
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3640
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3641
+ )
3642
+
3643
+ out_path <- file.path(
3644
+ OUTPUT_DATA_DIR,
3645
+ paste0(
3646
+ "Step-3-",
3647
+ DV_SERIAL, "_",
3648
+ DV_SUFFIX,
3649
+ "_UncorrelatedSlopes_Affective_Provo.xlsx"
3650
+ )
3651
+ )
3652
+
3653
+ save_re_outputs_to_excel(
3654
+ excel_path = out_path,
3655
+ dv = DV_TO_RUN,
3656
+ df_results = res$df_results,
3657
+ df_audit = res$df_audit,
3658
+ rowcount_summary = res$rowcounts
3659
+ )
3660
+
3661
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3662
+
3663
+ message("\nDV-SPECIFIC SAMPLE:")
3664
+ print(res$filter_summary)
3665
+
3666
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3667
+ message("Saved to: ", out_path)
3668
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3669
+
3670
+
3671
+
3672
+ # ============================================================
3673
+ # DV 3 — REGRESSION PATH DURATION / GO-PAST TIME (GPT)
3674
+ # ============================================================
3675
+
3676
+ DV_TO_RUN <- "IA_REGRESSION_PATH_DURATION"
3677
+
3678
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3679
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3680
+ }
3681
+
3682
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3683
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3684
+
3685
+ message("\n", strrep("=", 80))
3686
+ message("STARTING UNCORRELATED-SLOPE ANALYSIS")
3687
+ message(
3688
+ "DV: ",
3689
+ DV_TO_RUN,
3690
+ " | Stage=",
3691
+ DV_SERIAL,
3692
+ " | Measure=",
3693
+ DV_SUFFIX
3694
+ )
3695
+ message("Dataset: Affective Provo")
3696
+ message(strrep("=", 80))
3697
+
3698
+ t0 <- proc.time()[["elapsed"]]
3699
+
3700
+ res <- select_re_structure_dynamic(
3701
+ df = df,
3702
+ dv = DV_TO_RUN,
3703
+ re_candidates = CANDIDATES,
3704
+ rank_by = "BIC",
3705
+ n_jobs = N_JOBS,
3706
+ participant_col = "Participant_ID",
3707
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3708
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3709
+ )
3710
+
3711
+ out_path <- file.path(
3712
+ OUTPUT_DATA_DIR,
3713
+ paste0(
3714
+ "Step-3-",
3715
+ DV_SERIAL, "_",
3716
+ DV_SUFFIX,
3717
+ "_UncorrelatedSlopes_Affective_Provo.xlsx"
3718
+ )
3719
+ )
3720
+
3721
+ save_re_outputs_to_excel(
3722
+ excel_path = out_path,
3723
+ dv = DV_TO_RUN,
3724
+ df_results = res$df_results,
3725
+ df_audit = res$df_audit,
3726
+ rowcount_summary = res$rowcounts
3727
+ )
3728
+
3729
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3730
+
3731
+ message("\nDV-SPECIFIC SAMPLE:")
3732
+ print(res$filter_summary)
3733
+
3734
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3735
+ message("Saved to: ", out_path)
3736
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3737
+
3738
+
3739
+
3740
+ # ============================================================
3741
+ # DV 4 — TOTAL DWELL TIME / TOTAL READING TIME (TDT)
3742
+ # ============================================================
3743
+
3744
+ DV_TO_RUN <- "IA_DWELL_TIME"
3745
+
3746
+ if (is.null(DV_INFO[[DV_TO_RUN]])) {
3747
+ stop("Unknown DV_TO_RUN: ", DV_TO_RUN)
3748
+ }
3749
+
3750
+ DV_SERIAL <- DV_INFO[[DV_TO_RUN]]$serial
3751
+ DV_SUFFIX <- DV_INFO[[DV_TO_RUN]]$suffix
3752
+
3753
+ message("\n", strrep("=", 80))
3754
+ message("STARTING UNCORRELATED-SLOPE ANALYSIS")
3755
+ message(
3756
+ "DV: ",
3757
+ DV_TO_RUN,
3758
+ " | Stage=",
3759
+ DV_SERIAL,
3760
+ " | Measure=",
3761
+ DV_SUFFIX
3762
+ )
3763
+ message("Dataset: Affective Provo")
3764
+ message(strrep("=", 80))
3765
+
3766
+ t0 <- proc.time()[["elapsed"]]
3767
+
3768
+ res <- select_re_structure_dynamic(
3769
+ df = df,
3770
+ dv = DV_TO_RUN,
3771
+ re_candidates = CANDIDATES,
3772
+ rank_by = "BIC",
3773
+ n_jobs = N_JOBS,
3774
+ participant_col = "Participant_ID",
3775
+ additional_intercept_col = ADDITIONAL_INTERCEPT,
3776
+ use_additional_intercept = USE_ADDITIONAL_INTERCEPT
3777
+ )
3778
+
3779
+ out_path <- file.path(
3780
+ OUTPUT_DATA_DIR,
3781
+ paste0(
3782
+ "Step-3-",
3783
+ DV_SERIAL, "_",
3784
+ DV_SUFFIX,
3785
+ "_UncorrelatedSlopes_Affective_Provo.xlsx"
3786
+ )
3787
+ )
3788
+
3789
+ save_re_outputs_to_excel(
3790
+ excel_path = out_path,
3791
+ dv = DV_TO_RUN,
3792
+ df_results = res$df_results,
3793
+ df_audit = res$df_audit,
3794
+ rowcount_summary = res$rowcounts
3795
+ )
3796
+
3797
+ elapsed_total <- proc.time()[["elapsed"]] - t0
3798
+
3799
+ message("\nDV-SPECIFIC SAMPLE:")
3800
+ print(res$filter_summary)
3801
+
3802
+ message("\nCOMPLETED DV: ", DV_TO_RUN)
3803
+ message("Saved to: ", out_path)
3804
+ message("Elapsed time: ", fmt_secs(elapsed_total))
3805
+
3806
+
3807
+
3808
+
3809
+
3810
+ # ============================================================
3811
+ # RUNTIME LOG — END
3812
+ # ============================================================
3813
+ # Purpose:
3814
+ # Finalize the Step 3 runtime log after all requested
3815
+ # uncorrelated random-slope analyses have completed.
3816
+ #
3817
+ # Records:
3818
+ # - Analysis completion timestamp
3819
+ # - R session information
3820
+ #
3821
+ # Cleanup:
3822
+ # - Close the message sink
3823
+ # - Close the standard-output sink
3824
+ # - Close the runtime-log file connection
3825
+ #
3826
+ # Safety:
3827
+ # Sink and connection states are checked before closing so
3828
+ # this cell can be rerun without unnecessarily attempting
3829
+ # to close inactive sinks or an already-closed connection.
3830
+ # ============================================================
3831
+
3832
+
3833
+ # ------------------------------------------------------------
3834
+ # 1. Record Analysis Completion
3835
+ # ------------------------------------------------------------
3836
+
3837
+ cat(
3838
+ paste0(
3839
+ "\n",
3840
+ strrep("=", 80), "\n",
3841
+ "STEP 3 — UNCORRELATED RANDOM-SLOPE ANALYSIS COMPLETED\n",
3842
+ "Dataset: Affective Provo\n",
3843
+ "Finished: ",
3844
+ format(
3845
+ Sys.time(),
3846
+ "%Y-%m-%d %H:%M:%S"
3847
+ ),
3848
+ "\n",
3849
+ strrep("=", 80), "\n\n"
3850
+ )
3851
+ )
3852
+
3853
+
3854
+ # ------------------------------------------------------------
3855
+ # 2. Record R Session Information
3856
+ # ------------------------------------------------------------
3857
+
3858
+ cat("SESSION INFORMATION\n")
3859
+ cat(strrep("-", 80), "\n")
3860
+
3861
+ print(sessionInfo())
3862
+
3863
+ cat(
3864
+ "\n",
3865
+ strrep("=", 80), "\n",
3866
+ "END OF RUNTIME LOG\n",
3867
+ strrep("=", 80), "\n"
3868
+ )
3869
+
3870
+
3871
+ # ------------------------------------------------------------
3872
+ # 3. Flush Runtime-Log Connection
3873
+ # ------------------------------------------------------------
3874
+ # Push any buffered output to disk before sinks are closed.
3875
+ # ------------------------------------------------------------
3876
+
3877
+ if (exists("log_con") && isOpen(log_con)) {
3878
+ flush(log_con)
3879
+ }
3880
+
3881
+
3882
+ # ------------------------------------------------------------
3883
+ # 4. Close Message Sink
3884
+ # ------------------------------------------------------------
3885
+ # Message output was redirected separately using:
3886
+ # sink(log_con, type = "message")
3887
+ # ------------------------------------------------------------
3888
+
3889
+ if (sink.number(type = "message") > 0) {
3890
+ sink(type = "message")
3891
+ }
3892
+
3893
+
3894
+ # ------------------------------------------------------------
3895
+ # 5. Close Standard-Output Sink
3896
+ # ------------------------------------------------------------
3897
+ # Standard output was redirected using:
3898
+ # sink(log_con, split = TRUE)
3899
+ # ------------------------------------------------------------
3900
+
3901
+ if (sink.number(type = "output") > 0) {
3902
+ sink(type = "output")
3903
+ }
3904
+
3905
+
3906
+ # ------------------------------------------------------------
3907
+ # 6. Close Runtime-Log Connection
3908
+ # ------------------------------------------------------------
3909
+
3910
+ if (exists("log_con") && isOpen(log_con)) {
3911
+ close(log_con)
3912
+ }
3913
+
3914
+
3915
+ # ------------------------------------------------------------
3916
+ # 7. Confirm Successful Log Export
3917
+ # ------------------------------------------------------------
3918
+ # This message is intentionally emitted AFTER the sinks have
3919
+ # been closed, so it appears only in the active R console.
3920
+ # ------------------------------------------------------------
3921
+
3922
+ message(
3923
+ "Runtime log saved successfully: ",
3924
+ LOG_PATH
3925
+ )
05-Research_Program-Affective_Provo/01-Fixation_Duration_Research/01-LME_Model_Structure/01-Scripts/Step-4-Merging_Results_of_Correlated+Uncorrelated_Slopes.R ADDED
@@ -0,0 +1,2336 @@
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # COPYRIGHT, LICENSING, AND SCHOLARLY CITATION
3
+ # ============================================================
4
+ # Copyright (c) 2026 Mohit Gupta
5
+ # License: MIT
6
+ # SPDX-License-Identifier: MIT
7
+ #
8
+ # This script contains original computational software
9
+ # developed by Mohit Gupta for the AffLex-Provo
10
+ # Research Program.
11
+ #
12
+ # Citation:
13
+ # Researchers using this software in published research
14
+ # are strongly requested to cite the AffLex-Provo repository:
15
+ # https://huggingface.co/datasets/mohitg2/AffLex-Provo
16
+ #
17
+ # Third-party datasets and externally sourced materials
18
+ # remain subject to their respective original licenses.
19
+ #
20
+ # See the applicable repository LICENSE file for the
21
+ # complete MIT License terms.
22
+ # ============================================================
23
+
24
+ # ============================================================
25
+ # STEP 4 — MERGE, COMPARE, SORT, REORDER, AND FORMAT (Affective Provo)
26
+ # ============================================================
27
+ #
28
+ #
29
+ # REQUIRED R VERSION: R version 4.5.2 (2025-10-31)
30
+ #
31
+ #
32
+ # Purpose:
33
+ # Merge the Step 2 correlated and Step 3 uncorrelated
34
+ # random-slope results across all four duration-based reading
35
+ # measures into one consolidated result table.
36
+ #
37
+ # Inputs:
38
+ # Step 2:
39
+ # Correlated random-slope candidate rankings
40
+ #
41
+ # Step 3:
42
+ # Uncorrelated random-slope candidate rankings
43
+ #
44
+ # Reading measures:
45
+ # 1. First Fixation Duration (FFD)
46
+ # 2. Gaze Duration / First-Run Dwell Time (GD)
47
+ # 3. Regression Path Duration / Go-Past Time (GPT)
48
+ # 4. Total Dwell Time / Total Reading Time (TDT)
49
+ #
50
+ # Workflow:
51
+ # 1. Locate Step 2 and Step 3 result workbooks.
52
+ # 2. Read the ranking sheet from each workbook.
53
+ # 3. Tag each result with:
54
+ # - Stage of Reading
55
+ # - Reading Measure
56
+ # - Dependent Variable Name
57
+ # - Random-Slope Structure
58
+ # 4. Combine correlated and uncorrelated candidate models.
59
+ # 5. Recalculate AIC/BIC differences across the combined
60
+ # candidate set within each DV.
61
+ # 6. Preserve convergence/singularity-based selection
62
+ # eligibility from Steps 2 and 3.
63
+ # 7. Order selection-eligible models first and then by BIC.
64
+ # 8. Export the consolidated results to Excel.
65
+ #
66
+ # Dataset:
67
+ # Affective Provo
68
+ #
69
+ # Input / Output Directory:
70
+ #
71
+ # 05-Research_Program-Affective_Provo/
72
+ # 01-Fixation_Duration_Research/
73
+ # 01-LME_Model_Structure/
74
+ # 02-Results/
75
+ #
76
+ # Important:
77
+ # Step 2 and Step 3 intentionally use the same results
78
+ # directory. Their files are distinguished by:
79
+ #
80
+ # Step-2-* → correlated random slopes
81
+ # Step-3-* → uncorrelated random slopes
82
+ #
83
+ # Step 4 reads both model families from the same directory
84
+ # and compares them within each duration DV.
85
+ #
86
+ # Information criteria are comparable within each DV because
87
+ # the corresponding Step 2 and Step 3 models use:
88
+ #
89
+ # - the same source dataset
90
+ # - the same DV-specific filtering
91
+ # - the same predictor standardization procedure
92
+ # - the same fixed-effects specification
93
+ # - the same observations
94
+ # - REML estimation
95
+ #
96
+ # The random-intercept-only candidate is shared across the
97
+ # parameterization families and is represented once. Models
98
+ # containing participant-level random slopes are compared under
99
+ # correlated and uncorrelated parameterizations.
100
+ # ============================================================
101
+
102
+
103
+
104
+ # ============================================================
105
+ # CELL 1 — PACKAGE INSTALLATION AND INITIALIZATION
106
+ # ============================================================
107
+
108
+ REQUIRED_PACKAGES <- c(
109
+ "readxl",
110
+ "openxlsx",
111
+ "dplyr",
112
+ "stringr",
113
+ "here"
114
+ )
115
+
116
+
117
+ # ------------------------------------------------------------
118
+ # 1.1 Identify Missing Packages
119
+ # ------------------------------------------------------------
120
+
121
+ MISSING_PACKAGES <- REQUIRED_PACKAGES[
122
+ !vapply(
123
+ REQUIRED_PACKAGES,
124
+ requireNamespace,
125
+ quietly = TRUE,
126
+ FUN.VALUE = logical(1)
127
+ )
128
+ ]
129
+
130
+
131
+ # ------------------------------------------------------------
132
+ # 1.2 Install Missing Packages
133
+ # ------------------------------------------------------------
134
+
135
+ if (length(MISSING_PACKAGES) > 0) {
136
+
137
+ message(
138
+ "Installing missing package(s): ",
139
+ paste(MISSING_PACKAGES, collapse = ", ")
140
+ )
141
+
142
+ install.packages(
143
+ MISSING_PACKAGES,
144
+ repos = "https://cloud.r-project.org",
145
+ dependencies = TRUE
146
+ )
147
+
148
+ } else {
149
+
150
+ message("All required packages are already installed.")
151
+ }
152
+
153
+
154
+ # ------------------------------------------------------------
155
+ # 1.3 Load Required Packages
156
+ # ------------------------------------------------------------
157
+
158
+ suppressPackageStartupMessages({
159
+
160
+ library(readxl)
161
+ library(openxlsx)
162
+
163
+ library(dplyr)
164
+ library(stringr)
165
+
166
+ library(here)
167
+ })
168
+
169
+
170
+ message(
171
+ "Package initialization complete: ",
172
+ length(REQUIRED_PACKAGES),
173
+ " required packages available."
174
+ )
175
+
176
+
177
+
178
+
179
+
180
+ # ============================================================
181
+ # CELL 2 — PROJECT PATHS
182
+ # ============================================================
183
+ # Purpose:
184
+ # Define the shared Step 2 / Step 3 results directory and
185
+ # the Step 4 merged-result output path.
186
+ # ============================================================
187
+
188
+ PROJECT_ROOT <- here()
189
+
190
+
191
+ RESULTS_DIR <- here(
192
+ "05-Research_Program-Affective_Provo",
193
+ "01-Fixation_Duration_Research",
194
+ "01-LME_Model_Structure",
195
+ "02-Results"
196
+ )
197
+
198
+
199
+ # ------------------------------------------------------------
200
+ # 2.1 Validate Results Directory
201
+ # ------------------------------------------------------------
202
+
203
+ if (!dir.exists(RESULTS_DIR)) {
204
+
205
+ stop(
206
+ "Results directory not found: ",
207
+ RESULTS_DIR
208
+ )
209
+ }
210
+
211
+
212
+ # ------------------------------------------------------------
213
+ # 2.2 Define Step 4 Output File
214
+ # ------------------------------------------------------------
215
+
216
+ MERGED_OUTPUT_PATH <- file.path(
217
+ RESULTS_DIR,
218
+ "Step-4_Merged_Correlated-Uncorrelated_Slopes_Affective_Provo.xlsx"
219
+ )
220
+
221
+
222
+ # ------------------------------------------------------------
223
+ # 2.3 Report Resolved Paths
224
+ # ------------------------------------------------------------
225
+
226
+ message("PROJECT_ROOT: ", PROJECT_ROOT)
227
+ message("RESULTS_DIR: ", RESULTS_DIR)
228
+ message("MERGED_OUTPUT_PATH: ", MERGED_OUTPUT_PATH)
229
+
230
+
231
+
232
+
233
+
234
+ # ============================================================
235
+ # CELL 3 — DV REGISTRY
236
+ # ============================================================
237
+ # Purpose:
238
+ # Define the four duration DVs and the metadata required to
239
+ # construct Step 2 and Step 3 filenames deterministically.
240
+ # ============================================================
241
+
242
+ DV_INFO <- list(
243
+
244
+ IA_FIRST_FIXATION_DURATION = list(
245
+ serial = 1,
246
+ suffix = "FFD",
247
+ measure = "First Fixation Duration"
248
+ ),
249
+
250
+ IA_FIRST_RUN_DWELL_TIME = list(
251
+ serial = 2,
252
+ suffix = "GD",
253
+ measure = "Gaze Duration"
254
+ ),
255
+
256
+ IA_REGRESSION_PATH_DURATION = list(
257
+ serial = 3,
258
+ suffix = "GPT",
259
+ measure = "Regression Path Duration"
260
+ ),
261
+
262
+ IA_DWELL_TIME = list(
263
+ serial = 4,
264
+ suffix = "TDT",
265
+ measure = "Total Dwell Time"
266
+ )
267
+ )
268
+
269
+
270
+
271
+
272
+
273
+ # ============================================================
274
+ # CELL 4 — RESULT-WORKBOOK READER
275
+ # ============================================================
276
+ # Purpose:
277
+ # Read one Step 2 or Step 3 ranking workbook, validate its
278
+ # required columns, normalize model diagnostics, verify
279
+ # selection eligibility, and attach Step 4 comparison
280
+ # metadata.
281
+ #
282
+ # Required ranking columns:
283
+ # candidate
284
+ # aic
285
+ # bic
286
+ # converged
287
+ # singular
288
+ # nobs
289
+ #
290
+ # Expected selection column:
291
+ # selection_eligible
292
+ #
293
+ # If selection_eligible is absent, it is reconstructed using:
294
+ #
295
+ # converged = TRUE
296
+ # singular = FALSE
297
+ #
298
+ # Important:
299
+ # Steps 2 and 3 construct worksheet names using:
300
+ #
301
+ # safe_sheet_name(paste0(dv, "_ranking"))
302
+ #
303
+ # Because Excel limits worksheet names to 31 characters,
304
+ # long DV names may truncate part or all of the "_ranking"
305
+ # suffix. Step 4 therefore reconstructs the exact expected
306
+ # worksheet name rather than searching for the literal word
307
+ # "ranking".
308
+ #
309
+ # Safety:
310
+ # - Missing files cause an explicit failure.
311
+ # - Invalid structure-type arguments cause an explicit failure.
312
+ # - Missing expected ranking sheets cause an explicit failure.
313
+ # - Empty ranking sheets cause an explicit failure.
314
+ # - Missing required ranking columns cause an explicit failure.
315
+ # - Invalid or non-finite AIC/BIC values cause an explicit
316
+ # failure.
317
+ # - Missing convergence/singularity diagnostics cause an
318
+ # explicit failure.
319
+ # - Invalid logical diagnostic values cause an explicit
320
+ # failure.
321
+ # - Exported selection eligibility is independently checked
322
+ # against convergence and singularity.
323
+ # ============================================================
324
+
325
+
326
+ # ------------------------------------------------------------
327
+ # 4.0 Excel Sheet-Name Sanitizer
328
+ # ------------------------------------------------------------
329
+ # Must match the naming rule used by Steps 2 and 3.
330
+ # ------------------------------------------------------------
331
+
332
+ safe_sheet_name <- function(name) {
333
+
334
+ name <- str_replace_all(
335
+ name,
336
+ "[\\\\/*\\[\\]:?]",
337
+ "_"
338
+ )
339
+
340
+ str_sub(
341
+ name,
342
+ 1,
343
+ 31
344
+ )
345
+ }
346
+
347
+
348
+ # ------------------------------------------------------------
349
+ # 4.1 Logical-Value Normalization Helper
350
+ # ------------------------------------------------------------
351
+
352
+ normalize_logical <- function(x) {
353
+
354
+ if (is.logical(x)) {
355
+ return(x)
356
+ }
357
+
358
+ x_chr <- toupper(
359
+ trimws(
360
+ as.character(x)
361
+ )
362
+ )
363
+
364
+ out <- rep(
365
+ NA,
366
+ length(x_chr)
367
+ )
368
+
369
+ out[
370
+ x_chr %in% c(
371
+ "TRUE",
372
+ "T",
373
+ "1"
374
+ )
375
+ ] <- TRUE
376
+
377
+ out[
378
+ x_chr %in% c(
379
+ "FALSE",
380
+ "F",
381
+ "0"
382
+ )
383
+ ] <- FALSE
384
+
385
+ out
386
+ }
387
+
388
+
389
+ # ------------------------------------------------------------
390
+ # 4.2 Result-Workbook Reader
391
+ # ------------------------------------------------------------
392
+
393
+ read_and_tag <- function(
394
+ path,
395
+ structure_type,
396
+ serial,
397
+ suffix,
398
+ measure,
399
+ dv_name
400
+ ) {
401
+
402
+
403
+ # ----------------------------------------------------------
404
+ # 4.2.1 Validate Input File
405
+ # ----------------------------------------------------------
406
+
407
+ if (!file.exists(path)) {
408
+
409
+ stop(
410
+ "Required Step 4 input file not found: ",
411
+ path
412
+ )
413
+ }
414
+
415
+
416
+ # ----------------------------------------------------------
417
+ # 4.2.2 Validate Structure-Type Argument
418
+ # ----------------------------------------------------------
419
+
420
+ if (
421
+ !structure_type %in% c(
422
+ "Correlated",
423
+ "Uncorrelated"
424
+ )
425
+ ) {
426
+
427
+ stop(
428
+ "Invalid structure_type supplied to read_and_tag(): ",
429
+ structure_type
430
+ )
431
+ }
432
+
433
+
434
+ # ----------------------------------------------------------
435
+ # 4.2.3 Locate Exact Ranking Sheet
436
+ # ----------------------------------------------------------
437
+
438
+ sheet_names <- getSheetNames(
439
+ path
440
+ )
441
+
442
+ expected_ranking_sheet <- safe_sheet_name(
443
+ paste0(
444
+ dv_name,
445
+ "_ranking"
446
+ )
447
+ )
448
+
449
+ if (
450
+ !expected_ranking_sheet %in%
451
+ sheet_names
452
+ ) {
453
+
454
+ stop(
455
+ "Expected ranking sheet not found in ",
456
+ basename(path),
457
+ ".\n",
458
+ "Expected sheet: ",
459
+ expected_ranking_sheet,
460
+ "\n",
461
+ "Available sheets: ",
462
+ paste(
463
+ sheet_names,
464
+ collapse = ", "
465
+ )
466
+ )
467
+ }
468
+
469
+ sheet_name <- expected_ranking_sheet
470
+
471
+
472
+ # ----------------------------------------------------------
473
+ # 4.2.4 Read Ranking Results
474
+ # ----------------------------------------------------------
475
+
476
+ result_df <- read_excel(
477
+ path,
478
+ sheet = sheet_name
479
+ )
480
+
481
+ if (nrow(result_df) == 0) {
482
+
483
+ stop(
484
+ "Ranking sheet contains no candidate models: ",
485
+ basename(path)
486
+ )
487
+ }
488
+
489
+
490
+ # ----------------------------------------------------------
491
+ # 4.2.5 Validate Required Ranking Columns
492
+ # ----------------------------------------------------------
493
+
494
+ required_result_cols <- c(
495
+ "candidate",
496
+ "aic",
497
+ "bic",
498
+ "converged",
499
+ "singular",
500
+ "nobs"
501
+ )
502
+
503
+ missing_result_cols <- setdiff(
504
+ required_result_cols,
505
+ names(result_df)
506
+ )
507
+
508
+ if (length(missing_result_cols) > 0) {
509
+
510
+ stop(
511
+ "Missing required ranking column(s) in ",
512
+ basename(path),
513
+ ": ",
514
+ paste(
515
+ missing_result_cols,
516
+ collapse = ", "
517
+ )
518
+ )
519
+ }
520
+
521
+
522
+ # ----------------------------------------------------------
523
+ # 4.2.6 Validate Candidate Identifiers
524
+ # ----------------------------------------------------------
525
+
526
+ result_df$candidate <- trimws(
527
+ as.character(
528
+ result_df$candidate
529
+ )
530
+ )
531
+
532
+ if (
533
+ anyNA(result_df$candidate) ||
534
+ any(result_df$candidate == "")
535
+ ) {
536
+
537
+ stop(
538
+ "Missing or empty candidate identifier(s) detected in ",
539
+ basename(path),
540
+ "."
541
+ )
542
+ }
543
+
544
+
545
+ # ----------------------------------------------------------
546
+ # 4.2.7 Coerce Information Criteria to Numeric
547
+ # ----------------------------------------------------------
548
+
549
+ result_df <- result_df %>%
550
+ mutate(
551
+ aic = suppressWarnings(
552
+ as.numeric(aic)
553
+ ),
554
+ bic = suppressWarnings(
555
+ as.numeric(bic)
556
+ )
557
+ )
558
+
559
+
560
+ # ----------------------------------------------------------
561
+ # 4.2.8 Validate Information Criteria
562
+ # ----------------------------------------------------------
563
+
564
+ if (
565
+ any(!is.finite(result_df$aic)) ||
566
+ any(!is.finite(result_df$bic))
567
+ ) {
568
+
569
+ stop(
570
+ "Missing, invalid, or non-finite AIC/BIC values detected ",
571
+ "in ranking sheet: ",
572
+ basename(path)
573
+ )
574
+ }
575
+
576
+
577
+ # ----------------------------------------------------------
578
+ # 4.2.9 Normalize Core Diagnostic Columns
579
+ # ----------------------------------------------------------
580
+
581
+ result_df$converged <- normalize_logical(
582
+ result_df$converged
583
+ )
584
+
585
+ result_df$singular <- normalize_logical(
586
+ result_df$singular
587
+ )
588
+
589
+
590
+ # ----------------------------------------------------------
591
+ # 4.2.10 Reject Missing / Invalid Core Diagnostics
592
+ # ----------------------------------------------------------
593
+
594
+ if (anyNA(result_df$converged)) {
595
+
596
+ stop(
597
+ "Missing or invalid logical value(s) detected in ",
598
+ "'converged' in ",
599
+ basename(path),
600
+ ". Accepted values are TRUE/FALSE, T/F, or 1/0."
601
+ )
602
+ }
603
+
604
+ if (anyNA(result_df$singular)) {
605
+
606
+ stop(
607
+ "Missing or invalid logical value(s) detected in ",
608
+ "'singular' in ",
609
+ basename(path),
610
+ ". Accepted values are TRUE/FALSE, T/F, or 1/0."
611
+ )
612
+ }
613
+
614
+
615
+ # ----------------------------------------------------------
616
+ # 4.2.11 Normalize or Reconstruct Selection Eligibility
617
+ # ----------------------------------------------------------
618
+
619
+ if ("selection_eligible" %in% names(result_df)) {
620
+
621
+ result_df$selection_eligible <- normalize_logical(
622
+ result_df$selection_eligible
623
+ )
624
+
625
+ if (anyNA(result_df$selection_eligible)) {
626
+
627
+ stop(
628
+ "Missing or invalid logical value(s) detected in ",
629
+ "'selection_eligible' in ",
630
+ basename(path),
631
+ ". Accepted values are TRUE/FALSE, T/F, or 1/0."
632
+ )
633
+ }
634
+
635
+ } else {
636
+
637
+ warning(
638
+ "selection_eligible missing from ",
639
+ basename(path),
640
+ "; reconstructing it from converged and singular."
641
+ )
642
+
643
+ result_df <- result_df %>%
644
+ mutate(
645
+ selection_eligible =
646
+ converged %in% TRUE &
647
+ singular %in% FALSE
648
+ )
649
+ }
650
+
651
+
652
+ # ----------------------------------------------------------
653
+ # 4.2.12 Independently Verify Selection Eligibility
654
+ # ----------------------------------------------------------
655
+
656
+ expected_eligibility <- (
657
+ result_df$converged %in% TRUE &
658
+ result_df$singular %in% FALSE
659
+ )
660
+
661
+ eligibility_mismatch <- which(
662
+ is.na(result_df$selection_eligible) |
663
+ result_df$selection_eligible !=
664
+ expected_eligibility
665
+ )
666
+
667
+ if (length(eligibility_mismatch) > 0) {
668
+
669
+ stop(
670
+ "selection_eligible is inconsistent with converged / ",
671
+ "singular for ",
672
+ length(eligibility_mismatch),
673
+ " candidate(s) in ",
674
+ basename(path),
675
+ ". Step 4 comparison stopped."
676
+ )
677
+ }
678
+
679
+
680
+ # ----------------------------------------------------------
681
+ # 4.2.13 Add Step 4 Metadata
682
+ # ----------------------------------------------------------
683
+
684
+ result_df <- result_df %>%
685
+ mutate(
686
+ `Stage of Reading` = serial,
687
+ `Reading Measure` = measure,
688
+ `Measure Abbreviation` = suffix,
689
+ `Dependent Variable Name` = dv_name,
690
+ `Random-Slope Structure` = structure_type,
691
+ `Source Step` = ifelse(
692
+ structure_type == "Correlated",
693
+ "Step 2",
694
+ "Step 3"
695
+ ),
696
+ `Source Workbook` = basename(path)
697
+ )
698
+
699
+
700
+ # ----------------------------------------------------------
701
+ # 4.2.14 Return Validated Ranking Table
702
+ # ----------------------------------------------------------
703
+
704
+ result_df
705
+ }
706
+
707
+
708
+
709
+
710
+ # ============================================================
711
+ # CELL 5 — READ STEP 2 AND STEP 3 RESULTS
712
+ # ============================================================
713
+ # Purpose:
714
+ # Read the correlated and uncorrelated ranking workbook for
715
+ # each duration DV and combine all available model candidates
716
+ # into one master container.
717
+ #
718
+ # Expected filenames:
719
+ #
720
+ # Step 2:
721
+ # Step-2-1_FFD_CorrelatedSlopes_Affective_Provo.xlsx
722
+ # Step-2-2_GD_CorrelatedSlopes_Affective_Provo.xlsx
723
+ # Step-2-3_GPT_CorrelatedSlopes_Affective_Provo.xlsx
724
+ # Step-2-4_TDT_CorrelatedSlopes_Affective_Provo.xlsx
725
+ #
726
+ # Step 3:
727
+ # Step-3-1_FFD_UncorrelatedSlopes_Affective_Provo.xlsx
728
+ # Step-3-2_GD_UncorrelatedSlopes_Affective_Provo.xlsx
729
+ # Step-3-3_GPT_UncorrelatedSlopes_Affective_Provo.xlsx
730
+ # Step-3-4_TDT_UncorrelatedSlopes_Affective_Provo.xlsx
731
+ # ============================================================
732
+
733
+ master_df <- list()
734
+
735
+
736
+ message(
737
+ "\n",
738
+ strrep("=", 80)
739
+ )
740
+
741
+ message(
742
+ "STARTING STEP 4 — MERGING CORRELATED AND UNCORRELATED RESULTS"
743
+ )
744
+
745
+ message(
746
+ "Dataset: Affective Provo"
747
+ )
748
+
749
+ message(
750
+ strrep("=", 80)
751
+ )
752
+
753
+
754
+ for (dv_name in names(DV_INFO)) {
755
+
756
+
757
+ # ----------------------------------------------------------
758
+ # 5.1 Retrieve DV Metadata
759
+ # ----------------------------------------------------------
760
+
761
+ serial <- DV_INFO[[dv_name]]$serial
762
+ suffix <- DV_INFO[[dv_name]]$suffix
763
+ measure <- DV_INFO[[dv_name]]$measure
764
+
765
+
766
+ # ----------------------------------------------------------
767
+ # 5.2 Construct Step 2 Filename
768
+ # ----------------------------------------------------------
769
+
770
+ f_corr <- paste0(
771
+ "Step-2-",
772
+ serial,
773
+ "_",
774
+ suffix,
775
+ "_CorrelatedSlopes_Affective_Provo.xlsx"
776
+ )
777
+
778
+
779
+ # ----------------------------------------------------------
780
+ # 5.3 Construct Step 3 Filename
781
+ # ----------------------------------------------------------
782
+
783
+ f_uncorr <- paste0(
784
+ "Step-3-",
785
+ serial,
786
+ "_",
787
+ suffix,
788
+ "_UncorrelatedSlopes_Affective_Provo.xlsx"
789
+ )
790
+
791
+
792
+ path_corr <- file.path(
793
+ RESULTS_DIR,
794
+ f_corr
795
+ )
796
+
797
+ path_uncorr <- file.path(
798
+ RESULTS_DIR,
799
+ f_uncorr
800
+ )
801
+
802
+
803
+ # ----------------------------------------------------------
804
+ # 5.4 Read Correlated Results
805
+ # ----------------------------------------------------------
806
+
807
+ df_corr <- read_and_tag(
808
+ path = path_corr,
809
+ structure_type = "Correlated",
810
+ serial = serial,
811
+ suffix = suffix,
812
+ measure = measure,
813
+ dv_name = dv_name
814
+ )
815
+
816
+
817
+ # ----------------------------------------------------------
818
+ # 5.5 Read Uncorrelated Results
819
+ # ----------------------------------------------------------
820
+
821
+ df_uncorr <- read_and_tag(
822
+ path = path_uncorr,
823
+ structure_type = "Uncorrelated",
824
+ serial = serial,
825
+ suffix = suffix,
826
+ measure = measure,
827
+ dv_name = dv_name
828
+ )
829
+
830
+
831
+ # ----------------------------------------------------------
832
+ # 5.6 Store Results
833
+ # ----------------------------------------------------------
834
+
835
+ master_df[[paste0(
836
+ dv_name,
837
+ "_Correlated"
838
+ )]] <- df_corr
839
+
840
+ master_df[[paste0(
841
+ dv_name,
842
+ "_Uncorrelated"
843
+ )]] <- df_uncorr
844
+
845
+
846
+ message(
847
+ "Processed Stage ",
848
+ serial,
849
+ " — ",
850
+ suffix,
851
+ " — ",
852
+ dv_name
853
+ )
854
+ }
855
+
856
+
857
+
858
+
859
+
860
+ # ============================================================
861
+ # CELL 6 — MERGE AND RECALCULATE COMBINED MODEL COMPARISONS
862
+ # ============================================================
863
+ # Purpose:
864
+ # Combine the Step 2 and Step 3 candidate rankings and
865
+ # calculate information-criterion differences across both
866
+ # participant-level random-slope parameterizations within
867
+ # each DV.
868
+ #
869
+ # Affective Provo candidate space:
870
+ #
871
+ # Six possible participant-level random slopes:
872
+ #
873
+ # Length
874
+ # Predictability
875
+ # Frequency
876
+ # Valence
877
+ # Arousal
878
+ # Dominance
879
+ #
880
+ # Correlated family:
881
+ #
882
+ # 2^6 = 64 candidate structures
883
+ #
884
+ # This includes the random-intercept-only structure:
885
+ #
886
+ # 1
887
+ #
888
+ # Uncorrelated family:
889
+ #
890
+ # 2^6 - 1 = 63 candidate structures
891
+ #
892
+ # The random-intercept-only structure is not duplicated in
893
+ # the uncorrelated family because, in the absence of random
894
+ # slopes, there are no intercept-slope or slope-slope
895
+ # correlation parameters to remove.
896
+ #
897
+ # Therefore, each DV contains:
898
+ #
899
+ # 64 correlated-family candidates
900
+ # 63 uncorrelated-family candidates
901
+ # 127 unique combined candidates
902
+ #
903
+ # Across four duration DVs:
904
+ #
905
+ # 4 × 127 = 508 combined candidate rows
906
+ #
907
+ # Important distinction:
908
+ #
909
+ # delta_aic / delta_bic
910
+ # → source Step 2 / Step 3 within-family differences.
911
+ #
912
+ # combined_delta_aic / combined_delta_bic
913
+ # → differences across the complete unique Step 4
914
+ # candidate set for the current DV.
915
+ #
916
+ # eligible_delta_aic / eligible_delta_bic
917
+ # → differences relative to the best selection-eligible
918
+ # candidate for the current DV.
919
+ #
920
+ # Primary selection rule:
921
+ #
922
+ # 1. Candidate must satisfy:
923
+ #
924
+ # converged = TRUE
925
+ # singular = FALSE
926
+ #
927
+ # 2. Among eligible candidates, lower BIC is preferred.
928
+ # ============================================================
929
+
930
+ message(
931
+ "\nMerging candidate tables and recalculating combined deltas..."
932
+ )
933
+
934
+
935
+ # ------------------------------------------------------------
936
+ # 6.1 Safety Check
937
+ # ------------------------------------------------------------
938
+
939
+ if (length(master_df) == 0) {
940
+
941
+ stop(
942
+ "No Step 2 or Step 3 ranking results were loaded."
943
+ )
944
+ }
945
+
946
+
947
+ # ------------------------------------------------------------
948
+ # 6.2 Combine All Candidate Tables
949
+ # ------------------------------------------------------------
950
+
951
+ final_df <- bind_rows(
952
+ master_df
953
+ )
954
+
955
+
956
+ # ------------------------------------------------------------
957
+ # 6.3 Verify Both Structure Families Exist for Every DV
958
+ # ------------------------------------------------------------
959
+
960
+ structure_check <- final_df %>%
961
+ distinct(
962
+ `Dependent Variable Name`,
963
+ `Random-Slope Structure`
964
+ ) %>%
965
+ count(
966
+ `Dependent Variable Name`,
967
+ name = "N_Structure_Types"
968
+ )
969
+
970
+
971
+ if (
972
+ any(
973
+ structure_check$N_Structure_Types != 2
974
+ )
975
+ ) {
976
+
977
+ print(
978
+ structure_check
979
+ )
980
+
981
+ stop(
982
+ "At least one DV does not contain both correlated and ",
983
+ "uncorrelated random-slope results. Step 4 requires both ",
984
+ "model families before combined comparison can proceed."
985
+ )
986
+ }
987
+
988
+
989
+ message(
990
+ "Structure-family validation passed: correlated and ",
991
+ "uncorrelated results are present for every DV."
992
+ )
993
+
994
+
995
+ # ------------------------------------------------------------
996
+ # 6.3A Define Expected Affective Provo Candidate Structures
997
+ # ------------------------------------------------------------
998
+
999
+ AFFECTIVE_SLOPES <- c(
1000
+ "Length",
1001
+ "Predictability",
1002
+ "Frequency",
1003
+ "Valence",
1004
+ "Arousal",
1005
+ "Dominance"
1006
+ )
1007
+
1008
+
1009
+ generate_expected_candidates <- function(
1010
+ slope_vars
1011
+ ) {
1012
+
1013
+ candidates <- "1"
1014
+
1015
+ if (length(slope_vars) == 0) {
1016
+ return(candidates)
1017
+ }
1018
+
1019
+ for (r in seq_along(slope_vars)) {
1020
+
1021
+ combinations <- combn(
1022
+ slope_vars,
1023
+ r,
1024
+ simplify = FALSE
1025
+ )
1026
+
1027
+ candidates <- c(
1028
+ candidates,
1029
+ vapply(
1030
+ combinations,
1031
+ function(x) {
1032
+ paste(
1033
+ "1 +",
1034
+ paste(
1035
+ x,
1036
+ collapse = " + "
1037
+ )
1038
+ )
1039
+ },
1040
+ character(1)
1041
+ )
1042
+ )
1043
+ }
1044
+
1045
+ unique(
1046
+ candidates
1047
+ )
1048
+ }
1049
+
1050
+
1051
+ EXPECTED_CORRELATED_STRUCTURES <- (
1052
+ generate_expected_candidates(
1053
+ AFFECTIVE_SLOPES
1054
+ )
1055
+ )
1056
+
1057
+
1058
+ EXPECTED_UNCORRELATED_STRUCTURES <- setdiff(
1059
+ EXPECTED_CORRELATED_STRUCTURES,
1060
+ "1"
1061
+ )
1062
+
1063
+
1064
+ EXPECTED_CORRELATED_CANDIDATES <- length(
1065
+ EXPECTED_CORRELATED_STRUCTURES
1066
+ )
1067
+
1068
+
1069
+ EXPECTED_UNCORRELATED_CANDIDATES <- length(
1070
+ EXPECTED_UNCORRELATED_STRUCTURES
1071
+ )
1072
+
1073
+
1074
+ EXPECTED_CANDIDATES_PER_DV <- (
1075
+ EXPECTED_CORRELATED_CANDIDATES +
1076
+ EXPECTED_UNCORRELATED_CANDIDATES
1077
+ )
1078
+
1079
+
1080
+ EXPECTED_TOTAL_CANDIDATES <- (
1081
+ length(DV_INFO) *
1082
+ EXPECTED_CANDIDATES_PER_DV
1083
+ )
1084
+
1085
+
1086
+ # ------------------------------------------------------------
1087
+ # Validate Theoretical Candidate Counts
1088
+ # ------------------------------------------------------------
1089
+
1090
+ if (EXPECTED_CORRELATED_CANDIDATES != 64) {
1091
+
1092
+ stop(
1093
+ "Internal candidate-generation error: expected 64 ",
1094
+ "correlated Affective Provo structures but generated ",
1095
+ EXPECTED_CORRELATED_CANDIDATES,
1096
+ "."
1097
+ )
1098
+ }
1099
+
1100
+
1101
+ if (EXPECTED_UNCORRELATED_CANDIDATES != 63) {
1102
+
1103
+ stop(
1104
+ "Internal candidate-generation error: expected 63 ",
1105
+ "uncorrelated Affective Provo structures but generated ",
1106
+ EXPECTED_UNCORRELATED_CANDIDATES,
1107
+ "."
1108
+ )
1109
+ }
1110
+
1111
+
1112
+ if (EXPECTED_CANDIDATES_PER_DV != 127) {
1113
+
1114
+ stop(
1115
+ "Internal candidate-generation error: expected 127 ",
1116
+ "unique combined structures per DV but generated ",
1117
+ EXPECTED_CANDIDATES_PER_DV,
1118
+ "."
1119
+ )
1120
+ }
1121
+
1122
+
1123
+ # ------------------------------------------------------------
1124
+ # 6.3B Verify Expected Candidate Counts
1125
+ # ------------------------------------------------------------
1126
+
1127
+ candidate_count_check <- final_df %>%
1128
+ count(
1129
+ `Dependent Variable Name`,
1130
+ `Random-Slope Structure`,
1131
+ name = "N_Candidates"
1132
+ )
1133
+
1134
+
1135
+ bad_correlated_counts <- candidate_count_check %>%
1136
+ filter(
1137
+ `Random-Slope Structure` == "Correlated",
1138
+ N_Candidates !=
1139
+ EXPECTED_CORRELATED_CANDIDATES
1140
+ )
1141
+
1142
+
1143
+ bad_uncorrelated_counts <- candidate_count_check %>%
1144
+ filter(
1145
+ `Random-Slope Structure` == "Uncorrelated",
1146
+ N_Candidates !=
1147
+ EXPECTED_UNCORRELATED_CANDIDATES
1148
+ )
1149
+
1150
+
1151
+ if (
1152
+ nrow(bad_correlated_counts) > 0 ||
1153
+ nrow(bad_uncorrelated_counts) > 0
1154
+ ) {
1155
+
1156
+ print(
1157
+ candidate_count_check
1158
+ )
1159
+
1160
+ stop(
1161
+ "Unexpected Step 2 / Step 3 candidate count detected. ",
1162
+ "Each Affective Provo DV should contain exactly ",
1163
+ EXPECTED_CORRELATED_CANDIDATES,
1164
+ " correlated-family candidates and ",
1165
+ EXPECTED_UNCORRELATED_CANDIDATES,
1166
+ " uncorrelated-family candidates."
1167
+ )
1168
+ }
1169
+
1170
+
1171
+ dv_candidate_count_check <- final_df %>%
1172
+ count(
1173
+ `Dependent Variable Name`,
1174
+ name = "N_Combined_Candidates"
1175
+ )
1176
+
1177
+
1178
+ if (
1179
+ any(
1180
+ dv_candidate_count_check$N_Combined_Candidates !=
1181
+ EXPECTED_CANDIDATES_PER_DV
1182
+ )
1183
+ ) {
1184
+
1185
+ print(
1186
+ dv_candidate_count_check
1187
+ )
1188
+
1189
+ stop(
1190
+ "Unexpected combined candidate count detected. ",
1191
+ "Each Affective Provo DV should contain exactly ",
1192
+ EXPECTED_CANDIDATES_PER_DV,
1193
+ " unique correlated + uncorrelated candidate models."
1194
+ )
1195
+ }
1196
+
1197
+
1198
+ if (nrow(final_df) != EXPECTED_TOTAL_CANDIDATES) {
1199
+
1200
+ stop(
1201
+ "Unexpected total number of Step 4 candidate rows. ",
1202
+ "Expected ",
1203
+ EXPECTED_TOTAL_CANDIDATES,
1204
+ " rows across all DVs but found ",
1205
+ nrow(final_df),
1206
+ "."
1207
+ )
1208
+ }
1209
+
1210
+
1211
+ message(
1212
+ "Candidate-count validation passed: ",
1213
+ EXPECTED_CORRELATED_CANDIDATES,
1214
+ " correlated candidates + ",
1215
+ EXPECTED_UNCORRELATED_CANDIDATES,
1216
+ " uncorrelated candidates = ",
1217
+ EXPECTED_CANDIDATES_PER_DV,
1218
+ " unique candidates per DV."
1219
+ )
1220
+
1221
+
1222
+ # ------------------------------------------------------------
1223
+ # 6.3C Verify Exact Candidate Structures Within Each Family
1224
+ # ------------------------------------------------------------
1225
+ # Count validation alone cannot establish that the correct
1226
+ # candidate structures are present.
1227
+ #
1228
+ # Correlated family:
1229
+ # Random-intercept-only structure plus all 63 structures
1230
+ # containing at least one random slope.
1231
+ #
1232
+ # Uncorrelated family:
1233
+ # The same 63 slope-containing structures, without a second
1234
+ # copy of the random-intercept-only structure.
1235
+ # ------------------------------------------------------------
1236
+
1237
+ candidate_structure_errors <- character(0)
1238
+
1239
+
1240
+ for (dv_name in names(DV_INFO)) {
1241
+
1242
+
1243
+ # ----------------------------------------------------------
1244
+ # Correlated Family
1245
+ # ----------------------------------------------------------
1246
+
1247
+ observed_correlated <- final_df %>%
1248
+ filter(
1249
+ `Dependent Variable Name` == dv_name,
1250
+ `Random-Slope Structure` == "Correlated"
1251
+ ) %>%
1252
+ pull(candidate)
1253
+
1254
+
1255
+ duplicate_correlated <- unique(
1256
+ observed_correlated[
1257
+ duplicated(
1258
+ observed_correlated
1259
+ )
1260
+ ]
1261
+ )
1262
+
1263
+
1264
+ missing_correlated <- setdiff(
1265
+ EXPECTED_CORRELATED_STRUCTURES,
1266
+ observed_correlated
1267
+ )
1268
+
1269
+
1270
+ unexpected_correlated <- setdiff(
1271
+ observed_correlated,
1272
+ EXPECTED_CORRELATED_STRUCTURES
1273
+ )
1274
+
1275
+
1276
+ if (
1277
+ length(duplicate_correlated) > 0 ||
1278
+ length(missing_correlated) > 0 ||
1279
+ length(unexpected_correlated) > 0
1280
+ ) {
1281
+
1282
+ candidate_structure_errors <- c(
1283
+ candidate_structure_errors,
1284
+ paste0(
1285
+ dv_name,
1286
+ " / Correlated: ",
1287
+ "duplicates=[",
1288
+ paste(
1289
+ duplicate_correlated,
1290
+ collapse = ", "
1291
+ ),
1292
+ "]; missing=[",
1293
+ paste(
1294
+ missing_correlated,
1295
+ collapse = ", "
1296
+ ),
1297
+ "]; unexpected=[",
1298
+ paste(
1299
+ unexpected_correlated,
1300
+ collapse = ", "
1301
+ ),
1302
+ "]"
1303
+ )
1304
+ )
1305
+ }
1306
+
1307
+
1308
+ # ----------------------------------------------------------
1309
+ # Uncorrelated Family
1310
+ # ----------------------------------------------------------
1311
+
1312
+ observed_uncorrelated <- final_df %>%
1313
+ filter(
1314
+ `Dependent Variable Name` == dv_name,
1315
+ `Random-Slope Structure` == "Uncorrelated"
1316
+ ) %>%
1317
+ pull(candidate)
1318
+
1319
+
1320
+ duplicate_uncorrelated <- unique(
1321
+ observed_uncorrelated[
1322
+ duplicated(
1323
+ observed_uncorrelated
1324
+ )
1325
+ ]
1326
+ )
1327
+
1328
+
1329
+ missing_uncorrelated <- setdiff(
1330
+ EXPECTED_UNCORRELATED_STRUCTURES,
1331
+ observed_uncorrelated
1332
+ )
1333
+
1334
+
1335
+ unexpected_uncorrelated <- setdiff(
1336
+ observed_uncorrelated,
1337
+ EXPECTED_UNCORRELATED_STRUCTURES
1338
+ )
1339
+
1340
+
1341
+ if (
1342
+ length(duplicate_uncorrelated) > 0 ||
1343
+ length(missing_uncorrelated) > 0 ||
1344
+ length(unexpected_uncorrelated) > 0
1345
+ ) {
1346
+
1347
+ candidate_structure_errors <- c(
1348
+ candidate_structure_errors,
1349
+ paste0(
1350
+ dv_name,
1351
+ " / Uncorrelated: ",
1352
+ "duplicates=[",
1353
+ paste(
1354
+ duplicate_uncorrelated,
1355
+ collapse = ", "
1356
+ ),
1357
+ "]; missing=[",
1358
+ paste(
1359
+ missing_uncorrelated,
1360
+ collapse = ", "
1361
+ ),
1362
+ "]; unexpected=[",
1363
+ paste(
1364
+ unexpected_uncorrelated,
1365
+ collapse = ", "
1366
+ ),
1367
+ "]"
1368
+ )
1369
+ )
1370
+ }
1371
+ }
1372
+
1373
+
1374
+ if (length(candidate_structure_errors) > 0) {
1375
+
1376
+ stop(
1377
+ "Candidate-structure validation failed:\n",
1378
+ paste(
1379
+ candidate_structure_errors,
1380
+ collapse = "\n"
1381
+ )
1382
+ )
1383
+ }
1384
+
1385
+
1386
+ message(
1387
+ "Candidate-structure validation passed: each DV contains ",
1388
+ "the expected 64 correlated-family structures and 63 ",
1389
+ "uncorrelated-family structures."
1390
+ )
1391
+
1392
+
1393
+ # ------------------------------------------------------------
1394
+ # 6.3D Verify Relationship Between Structure Families
1395
+ # ------------------------------------------------------------
1396
+ # Every slope-containing correlated candidate must have a
1397
+ # corresponding uncorrelated candidate.
1398
+ #
1399
+ # The only candidate permitted to occur exclusively in the
1400
+ # correlated family is:
1401
+ #
1402
+ # 1
1403
+ #
1404
+ # because the random-intercept-only model has no random-effect
1405
+ # correlation parameters to remove.
1406
+ # ------------------------------------------------------------
1407
+
1408
+ for (dv_name in names(DV_INFO)) {
1409
+
1410
+ corr_candidates <- final_df %>%
1411
+ filter(
1412
+ `Dependent Variable Name` == dv_name,
1413
+ `Random-Slope Structure` == "Correlated"
1414
+ ) %>%
1415
+ pull(candidate)
1416
+
1417
+
1418
+ uncorr_candidates <- final_df %>%
1419
+ filter(
1420
+ `Dependent Variable Name` == dv_name,
1421
+ `Random-Slope Structure` == "Uncorrelated"
1422
+ ) %>%
1423
+ pull(candidate)
1424
+
1425
+
1426
+ correlated_slope_candidates <- setdiff(
1427
+ corr_candidates,
1428
+ "1"
1429
+ )
1430
+
1431
+
1432
+ if (
1433
+ !setequal(
1434
+ correlated_slope_candidates,
1435
+ uncorr_candidates
1436
+ )
1437
+ ) {
1438
+
1439
+ missing_from_uncorrelated <- setdiff(
1440
+ correlated_slope_candidates,
1441
+ uncorr_candidates
1442
+ )
1443
+
1444
+ unexpected_in_uncorrelated <- setdiff(
1445
+ uncorr_candidates,
1446
+ correlated_slope_candidates
1447
+ )
1448
+
1449
+ stop(
1450
+ "Correlated/uncorrelated candidate-family mismatch for ",
1451
+ dv_name,
1452
+ ".\n",
1453
+ "Missing from uncorrelated: ",
1454
+ paste(
1455
+ missing_from_uncorrelated,
1456
+ collapse = " | "
1457
+ ),
1458
+ "\n",
1459
+ "Unexpected in uncorrelated: ",
1460
+ paste(
1461
+ unexpected_in_uncorrelated,
1462
+ collapse = " | "
1463
+ )
1464
+ )
1465
+ }
1466
+
1467
+
1468
+ if (!"1" %in% corr_candidates) {
1469
+
1470
+ stop(
1471
+ "The correlated family is missing the shared ",
1472
+ "random-intercept-only candidate for ",
1473
+ dv_name,
1474
+ "."
1475
+ )
1476
+ }
1477
+
1478
+
1479
+ if ("1" %in% uncorr_candidates) {
1480
+
1481
+ stop(
1482
+ "The uncorrelated family unexpectedly contains a ",
1483
+ "duplicate random-intercept-only candidate for ",
1484
+ dv_name,
1485
+ "."
1486
+ )
1487
+ }
1488
+ }
1489
+
1490
+
1491
+ message(
1492
+ "Cross-family candidate validation passed: all 63 ",
1493
+ "slope-containing structures occur under both ",
1494
+ "parameterizations, while the random-intercept-only ",
1495
+ "candidate is represented once."
1496
+ )
1497
+
1498
+
1499
+ # ------------------------------------------------------------
1500
+ # 6.4 Verify Observation Counts Across Combined Candidates
1501
+ # ------------------------------------------------------------
1502
+ # Step 2 and Step 3 must use exactly the same DV-specific
1503
+ # analysis sample for direct information-criterion comparison.
1504
+ # ------------------------------------------------------------
1505
+
1506
+ final_df <- final_df %>%
1507
+ mutate(
1508
+ nobs = suppressWarnings(
1509
+ as.numeric(nobs)
1510
+ )
1511
+ )
1512
+
1513
+
1514
+ if (any(!is.finite(final_df$nobs))) {
1515
+
1516
+ stop(
1517
+ "Missing, invalid, or non-finite nobs values detected in ",
1518
+ "the combined Step 2 / Step 3 results."
1519
+ )
1520
+ }
1521
+
1522
+
1523
+ nobs_check <- final_df %>%
1524
+ group_by(
1525
+ `Dependent Variable Name`
1526
+ ) %>%
1527
+ summarise(
1528
+ N_Distinct_Nobs =
1529
+ n_distinct(nobs),
1530
+
1531
+ Min_Nobs =
1532
+ min(nobs),
1533
+
1534
+ Max_Nobs =
1535
+ max(nobs),
1536
+
1537
+ .groups = "drop"
1538
+ )
1539
+
1540
+
1541
+ if (
1542
+ any(
1543
+ nobs_check$N_Distinct_Nobs != 1
1544
+ )
1545
+ ) {
1546
+
1547
+ print(
1548
+ nobs_check
1549
+ )
1550
+
1551
+ stop(
1552
+ "Step 2 and Step 3 candidates do not use identical ",
1553
+ "observation counts for at least one DV. Combined ",
1554
+ "AIC/BIC comparison should not proceed."
1555
+ )
1556
+ }
1557
+
1558
+
1559
+ message(
1560
+ "Observation-count validation passed: all Step 2 / Step 3 ",
1561
+ "candidates use identical nobs within each DV."
1562
+ )
1563
+
1564
+
1565
+ # ------------------------------------------------------------
1566
+ # 6.5 Calculate Combined AIC/BIC Differences
1567
+ # ------------------------------------------------------------
1568
+
1569
+ final_df <- final_df %>%
1570
+ group_by(
1571
+ `Dependent Variable Name`
1572
+ ) %>%
1573
+ mutate(
1574
+
1575
+ combined_min_aic =
1576
+ min(
1577
+ aic,
1578
+ na.rm = TRUE
1579
+ ),
1580
+
1581
+ combined_min_bic =
1582
+ min(
1583
+ bic,
1584
+ na.rm = TRUE
1585
+ ),
1586
+
1587
+ combined_delta_aic =
1588
+ aic -
1589
+ combined_min_aic,
1590
+
1591
+ combined_delta_bic =
1592
+ bic -
1593
+ combined_min_bic,
1594
+
1595
+ eligible_min_aic =
1596
+ if (
1597
+ any(
1598
+ selection_eligible %in% TRUE
1599
+ )
1600
+ ) {
1601
+
1602
+ min(
1603
+ aic[
1604
+ selection_eligible %in% TRUE
1605
+ ],
1606
+ na.rm = TRUE
1607
+ )
1608
+
1609
+ } else {
1610
+
1611
+ NA_real_
1612
+ },
1613
+
1614
+ eligible_min_bic =
1615
+ if (
1616
+ any(
1617
+ selection_eligible %in% TRUE
1618
+ )
1619
+ ) {
1620
+
1621
+ min(
1622
+ bic[
1623
+ selection_eligible %in% TRUE
1624
+ ],
1625
+ na.rm = TRUE
1626
+ )
1627
+
1628
+ } else {
1629
+
1630
+ NA_real_
1631
+ },
1632
+
1633
+ eligible_delta_aic =
1634
+ ifelse(
1635
+ selection_eligible %in% TRUE,
1636
+ aic - eligible_min_aic,
1637
+ NA_real_
1638
+ ),
1639
+
1640
+ eligible_delta_bic =
1641
+ ifelse(
1642
+ selection_eligible %in% TRUE,
1643
+ bic - eligible_min_bic,
1644
+ NA_real_
1645
+ )
1646
+
1647
+ ) %>%
1648
+ ungroup() %>%
1649
+ select(
1650
+ -combined_min_aic,
1651
+ -combined_min_bic,
1652
+ -eligible_min_aic,
1653
+ -eligible_min_bic
1654
+ )
1655
+
1656
+
1657
+
1658
+
1659
+ # ============================================================
1660
+ # CELL 7 — ORDER, RANK, AND REORGANIZE MERGED RESULTS
1661
+ # ============================================================
1662
+ # Purpose:
1663
+ # Order the combined candidate set according to the Step 4
1664
+ # model-selection rule, assign within-DV ordering variables,
1665
+ # and place the primary comparison metadata and diagnostics
1666
+ # at the front of the merged table.
1667
+ #
1668
+ # Ordering:
1669
+ # 1. Stage of Reading
1670
+ # 2. selection_eligible = TRUE before FALSE
1671
+ # 3. BIC ascending
1672
+ #
1673
+ # Ranking:
1674
+ #
1675
+ # Step 4 Overall Order
1676
+ # → position of every candidate within its DV after
1677
+ # applying the Step 4 ordering rule
1678
+ #
1679
+ # Step 4 Eligible Rank
1680
+ # → BIC rank among selection-eligible candidates only;
1681
+ # ineligible candidates receive NA
1682
+ #
1683
+ # The complete original Step 2 / Step 3 ranking information is
1684
+ # retained after the primary Step 4 comparison columns.
1685
+ # ============================================================
1686
+
1687
+
1688
+ # ------------------------------------------------------------
1689
+ # 7.1 Sort Final Candidate Table
1690
+ # ------------------------------------------------------------
1691
+
1692
+ final_df <- final_df %>%
1693
+ arrange(
1694
+ `Stage of Reading`,
1695
+ desc(
1696
+ selection_eligible
1697
+ ),
1698
+ bic
1699
+ )
1700
+
1701
+
1702
+ # ------------------------------------------------------------
1703
+ # 7.2 Add Within-DV Step 4 Ordering and Eligible Rank
1704
+ # ------------------------------------------------------------
1705
+ # Because candidates have already been ordered by:
1706
+ #
1707
+ # 1. selection eligibility
1708
+ # 2. BIC
1709
+ #
1710
+ # row_number() gives the overall Step 4 position within each
1711
+ # DV, while cumsum(selection_eligible) gives the BIC ordering
1712
+ # among eligible candidates.
1713
+ # ------------------------------------------------------------
1714
+
1715
+ final_df <- final_df %>%
1716
+ group_by(
1717
+ `Dependent Variable Name`
1718
+ ) %>%
1719
+ mutate(
1720
+
1721
+ `Step 4 Overall Order` =
1722
+ row_number(),
1723
+
1724
+ `Step 4 Eligible Rank` =
1725
+ ifelse(
1726
+ selection_eligible %in% TRUE,
1727
+ cumsum(
1728
+ selection_eligible %in% TRUE
1729
+ ),
1730
+ NA_integer_
1731
+ )
1732
+
1733
+ ) %>%
1734
+ ungroup()
1735
+
1736
+
1737
+ # ------------------------------------------------------------
1738
+ # 7.3 Reorder Columns
1739
+ # ------------------------------------------------------------
1740
+
1741
+ priority_cols <- c(
1742
+ "Stage of Reading",
1743
+ "Reading Measure",
1744
+ "Measure Abbreviation",
1745
+ "Dependent Variable Name",
1746
+ "Random-Slope Structure",
1747
+ "Source Step",
1748
+ "selection_eligible",
1749
+ "Step 4 Overall Order",
1750
+ "Step 4 Eligible Rank",
1751
+ "eligible_delta_bic",
1752
+ "bic",
1753
+ "eligible_delta_aic",
1754
+ "aic",
1755
+ "combined_delta_bic",
1756
+ "combined_delta_aic",
1757
+ "candidate",
1758
+ "re_formula",
1759
+ "converged",
1760
+ "singular",
1761
+ "optimizer",
1762
+ "selected_via",
1763
+ "nobs",
1764
+ "llf",
1765
+ "status",
1766
+ "warnings",
1767
+ "Source Workbook"
1768
+ )
1769
+
1770
+
1771
+ priority_cols <- priority_cols[
1772
+ priority_cols %in% names(final_df)
1773
+ ]
1774
+
1775
+
1776
+ final_df <- final_df %>%
1777
+ select(
1778
+ all_of(priority_cols),
1779
+ everything()
1780
+ )
1781
+
1782
+
1783
+
1784
+
1785
+
1786
+ # ============================================================
1787
+ # CELL 8 — STEP 4 BEST-MODEL SUMMARY
1788
+ # ============================================================
1789
+ # Purpose:
1790
+ # Create a compact summary containing the preferred
1791
+ # selection-eligible candidate for each duration DV after
1792
+ # correlated and uncorrelated random-slope structures have
1793
+ # been combined.
1794
+ #
1795
+ # Selection rule:
1796
+ #
1797
+ # 1. Candidate must be selection eligible:
1798
+ #
1799
+ # converged = TRUE
1800
+ # singular = FALSE
1801
+ #
1802
+ # 2. Among eligible candidates, select minimum BIC.
1803
+ #
1804
+ # Because Step 4 Eligible Rank was calculated after applying
1805
+ # this same ordering rule, the selected candidate should have:
1806
+ #
1807
+ # Step 4 Eligible Rank = 1
1808
+ #
1809
+ # for each DV having at least one eligible candidate.
1810
+ #
1811
+ # This summary does not replace the complete candidate table.
1812
+ # It provides the final preferred random-slope structure for
1813
+ # each reading measure under the prespecified Step 4 rule.
1814
+ # ============================================================
1815
+
1816
+ best_model_summary <- final_df %>%
1817
+ filter(
1818
+ selection_eligible %in% TRUE,
1819
+ `Step 4 Eligible Rank` == 1
1820
+ ) %>%
1821
+ arrange(
1822
+ `Stage of Reading`
1823
+ )
1824
+
1825
+
1826
+ # ------------------------------------------------------------
1827
+ # Verify One Preferred Model per DV
1828
+ # ------------------------------------------------------------
1829
+
1830
+ summary_dv_check <- best_model_summary %>%
1831
+ count(
1832
+ `Dependent Variable Name`,
1833
+ name = "N_Selected"
1834
+ )
1835
+
1836
+
1837
+ # ------------------------------------------------------------
1838
+ # Detect Multiple Preferred Models Within a DV
1839
+ # ------------------------------------------------------------
1840
+
1841
+ if (
1842
+ nrow(summary_dv_check) > 0 &&
1843
+ any(
1844
+ summary_dv_check$N_Selected != 1
1845
+ )
1846
+ ) {
1847
+
1848
+ print(
1849
+ summary_dv_check
1850
+ )
1851
+
1852
+ stop(
1853
+ "The Step 4 best-model summary contains multiple selected ",
1854
+ "models for at least one DV."
1855
+ )
1856
+ }
1857
+
1858
+
1859
+ # ------------------------------------------------------------
1860
+ # Detect DVs Without an Eligible Preferred Model
1861
+ # ------------------------------------------------------------
1862
+
1863
+ selected_dvs <- unique(
1864
+ best_model_summary$`Dependent Variable Name`
1865
+ )
1866
+
1867
+ missing_selected_dvs <- setdiff(
1868
+ names(DV_INFO),
1869
+ selected_dvs
1870
+ )
1871
+
1872
+
1873
+ if (length(missing_selected_dvs) > 0) {
1874
+
1875
+ warning(
1876
+ "No selection-eligible Step 4 candidate was identified for: ",
1877
+ paste(
1878
+ missing_selected_dvs,
1879
+ collapse = ", "
1880
+ )
1881
+ )
1882
+ }
1883
+
1884
+
1885
+ # ------------------------------------------------------------
1886
+ # Confirm Complete Best-Model Summary When Available
1887
+ # ------------------------------------------------------------
1888
+
1889
+ if (length(missing_selected_dvs) == 0) {
1890
+
1891
+ message(
1892
+ "Best-model validation passed: exactly one preferred ",
1893
+ "selection-eligible candidate was identified for every DV."
1894
+ )
1895
+ }
1896
+
1897
+
1898
+
1899
+
1900
+
1901
+ # ============================================================
1902
+ # CELL 9 — FORMAT AND SAVE STEP 4 WORKBOOK
1903
+ # ============================================================
1904
+ # Purpose:
1905
+ # Export:
1906
+ #
1907
+ # Merged_Results
1908
+ # → complete combined candidate table
1909
+ #
1910
+ # Best_Model_Summary
1911
+ # → best selection-eligible BIC candidate per DV
1912
+ #
1913
+ # Structure_Check
1914
+ # → confirms presence of both correlated and
1915
+ # uncorrelated model families for every DV
1916
+ #
1917
+ # Formatting:
1918
+ # - Header styling
1919
+ # - Stage-specific row shading
1920
+ # - Borders
1921
+ # - Automatic column widths
1922
+ # - Frozen header rows
1923
+ # - Excel filters
1924
+ # ============================================================
1925
+
1926
+ wb <- createWorkbook()
1927
+
1928
+
1929
+ # ------------------------------------------------------------
1930
+ # 9.1 Add Worksheets
1931
+ # ------------------------------------------------------------
1932
+
1933
+ addWorksheet(
1934
+ wb,
1935
+ "Merged_Results"
1936
+ )
1937
+
1938
+ addWorksheet(
1939
+ wb,
1940
+ "Best_Model_Summary"
1941
+ )
1942
+
1943
+ addWorksheet(
1944
+ wb,
1945
+ "Structure_Check"
1946
+ )
1947
+
1948
+
1949
+ # ------------------------------------------------------------
1950
+ # 9.2 Write Data
1951
+ # ------------------------------------------------------------
1952
+
1953
+ writeData(
1954
+ wb,
1955
+ "Merged_Results",
1956
+ final_df,
1957
+ withFilter = TRUE
1958
+ )
1959
+
1960
+ writeData(
1961
+ wb,
1962
+ "Best_Model_Summary",
1963
+ best_model_summary,
1964
+ withFilter = TRUE
1965
+ )
1966
+
1967
+ writeData(
1968
+ wb,
1969
+ "Structure_Check",
1970
+ structure_check,
1971
+ withFilter = TRUE
1972
+ )
1973
+
1974
+
1975
+
1976
+
1977
+
1978
+ # ============================================================
1979
+ # CELL 10 — EXCEL STYLING
1980
+ # ============================================================
1981
+
1982
+
1983
+ # ------------------------------------------------------------
1984
+ # 10.1 Define Styles
1985
+ # ------------------------------------------------------------
1986
+
1987
+ style_header <- createStyle(
1988
+ textDecoration = "bold",
1989
+ halign = "center",
1990
+ valign = "center",
1991
+ border = "TopBottomLeftRight",
1992
+ borderStyle = "thin"
1993
+ )
1994
+
1995
+
1996
+ style_border <- createStyle(
1997
+ border = "TopBottomLeftRight",
1998
+ borderStyle = "thin"
1999
+ )
2000
+
2001
+
2002
+ style_stage1 <- createStyle(
2003
+ fgFill = "#E0F7FA"
2004
+ )
2005
+
2006
+ style_stage2 <- createStyle(
2007
+ fgFill = "#E8F5E9"
2008
+ )
2009
+
2010
+ style_stage3 <- createStyle(
2011
+ fgFill = "#FFF3E0"
2012
+ )
2013
+
2014
+ style_stage4 <- createStyle(
2015
+ fgFill = "#F3E5F5"
2016
+ )
2017
+
2018
+
2019
+ # ------------------------------------------------------------
2020
+ # 10.2 Apply Header Style
2021
+ # ------------------------------------------------------------
2022
+
2023
+ addStyle(
2024
+ wb,
2025
+ "Merged_Results",
2026
+ style_header,
2027
+ rows = 1,
2028
+ cols = seq_len(
2029
+ ncol(final_df)
2030
+ ),
2031
+ gridExpand = TRUE,
2032
+ stack = TRUE
2033
+ )
2034
+
2035
+
2036
+ if (ncol(best_model_summary) > 0) {
2037
+
2038
+ addStyle(
2039
+ wb,
2040
+ "Best_Model_Summary",
2041
+ style_header,
2042
+ rows = 1,
2043
+ cols = seq_len(
2044
+ ncol(best_model_summary)
2045
+ ),
2046
+ gridExpand = TRUE,
2047
+ stack = TRUE
2048
+ )
2049
+ }
2050
+
2051
+
2052
+ addStyle(
2053
+ wb,
2054
+ "Structure_Check",
2055
+ style_header,
2056
+ rows = 1,
2057
+ cols = seq_len(
2058
+ ncol(structure_check)
2059
+ ),
2060
+ gridExpand = TRUE,
2061
+ stack = TRUE
2062
+ )
2063
+
2064
+
2065
+
2066
+
2067
+
2068
+ # ============================================================
2069
+ # CELL 11 — STAGE-SPECIFIC ROW FORMATTING
2070
+ # ============================================================
2071
+
2072
+ message(
2073
+ "Applying stage-specific formatting..."
2074
+ )
2075
+
2076
+
2077
+ rows_s1 <- which(
2078
+ final_df$`Stage of Reading` == 1
2079
+ ) + 1
2080
+
2081
+ rows_s2 <- which(
2082
+ final_df$`Stage of Reading` == 2
2083
+ ) + 1
2084
+
2085
+ rows_s3 <- which(
2086
+ final_df$`Stage of Reading` == 3
2087
+ ) + 1
2088
+
2089
+ rows_s4 <- which(
2090
+ final_df$`Stage of Reading` == 4
2091
+ ) + 1
2092
+
2093
+
2094
+ if (length(rows_s1) > 0) {
2095
+
2096
+ addStyle(
2097
+ wb,
2098
+ "Merged_Results",
2099
+ style_stage1,
2100
+ rows = rows_s1,
2101
+ cols = seq_len(
2102
+ ncol(final_df)
2103
+ ),
2104
+ gridExpand = TRUE,
2105
+ stack = TRUE
2106
+ )
2107
+ }
2108
+
2109
+
2110
+ if (length(rows_s2) > 0) {
2111
+
2112
+ addStyle(
2113
+ wb,
2114
+ "Merged_Results",
2115
+ style_stage2,
2116
+ rows = rows_s2,
2117
+ cols = seq_len(
2118
+ ncol(final_df)
2119
+ ),
2120
+ gridExpand = TRUE,
2121
+ stack = TRUE
2122
+ )
2123
+ }
2124
+
2125
+
2126
+ if (length(rows_s3) > 0) {
2127
+
2128
+ addStyle(
2129
+ wb,
2130
+ "Merged_Results",
2131
+ style_stage3,
2132
+ rows = rows_s3,
2133
+ cols = seq_len(
2134
+ ncol(final_df)
2135
+ ),
2136
+ gridExpand = TRUE,
2137
+ stack = TRUE
2138
+ )
2139
+ }
2140
+
2141
+
2142
+ if (length(rows_s4) > 0) {
2143
+
2144
+ addStyle(
2145
+ wb,
2146
+ "Merged_Results",
2147
+ style_stage4,
2148
+ rows = rows_s4,
2149
+ cols = seq_len(
2150
+ ncol(final_df)
2151
+ ),
2152
+ gridExpand = TRUE,
2153
+ stack = TRUE
2154
+ )
2155
+ }
2156
+
2157
+
2158
+
2159
+
2160
+
2161
+ # ============================================================
2162
+ # CELL 12 — BORDERS, WIDTHS, AND FREEZE PANES
2163
+ # ============================================================
2164
+
2165
+
2166
+ # ------------------------------------------------------------
2167
+ # 12.1 Borders — Merged Results
2168
+ # ------------------------------------------------------------
2169
+
2170
+ addStyle(
2171
+ wb,
2172
+ "Merged_Results",
2173
+ style_border,
2174
+ rows = seq_len(
2175
+ nrow(final_df) + 1
2176
+ ),
2177
+ cols = seq_len(
2178
+ ncol(final_df)
2179
+ ),
2180
+ gridExpand = TRUE,
2181
+ stack = TRUE
2182
+ )
2183
+
2184
+
2185
+ # ------------------------------------------------------------
2186
+ # 12.2 Borders — Best Model Summary
2187
+ # ------------------------------------------------------------
2188
+
2189
+ if (
2190
+ nrow(best_model_summary) > 0 &&
2191
+ ncol(best_model_summary) > 0
2192
+ ) {
2193
+
2194
+ addStyle(
2195
+ wb,
2196
+ "Best_Model_Summary",
2197
+ style_border,
2198
+ rows = seq_len(
2199
+ nrow(best_model_summary) + 1
2200
+ ),
2201
+ cols = seq_len(
2202
+ ncol(best_model_summary)
2203
+ ),
2204
+ gridExpand = TRUE,
2205
+ stack = TRUE
2206
+ )
2207
+ }
2208
+
2209
+
2210
+ # ------------------------------------------------------------
2211
+ # 12.3 Borders — Structure Check
2212
+ # ------------------------------------------------------------
2213
+
2214
+ addStyle(
2215
+ wb,
2216
+ "Structure_Check",
2217
+ style_border,
2218
+ rows = seq_len(
2219
+ nrow(structure_check) + 1
2220
+ ),
2221
+ cols = seq_len(
2222
+ ncol(structure_check)
2223
+ ),
2224
+ gridExpand = TRUE,
2225
+ stack = TRUE
2226
+ )
2227
+
2228
+
2229
+ # ------------------------------------------------------------
2230
+ # 12.4 Automatic Column Widths
2231
+ # ------------------------------------------------------------
2232
+
2233
+ setColWidths(
2234
+ wb,
2235
+ "Merged_Results",
2236
+ cols = seq_len(
2237
+ ncol(final_df)
2238
+ ),
2239
+ widths = "auto"
2240
+ )
2241
+
2242
+
2243
+ if (ncol(best_model_summary) > 0) {
2244
+
2245
+ setColWidths(
2246
+ wb,
2247
+ "Best_Model_Summary",
2248
+ cols = seq_len(
2249
+ ncol(best_model_summary)
2250
+ ),
2251
+ widths = "auto"
2252
+ )
2253
+ }
2254
+
2255
+
2256
+ setColWidths(
2257
+ wb,
2258
+ "Structure_Check",
2259
+ cols = seq_len(
2260
+ ncol(structure_check)
2261
+ ),
2262
+ widths = "auto"
2263
+ )
2264
+
2265
+
2266
+ # ------------------------------------------------------------
2267
+ # 12.5 Freeze Header Rows
2268
+ # ------------------------------------------------------------
2269
+
2270
+ freezePane(
2271
+ wb,
2272
+ "Merged_Results",
2273
+ firstRow = TRUE
2274
+ )
2275
+
2276
+ freezePane(
2277
+ wb,
2278
+ "Best_Model_Summary",
2279
+ firstRow = TRUE
2280
+ )
2281
+
2282
+ freezePane(
2283
+ wb,
2284
+ "Structure_Check",
2285
+ firstRow = TRUE
2286
+ )
2287
+
2288
+
2289
+
2290
+
2291
+
2292
+ # ============================================================
2293
+ # CELL 13 — SAVE STEP 4 WORKBOOK
2294
+ # ============================================================
2295
+
2296
+ saveWorkbook(
2297
+ wb,
2298
+ MERGED_OUTPUT_PATH,
2299
+ overwrite = TRUE
2300
+ )
2301
+
2302
+
2303
+ message(
2304
+ "\n",
2305
+ strrep("=", 80)
2306
+ )
2307
+
2308
+ message(
2309
+ "STEP 4 COMPLETED SUCCESSFULLY"
2310
+ )
2311
+
2312
+ message(
2313
+ "Dataset: Affective Provo"
2314
+ )
2315
+
2316
+ message(
2317
+ "Merged candidate models: ",
2318
+ format(
2319
+ nrow(final_df),
2320
+ big.mark = ","
2321
+ )
2322
+ )
2323
+
2324
+ message(
2325
+ "Duration DVs: ",
2326
+ length(DV_INFO)
2327
+ )
2328
+
2329
+ message(
2330
+ "Output: ",
2331
+ MERGED_OUTPUT_PATH
2332
+ )
2333
+
2334
+ message(
2335
+ strrep("=", 80)
2336
+ )
05-Research_Program-Affective_Provo/01-Fixation_Duration_Research/01-LME_Model_Structure/01-Scripts/Step-5-Filtering_the_Best_Random_Slope.R ADDED
@@ -0,0 +1,2981 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # COPYRIGHT, LICENSING, AND SCHOLARLY CITATION
3
+ # ============================================================
4
+ # Copyright (c) 2026 Mohit Gupta
5
+ # License: MIT
6
+ # SPDX-License-Identifier: MIT
7
+ #
8
+ # This script contains original computational software
9
+ # developed by Mohit Gupta for the AffLex-Provo
10
+ # Research Program.
11
+ #
12
+ # Citation:
13
+ # Researchers using this software in published research
14
+ # are strongly requested to cite the AffLex-Provo repository:
15
+ # https://huggingface.co/datasets/mohitg2/AffLex-Provo
16
+ #
17
+ # Third-party datasets and externally sourced materials
18
+ # remain subject to their respective original licenses.
19
+ #
20
+ # See the applicable repository LICENSE file for the
21
+ # complete MIT License terms.
22
+ # ============================================================
23
+
24
+ # ============================================================
25
+ # STEP 5 — FINAL RANDOM-SLOPE STRUCTURE DECISION (Affective Provo)
26
+ # ============================================================
27
+ #
28
+ #
29
+ # REQUIRED R VERSION: R version 4.5.2 (2025-10-31)
30
+ #
31
+ #
32
+ # Purpose:
33
+ # Determine the final participant-level random-slope
34
+ # structure for each duration-based dependent variable after
35
+ # combining the Step 2 correlated and Step 3 uncorrelated
36
+ # candidate searches in Step 4.
37
+ #
38
+ # Dataset:
39
+ # Affective Provo
40
+ #
41
+ # Input:
42
+ # Step-4_Merged_Correlated-Uncorrelated_Slopes_Affective_Provo.xlsx
43
+ #
44
+ # Decision framework:
45
+ #
46
+ # 1. Retain only selection-eligible models:
47
+ #
48
+ # converged = TRUE
49
+ # singular = FALSE
50
+ #
51
+ # 2. Across the complete eligible Step 4 candidate set for
52
+ # each DV, identify the random-slope composition associated
53
+ # with the minimum BIC.
54
+ #
55
+ # 3. Once that slope composition has been selected, compare
56
+ # the correlated and uncorrelated parameterizations of
57
+ # that SAME random-slope composition.
58
+ #
59
+ # 4. If both parameterizations are available and the selected
60
+ # structure contains at least one random slope, calculate
61
+ # a likelihood-ratio statistic:
62
+ #
63
+ # LR = 2 × (logLik_correlated - logLik_uncorrelated)
64
+ #
65
+ # The degrees-of-freedom difference equals the number of
66
+ # covariance parameters present in the correlated model
67
+ # but absent from the uncorrelated model:
68
+ #
69
+ # q(q - 1) / 2
70
+ #
71
+ # where:
72
+ #
73
+ # q = 1 + number of participant-level random slopes
74
+ #
75
+ # The correlated parameterization is retained when:
76
+ #
77
+ # p < .05
78
+ #
79
+ # Otherwise, the uncorrelated parameterization is retained
80
+ # on grounds of parsimony.
81
+ #
82
+ # 5. If only one parameterization of the selected slope
83
+ # composition is selection eligible, retain the available
84
+ # eligible parameterization.
85
+ #
86
+ # 6. The random-intercept-only candidate:
87
+ #
88
+ # 1
89
+ #
90
+ # is represented only once in Step 4 because correlated
91
+ # versus uncorrelated parameterization is not defined when
92
+ # there are no participant-level random slopes and hence
93
+ # no covariance parameters to estimate.
94
+ #
95
+ # Relationship to the original analysis:
96
+ #
97
+ # This reproduces the decision hierarchy used in the original
98
+ # analysis:
99
+ #
100
+ # minimum-BIC slope composition
101
+ # ↓
102
+ # matched correlated / uncorrelated comparison
103
+ # ↓
104
+ # LRT for covariance parameters
105
+ # ↓
106
+ # correlated if significant,
107
+ # uncorrelated if nonsignificant
108
+ #
109
+ # The present implementation retains additional safeguards
110
+ # introduced in the revised pipeline, including explicit
111
+ # convergence, singularity, finite-statistic, and observation-
112
+ # count validation.
113
+ #
114
+ # Important:
115
+ # Step 5 does NOT refit models.
116
+ #
117
+ # It operates on model statistics already generated in
118
+ # Steps 2 and 3 and consolidated in Step 4.
119
+ #
120
+ # Paper 1 candidate random slopes:
121
+ #
122
+ # - Length
123
+ # - Predictability
124
+ # - Frequency
125
+ # - Valence
126
+ # - Arousal
127
+ # - Dominance
128
+ #
129
+ # Output:
130
+ # Step-5_Final_Random-Slope_Decisions_Affective_Provo.xlsx
131
+ #
132
+ # Sheets:
133
+ #
134
+ # Final_Decisions
135
+ # → final selected structure for each DV
136
+ #
137
+ # Selected_Structure_Comparison
138
+ # → correlated and uncorrelated parameterizations of the
139
+ # minimum-BIC selected slope composition
140
+ #
141
+ # Design principles:
142
+ # - convergence-aware
143
+ # - singularity-aware
144
+ # - minimum-BIC slope-composition selection
145
+ # - matched parameterization comparison
146
+ # - LRT-based covariance decision
147
+ # - identical decision principle across duration DVs
148
+ # - fully reproducible
149
+ # ============================================================
150
+
151
+
152
+
153
+ # ============================================================
154
+ # CELL 1 — PACKAGE INSTALLATION AND INITIALIZATION
155
+ # ============================================================
156
+
157
+ REQUIRED_PACKAGES <- c(
158
+ "readxl",
159
+ "openxlsx",
160
+ "dplyr",
161
+ "stringr",
162
+ "here"
163
+ )
164
+
165
+
166
+ # ------------------------------------------------------------
167
+ # 1.1 Identify Missing Packages
168
+ # ------------------------------------------------------------
169
+
170
+ MISSING_PACKAGES <- REQUIRED_PACKAGES[
171
+ !vapply(
172
+ REQUIRED_PACKAGES,
173
+ requireNamespace,
174
+ quietly = TRUE,
175
+ FUN.VALUE = logical(1)
176
+ )
177
+ ]
178
+
179
+
180
+ # ------------------------------------------------------------
181
+ # 1.2 Install Missing Packages
182
+ # ------------------------------------------------------------
183
+
184
+ if (length(MISSING_PACKAGES) > 0) {
185
+
186
+ message(
187
+ "Installing missing package(s): ",
188
+ paste(MISSING_PACKAGES, collapse = ", ")
189
+ )
190
+
191
+ install.packages(
192
+ MISSING_PACKAGES,
193
+ repos = "https://cloud.r-project.org",
194
+ dependencies = TRUE
195
+ )
196
+
197
+ } else {
198
+
199
+ message(
200
+ "All required packages are already installed."
201
+ )
202
+ }
203
+
204
+
205
+ # ------------------------------------------------------------
206
+ # 1.3 Load Required Packages
207
+ # ------------------------------------------------------------
208
+
209
+ suppressPackageStartupMessages({
210
+
211
+ library(readxl)
212
+ library(openxlsx)
213
+
214
+ library(dplyr)
215
+ library(stringr)
216
+
217
+ library(here)
218
+ })
219
+
220
+
221
+ message(
222
+ "Package initialization complete: ",
223
+ length(REQUIRED_PACKAGES),
224
+ " required packages available."
225
+ )
226
+
227
+
228
+
229
+
230
+
231
+ # ============================================================
232
+ # CELL 2 — PROJECT PATHS
233
+ # ============================================================
234
+ # Purpose:
235
+ # Define the Step 4 input workbook and Step 5 output workbook.
236
+ #
237
+ # Directory:
238
+ #
239
+ # 05-Research_Program-Affective_Provo/
240
+ # 01-Fixation_Duration_Research/
241
+ # 01-LME_Model_Structure/
242
+ # 02-Results/
243
+ # ============================================================
244
+
245
+ PROJECT_ROOT <- here()
246
+
247
+
248
+ RESULTS_DIR <- here(
249
+ "05-Research_Program-Affective_Provo",
250
+ "01-Fixation_Duration_Research",
251
+ "01-LME_Model_Structure",
252
+ "02-Results"
253
+ )
254
+
255
+
256
+ INPUT_FILE <- file.path(
257
+ RESULTS_DIR,
258
+ "Step-4_Merged_Correlated-Uncorrelated_Slopes_Affective_Provo.xlsx"
259
+ )
260
+
261
+
262
+ OUTPUT_FILE <- file.path(
263
+ RESULTS_DIR,
264
+ "Step-5_Final_Random-Slope_Decisions_Affective_Provo.xlsx"
265
+ )
266
+
267
+
268
+ # ------------------------------------------------------------
269
+ # 2.1 Validate Input
270
+ # ------------------------------------------------------------
271
+
272
+ if (!dir.exists(RESULTS_DIR)) {
273
+
274
+ stop(
275
+ "Results directory not found: ",
276
+ RESULTS_DIR
277
+ )
278
+ }
279
+
280
+
281
+ if (!file.exists(INPUT_FILE)) {
282
+
283
+ stop(
284
+ "Step 4 merged workbook not found: ",
285
+ INPUT_FILE
286
+ )
287
+ }
288
+
289
+
290
+ # ------------------------------------------------------------
291
+ # 2.2 Report Resolved Paths
292
+ # ------------------------------------------------------------
293
+
294
+ message(
295
+ "PROJECT_ROOT: ",
296
+ PROJECT_ROOT
297
+ )
298
+
299
+ message(
300
+ "RESULTS_DIR: ",
301
+ RESULTS_DIR
302
+ )
303
+
304
+ message(
305
+ "INPUT_FILE: ",
306
+ INPUT_FILE
307
+ )
308
+
309
+ message(
310
+ "OUTPUT_FILE: ",
311
+ OUTPUT_FILE
312
+ )
313
+
314
+
315
+
316
+
317
+
318
+ # ============================================================
319
+ # CELL 3 — LOAD AND VALIDATE STEP 4 RESULTS
320
+ # ============================================================
321
+ # Purpose:
322
+ # Load the complete merged candidate table produced by
323
+ # Step 4 and validate the columns required for the final
324
+ # model-selection procedure.
325
+ #
326
+ # Validation includes:
327
+ # - required columns
328
+ # - finite AIC/BIC/log-likelihood values
329
+ # - positive integer observation counts
330
+ # - valid logical diagnostic values
331
+ # - consistency of selection_eligible with convergence and
332
+ # singularity
333
+ # - valid random-slope structure labels
334
+ # - presence of both parameterizations for every DV
335
+ # ============================================================
336
+
337
+
338
+ # ------------------------------------------------------------
339
+ # 3.1 Load Merged Candidate Table
340
+ # ------------------------------------------------------------
341
+
342
+ df_all <- read_excel(
343
+ INPUT_FILE,
344
+ sheet = "Merged_Results"
345
+ )
346
+
347
+
348
+ if (nrow(df_all) == 0) {
349
+
350
+ stop(
351
+ "Step 4 Merged_Results sheet contains no candidate models."
352
+ )
353
+ }
354
+
355
+
356
+ message(
357
+ "Merged Step 4 candidate rows loaded: ",
358
+ format(
359
+ nrow(df_all),
360
+ big.mark = ","
361
+ )
362
+ )
363
+
364
+
365
+ # ------------------------------------------------------------
366
+ # 3.2 Validate Required Columns
367
+ # ------------------------------------------------------------
368
+
369
+ REQUIRED_COLUMNS <- c(
370
+ "Stage of Reading",
371
+ "Reading Measure",
372
+ "Dependent Variable Name",
373
+ "Random-Slope Structure",
374
+ "selection_eligible",
375
+ "re_formula",
376
+ "aic",
377
+ "bic",
378
+ "llf",
379
+ "nobs",
380
+ "converged",
381
+ "singular"
382
+ )
383
+
384
+
385
+ missing_columns <- setdiff(
386
+ REQUIRED_COLUMNS,
387
+ names(df_all)
388
+ )
389
+
390
+
391
+ if (length(missing_columns) > 0) {
392
+
393
+ stop(
394
+ "Step 4 workbook is missing required column(s): ",
395
+ paste(
396
+ missing_columns,
397
+ collapse = ", "
398
+ )
399
+ )
400
+ }
401
+
402
+
403
+ # ------------------------------------------------------------
404
+ # 3.3 Normalize and Validate Required Numeric Columns
405
+ # ------------------------------------------------------------
406
+
407
+ df_all <- df_all %>%
408
+ mutate(
409
+ aic = suppressWarnings(
410
+ as.numeric(aic)
411
+ ),
412
+ bic = suppressWarnings(
413
+ as.numeric(bic)
414
+ ),
415
+ llf = suppressWarnings(
416
+ as.numeric(llf)
417
+ ),
418
+ nobs = suppressWarnings(
419
+ as.numeric(nobs)
420
+ )
421
+ )
422
+
423
+
424
+ if (
425
+ any(!is.finite(df_all$aic)) ||
426
+ any(!is.finite(df_all$bic)) ||
427
+ any(!is.finite(df_all$llf))
428
+ ) {
429
+
430
+ stop(
431
+ "Missing, invalid, or non-finite AIC/BIC/log-likelihood ",
432
+ "values detected in the Step 4 merged results."
433
+ )
434
+ }
435
+
436
+
437
+ if (
438
+ any(!is.finite(df_all$nobs)) ||
439
+ any(df_all$nobs <= 0) ||
440
+ any(df_all$nobs != floor(df_all$nobs))
441
+ ) {
442
+
443
+ stop(
444
+ "Missing, invalid, non-positive, or non-integer nobs ",
445
+ "values detected in the Step 4 merged results."
446
+ )
447
+ }
448
+
449
+
450
+ df_all <- df_all %>%
451
+ mutate(
452
+ nobs = as.integer(nobs)
453
+ )
454
+
455
+
456
+ # ------------------------------------------------------------
457
+ # 3.4 Normalize Logical Columns
458
+ # ------------------------------------------------------------
459
+
460
+ to_logical_safe <- function(x) {
461
+
462
+ if (is.logical(x)) {
463
+ return(x)
464
+ }
465
+
466
+ x_chr <- toupper(
467
+ trimws(
468
+ as.character(x)
469
+ )
470
+ )
471
+
472
+ case_when(
473
+ x_chr %in% c(
474
+ "TRUE",
475
+ "T",
476
+ "1"
477
+ ) ~ TRUE,
478
+
479
+ x_chr %in% c(
480
+ "FALSE",
481
+ "F",
482
+ "0"
483
+ ) ~ FALSE,
484
+
485
+ TRUE ~ NA
486
+ )
487
+ }
488
+
489
+
490
+ df_all <- df_all %>%
491
+ mutate(
492
+ selection_eligible =
493
+ to_logical_safe(
494
+ selection_eligible
495
+ ),
496
+
497
+ converged =
498
+ to_logical_safe(
499
+ converged
500
+ ),
501
+
502
+ singular =
503
+ to_logical_safe(
504
+ singular
505
+ )
506
+ )
507
+
508
+
509
+ # ------------------------------------------------------------
510
+ # 3.4A Validate Normalized Logical Columns
511
+ # ------------------------------------------------------------
512
+
513
+ if (anyNA(df_all$converged)) {
514
+
515
+ stop(
516
+ "Missing or invalid logical value(s) detected in ",
517
+ "'converged' in the Step 4 merged results."
518
+ )
519
+ }
520
+
521
+
522
+ if (anyNA(df_all$singular)) {
523
+
524
+ stop(
525
+ "Missing or invalid logical value(s) detected in ",
526
+ "'singular' in the Step 4 merged results."
527
+ )
528
+ }
529
+
530
+
531
+ if (anyNA(df_all$selection_eligible)) {
532
+
533
+ stop(
534
+ "Missing or invalid logical value(s) detected in ",
535
+ "'selection_eligible' in the Step 4 merged results."
536
+ )
537
+ }
538
+
539
+
540
+ # ------------------------------------------------------------
541
+ # 3.5 Verify Selection Eligibility
542
+ # ------------------------------------------------------------
543
+
544
+ expected_eligibility <- (
545
+ df_all$converged %in% TRUE &
546
+ df_all$singular %in% FALSE
547
+ )
548
+
549
+
550
+ eligibility_mismatch <- which(
551
+ df_all$selection_eligible !=
552
+ expected_eligibility
553
+ )
554
+
555
+
556
+ if (length(eligibility_mismatch) > 0) {
557
+
558
+ stop(
559
+ "selection_eligible is inconsistent with converged / ",
560
+ "singular for ",
561
+ length(eligibility_mismatch),
562
+ " candidate(s) in the Step 4 merged results."
563
+ )
564
+ }
565
+
566
+
567
+ # ------------------------------------------------------------
568
+ # 3.6 Validate Random-Slope Structure Labels
569
+ # ------------------------------------------------------------
570
+
571
+ valid_structure_labels <- c(
572
+ "Correlated",
573
+ "Uncorrelated"
574
+ )
575
+
576
+
577
+ unexpected_structure_labels <- setdiff(
578
+ unique(
579
+ df_all$`Random-Slope Structure`
580
+ ),
581
+ valid_structure_labels
582
+ )
583
+
584
+
585
+ if (length(unexpected_structure_labels) > 0) {
586
+
587
+ stop(
588
+ "Unexpected Random-Slope Structure label(s): ",
589
+ paste(
590
+ unexpected_structure_labels,
591
+ collapse = ", "
592
+ )
593
+ )
594
+ }
595
+
596
+
597
+ # ------------------------------------------------------------
598
+ # 3.7 Validate Random-Slope Formula Values
599
+ # ------------------------------------------------------------
600
+
601
+ if (
602
+ any(
603
+ is.na(
604
+ df_all$re_formula
605
+ )
606
+ ) ||
607
+ any(
608
+ !nzchar(
609
+ trimws(
610
+ as.character(
611
+ df_all$re_formula
612
+ )
613
+ )
614
+ )
615
+ )
616
+ ) {
617
+
618
+ stop(
619
+ "Missing or empty re_formula value(s) detected in the ",
620
+ "Step 4 merged results."
621
+ )
622
+ }
623
+
624
+
625
+ # ------------------------------------------------------------
626
+ # 3.8 Verify Parameterization Coverage Within Each DV
627
+ # ------------------------------------------------------------
628
+
629
+ parameterization_check <- df_all %>%
630
+ distinct(
631
+ `Dependent Variable Name`,
632
+ `Random-Slope Structure`
633
+ ) %>%
634
+ count(
635
+ `Dependent Variable Name`,
636
+ name = "N_Parameterizations"
637
+ )
638
+
639
+
640
+ if (
641
+ any(
642
+ parameterization_check$N_Parameterizations != 2
643
+ )
644
+ ) {
645
+
646
+ print(
647
+ parameterization_check
648
+ )
649
+
650
+ stop(
651
+ "At least one DV does not contain both correlated and ",
652
+ "uncorrelated candidate models in the Step 4 results."
653
+ )
654
+ }
655
+
656
+
657
+ message(
658
+ "Parameterization validation passed: correlated and ",
659
+ "uncorrelated candidate families are present for every DV."
660
+ )
661
+
662
+
663
+
664
+ # ============================================================
665
+ # CELL 4 — DEFINE ELIGIBLE FINAL-SELECTION CANDIDATES
666
+ # ============================================================
667
+ # Purpose:
668
+ # Restrict final model selection to numerically acceptable
669
+ # candidate models.
670
+ #
671
+ # Eligibility rule inherited from Steps 2–4:
672
+ #
673
+ # converged = TRUE
674
+ # singular = FALSE
675
+ #
676
+ # Step 4 already stores this rule in selection_eligible.
677
+ #
678
+ # The conditions are checked again here so Step 5 does not
679
+ # depend blindly on a single imported flag.
680
+ # ============================================================
681
+
682
+ df_eligible <- df_all %>%
683
+ filter(
684
+ selection_eligible %in% TRUE,
685
+ converged %in% TRUE,
686
+ singular %in% FALSE,
687
+ is.finite(bic),
688
+ is.finite(aic),
689
+ is.finite(llf)
690
+ )
691
+
692
+
693
+ message(
694
+ "Total merged candidates : ",
695
+ format(
696
+ nrow(df_all),
697
+ big.mark = ","
698
+ )
699
+ )
700
+
701
+
702
+ message(
703
+ "Selection-eligible candidates: ",
704
+ format(
705
+ nrow(df_eligible),
706
+ big.mark = ","
707
+ )
708
+ )
709
+
710
+
711
+ if (nrow(df_eligible) == 0) {
712
+
713
+ stop(
714
+ "No selection-eligible candidate models remain."
715
+ )
716
+ }
717
+
718
+
719
+ # ------------------------------------------------------------
720
+ # Verify Every DV Has at Least One Eligible Candidate
721
+ # ------------------------------------------------------------
722
+
723
+ eligible_dv_check <- df_eligible %>%
724
+ distinct(
725
+ `Dependent Variable Name`
726
+ )
727
+
728
+
729
+ missing_eligible_dvs <- setdiff(
730
+ unique(
731
+ df_all$`Dependent Variable Name`
732
+ ),
733
+ eligible_dv_check$`Dependent Variable Name`
734
+ )
735
+
736
+
737
+ if (length(missing_eligible_dvs) > 0) {
738
+
739
+ stop(
740
+ "No selection-eligible candidate remains for: ",
741
+ paste(
742
+ missing_eligible_dvs,
743
+ collapse = ", "
744
+ )
745
+ )
746
+ }
747
+
748
+
749
+ message(
750
+ "Eligibility validation passed: every DV contains at least ",
751
+ "one converged, nonsingular candidate."
752
+ )
753
+
754
+
755
+
756
+ # ============================================================
757
+ # CELL 5 — HELPER FUNCTIONS FOR FINAL DECISION
758
+ # ============================================================
759
+ # Purpose:
760
+ # Define helper functions required to reproduce the original
761
+ # Step 5 decision framework.
762
+ #
763
+ # The decision occurs in two stages:
764
+ #
765
+ # Stage 1:
766
+ # Identify the random-slope composition associated with
767
+ # the minimum BIC among all eligible candidates.
768
+ #
769
+ # Stage 2:
770
+ # Compare correlated and uncorrelated parameterizations
771
+ # of that SAME random-slope composition.
772
+ #
773
+ # Formula comparison ignores whitespace and ordering of slope
774
+ # terms so logically equivalent candidate structures can be
775
+ # matched safely.
776
+ # ============================================================
777
+
778
+
779
+ # ------------------------------------------------------------
780
+ # 5.1 Normalize Random-Slope Formula
781
+ # ------------------------------------------------------------
782
+
783
+ normalize_re_formula <- function(x) {
784
+
785
+ str_replace_all(
786
+ x,
787
+ "\\s+",
788
+ ""
789
+ )
790
+ }
791
+
792
+
793
+ # ------------------------------------------------------------
794
+ # 5.2 Extract Random-Slope Terms
795
+ # ------------------------------------------------------------
796
+
797
+ extract_random_slopes <- function(
798
+ re_formula
799
+ ) {
800
+
801
+ if (
802
+ length(re_formula) != 1 ||
803
+ is.na(re_formula)
804
+ ) {
805
+
806
+ return(
807
+ character(0)
808
+ )
809
+ }
810
+
811
+
812
+ normalized <- normalize_re_formula(
813
+ re_formula
814
+ )
815
+
816
+
817
+ if (normalized == "1") {
818
+
819
+ return(
820
+ character(0)
821
+ )
822
+ }
823
+
824
+
825
+ terms <- str_split(
826
+ normalized,
827
+ fixed("+"),
828
+ simplify = FALSE
829
+ )[[1]]
830
+
831
+
832
+ slopes <- terms[
833
+ terms != "1" &
834
+ nzchar(terms)
835
+ ]
836
+
837
+
838
+ sort(
839
+ unique(
840
+ slopes
841
+ )
842
+ )
843
+ }
844
+
845
+
846
+ # ------------------------------------------------------------
847
+ # 5.3 Count Candidate Random Slopes
848
+ # ------------------------------------------------------------
849
+
850
+ count_random_slopes <- function(
851
+ re_formula
852
+ ) {
853
+
854
+ as.integer(
855
+ length(
856
+ extract_random_slopes(
857
+ re_formula
858
+ )
859
+ )
860
+ )
861
+ }
862
+
863
+
864
+ # ------------------------------------------------------------
865
+ # 5.4 Create Canonical Slope-Set Key
866
+ # ------------------------------------------------------------
867
+ # Purpose:
868
+ # Produce an ordering-independent identifier for each random-
869
+ # slope composition.
870
+ #
871
+ # Examples:
872
+ #
873
+ # 1
874
+ # → "1"
875
+ #
876
+ # 1 + Length + Valence + Arousal
877
+ # 1 + Arousal + Length + Valence
878
+ #
879
+ # → "Arousal|Length|Valence"
880
+ # ------------------------------------------------------------
881
+
882
+ canonical_slope_key <- function(
883
+ re_formula
884
+ ) {
885
+
886
+ slopes <- extract_random_slopes(
887
+ re_formula
888
+ )
889
+
890
+
891
+ if (length(slopes) == 0) {
892
+
893
+ return(
894
+ "1"
895
+ )
896
+ }
897
+
898
+
899
+ paste(
900
+ slopes,
901
+ collapse = "|"
902
+ )
903
+ }
904
+
905
+
906
+ # ------------------------------------------------------------
907
+ # 5.5 Calculate Covariance-Parameter Difference
908
+ # ------------------------------------------------------------
909
+ # For a participant-level random-effects structure containing:
910
+ #
911
+ # q = intercept + random slopes
912
+ #
913
+ # the correlated covariance matrix contains:
914
+ #
915
+ # q(q + 1) / 2
916
+ #
917
+ # variance/covariance parameters.
918
+ #
919
+ # The corresponding uncorrelated model contains:
920
+ #
921
+ # q
922
+ #
923
+ # variance parameters.
924
+ #
925
+ # Therefore the number of covariance parameters removed by the
926
+ # uncorrelated parameterization is:
927
+ #
928
+ # q(q - 1) / 2
929
+ #
930
+ # Examples:
931
+ #
932
+ # 1 slope:
933
+ # q = 2
934
+ # df = 1
935
+ #
936
+ # 2 slopes:
937
+ # q = 3
938
+ # df = 3
939
+ #
940
+ # 3 slopes:
941
+ # q = 4
942
+ # df = 6
943
+ #
944
+ # 6 slopes:
945
+ # q = 7
946
+ # df = 21
947
+ # ------------------------------------------------------------
948
+
949
+ covariance_df_difference <- function(
950
+ re_formula
951
+ ) {
952
+
953
+ n_slopes <- count_random_slopes(
954
+ re_formula
955
+ )
956
+
957
+
958
+ q <- 1L + n_slopes
959
+
960
+
961
+ as.integer(
962
+ q * (q - 1L) / 2L
963
+ )
964
+ }
965
+
966
+
967
+
968
+
969
+
970
+ # ============================================================
971
+ # CELL 6 — SELECT MINIMUM-BIC RANDOM-SLOPE COMPOSITION
972
+ # ============================================================
973
+ # Purpose:
974
+ # Reproduce the first stage of the original Step 5 decision
975
+ # procedure.
976
+ #
977
+ # For each DV:
978
+ #
979
+ # 1. Consider all selection-eligible Step 4 candidates across
980
+ # both correlated and uncorrelated parameterizations.
981
+ #
982
+ # 2. Identify the candidate having the minimum BIC.
983
+ #
984
+ # 3. Use the random-slope composition of that candidate as
985
+ # the selected slope structure.
986
+ #
987
+ # 4. Retrieve every eligible parameterization of that SAME
988
+ # slope composition.
989
+ #
990
+ # Thus BIC selects the slope composition before the covariance
991
+ # parameterization is decided.
992
+ #
993
+ # This deliberately differs from selecting the best correlated
994
+ # and best uncorrelated structures independently.
995
+ # ============================================================
996
+
997
+
998
+ # ------------------------------------------------------------
999
+ # 6.1 Add Canonical Slope-Composition Keys
1000
+ # ------------------------------------------------------------
1001
+
1002
+ df_eligible <- df_eligible %>%
1003
+ mutate(
1004
+ Slope_Set_Key = vapply(
1005
+ re_formula,
1006
+ canonical_slope_key,
1007
+ character(1)
1008
+ )
1009
+ )
1010
+
1011
+
1012
+ # ------------------------------------------------------------
1013
+ # 6.2 Identify Global Minimum-BIC Candidate Within Each DV
1014
+ # ------------------------------------------------------------
1015
+
1016
+ minimum_bic_candidates <- df_eligible %>%
1017
+ group_by(
1018
+ `Stage of Reading`,
1019
+ `Reading Measure`,
1020
+ `Dependent Variable Name`
1021
+ ) %>%
1022
+ filter(
1023
+ bic == min(
1024
+ bic,
1025
+ na.rm = TRUE
1026
+ )
1027
+ ) %>%
1028
+ ungroup()
1029
+
1030
+
1031
+ # ------------------------------------------------------------
1032
+ # 6.3 Detect Exact Global Minimum-BIC Ties
1033
+ # ------------------------------------------------------------
1034
+ # An exact tie between DIFFERENT slope compositions cannot be
1035
+ # resolved by the prespecified minimum-BIC rule and therefore
1036
+ # causes an explicit stop.
1037
+ #
1038
+ # Multiple minimum-BIC rows representing the SAME slope
1039
+ # composition under different parameterizations do not create
1040
+ # a slope-selection ambiguity.
1041
+ # ------------------------------------------------------------
1042
+
1043
+ global_bic_tie_check <- minimum_bic_candidates %>%
1044
+ group_by(
1045
+ `Dependent Variable Name`
1046
+ ) %>%
1047
+ summarise(
1048
+ N_Min_BIC_Rows = n(),
1049
+ N_Min_BIC_Slope_Sets =
1050
+ n_distinct(
1051
+ Slope_Set_Key
1052
+ ),
1053
+ .groups = "drop"
1054
+ )
1055
+
1056
+
1057
+ ambiguous_global_ties <- global_bic_tie_check %>%
1058
+ filter(
1059
+ N_Min_BIC_Slope_Sets > 1
1060
+ )
1061
+
1062
+
1063
+ if (nrow(ambiguous_global_ties) > 0) {
1064
+
1065
+ print(
1066
+ ambiguous_global_ties
1067
+ )
1068
+
1069
+
1070
+ tied_models <- minimum_bic_candidates %>%
1071
+ semi_join(
1072
+ ambiguous_global_ties,
1073
+ by = "Dependent Variable Name"
1074
+ ) %>%
1075
+ select(
1076
+ `Stage of Reading`,
1077
+ `Reading Measure`,
1078
+ `Dependent Variable Name`,
1079
+ `Random-Slope Structure`,
1080
+ re_formula,
1081
+ Slope_Set_Key,
1082
+ aic,
1083
+ bic,
1084
+ llf,
1085
+ nobs
1086
+ )
1087
+
1088
+
1089
+ print(
1090
+ tied_models
1091
+ )
1092
+
1093
+
1094
+ stop(
1095
+ "Exact minimum-BIC tie detected between different ",
1096
+ "random-slope compositions for at least one DV. ",
1097
+ "Step 5 stopped rather than resolving the slope-selection ",
1098
+ "ambiguity by row order."
1099
+ )
1100
+ }
1101
+
1102
+
1103
+ # ------------------------------------------------------------
1104
+ # 6.4 Define One Selected Slope Composition per DV
1105
+ # ------------------------------------------------------------
1106
+
1107
+ selected_slope_structures <- minimum_bic_candidates %>%
1108
+ group_by(
1109
+ `Stage of Reading`,
1110
+ `Reading Measure`,
1111
+ `Dependent Variable Name`
1112
+ ) %>%
1113
+ slice(
1114
+ 1
1115
+ ) %>%
1116
+ ungroup() %>%
1117
+ transmute(
1118
+ `Stage of Reading`,
1119
+ `Reading Measure`,
1120
+ `Dependent Variable Name`,
1121
+
1122
+ Selected_Random_Slope_Structure =
1123
+ re_formula,
1124
+
1125
+ Selected_Slope_Set_Key =
1126
+ Slope_Set_Key,
1127
+
1128
+ Selected_Structure_Minimum_BIC =
1129
+ bic
1130
+ )
1131
+
1132
+
1133
+ # ------------------------------------------------------------
1134
+ # 6.5 Verify One Selected Slope Composition per DV
1135
+ # ------------------------------------------------------------
1136
+
1137
+ if (
1138
+ nrow(selected_slope_structures) !=
1139
+ n_distinct(
1140
+ df_all$`Dependent Variable Name`
1141
+ )
1142
+ ) {
1143
+
1144
+ stop(
1145
+ "Step 5 did not identify exactly one minimum-BIC slope ",
1146
+ "composition for every DV."
1147
+ )
1148
+ }
1149
+
1150
+
1151
+ # ------------------------------------------------------------
1152
+ # 6.6 Retrieve Matched Parameterizations
1153
+ # ------------------------------------------------------------
1154
+ # Retrieve only models having the SAME slope composition as the
1155
+ # globally selected minimum-BIC structure.
1156
+ #
1157
+ # For slope-containing structures this can yield:
1158
+ #
1159
+ # one correlated model
1160
+ # one uncorrelated model
1161
+ #
1162
+ # provided both are selection eligible.
1163
+ #
1164
+ # For the intercept-only structure:
1165
+ #
1166
+ # 1
1167
+ #
1168
+ # only one row exists because Step 4 intentionally represents
1169
+ # that shared model once.
1170
+ # ------------------------------------------------------------
1171
+
1172
+ selected_structure_comparison <- df_eligible %>%
1173
+ inner_join(
1174
+ selected_slope_structures %>%
1175
+ select(
1176
+ `Dependent Variable Name`,
1177
+ Selected_Slope_Set_Key
1178
+ ),
1179
+ by = "Dependent Variable Name"
1180
+ ) %>%
1181
+ filter(
1182
+ Slope_Set_Key ==
1183
+ Selected_Slope_Set_Key
1184
+ ) %>%
1185
+ arrange(
1186
+ `Stage of Reading`,
1187
+ `Random-Slope Structure`
1188
+ )
1189
+
1190
+
1191
+ # ------------------------------------------------------------
1192
+ # 6.7 Validate Matched Comparison Sets
1193
+ # ------------------------------------------------------------
1194
+
1195
+ comparison_count_check <- selected_structure_comparison %>%
1196
+ count(
1197
+ `Dependent Variable Name`,
1198
+ `Random-Slope Structure`,
1199
+ name = "N_Models"
1200
+ )
1201
+
1202
+
1203
+ if (
1204
+ any(
1205
+ comparison_count_check$N_Models > 1
1206
+ )
1207
+ ) {
1208
+
1209
+ print(
1210
+ comparison_count_check
1211
+ )
1212
+
1213
+ stop(
1214
+ "Duplicate eligible models detected for the same DV, ",
1215
+ "slope composition, and covariance parameterization."
1216
+ )
1217
+ }
1218
+
1219
+
1220
+ # ------------------------------------------------------------
1221
+ # 6.8 Report Selected Slope Structures
1222
+ # ------------------------------------------------------------
1223
+
1224
+ message(
1225
+ "\nMinimum-BIC random-slope compositions:"
1226
+ )
1227
+
1228
+
1229
+ for (
1230
+ i in seq_len(
1231
+ nrow(
1232
+ selected_slope_structures
1233
+ )
1234
+ )
1235
+ ) {
1236
+
1237
+ message(
1238
+ "Stage ",
1239
+ selected_slope_structures$
1240
+ `Stage of Reading`[i],
1241
+ " — ",
1242
+ selected_slope_structures$
1243
+ `Dependent Variable Name`[i],
1244
+ " — ",
1245
+ selected_slope_structures$
1246
+ Selected_Random_Slope_Structure[i],
1247
+ " | minimum BIC=",
1248
+ round(
1249
+ selected_slope_structures$
1250
+ Selected_Structure_Minimum_BIC[i],
1251
+ 3
1252
+ )
1253
+ )
1254
+ }
1255
+
1256
+
1257
+ message(
1258
+ "Minimum-BIC slope-composition selection completed."
1259
+ )
1260
+
1261
+
1262
+
1263
+
1264
+
1265
+ # ============================================================
1266
+ # CELL 7 — MATCHED CORRELATED/UNCORRELATED DECISION ENGINE
1267
+ # ============================================================
1268
+ # Purpose:
1269
+ # Determine the final participant-level random-effects
1270
+ # parameterization after the minimum-BIC slope composition
1271
+ # has been selected.
1272
+ #
1273
+ # Decision hierarchy:
1274
+ #
1275
+ # CASE A — selected structure is random-intercept only
1276
+ #
1277
+ # The structure:
1278
+ #
1279
+ # 1
1280
+ #
1281
+ # contains no participant-level random slopes and hence
1282
+ # no covariance parameters.
1283
+ #
1284
+ # Correlated versus uncorrelated parameterization is
1285
+ # therefore not applicable. Retain the shared
1286
+ # random-intercept-only structure.
1287
+ #
1288
+ # CASE B — both matched parameterizations are eligible
1289
+ #
1290
+ # Compare correlated and uncorrelated versions of the
1291
+ # SAME selected slope composition using:
1292
+ #
1293
+ # LR = 2 × (logLik_corr - logLik_uncorr)
1294
+ #
1295
+ # with:
1296
+ #
1297
+ # df = q(q - 1) / 2
1298
+ #
1299
+ # where q equals the participant intercept plus the
1300
+ # selected random slopes.
1301
+ #
1302
+ # Decision:
1303
+ #
1304
+ # p < .05 → Correlated
1305
+ # p >= .05 → Uncorrelated
1306
+ #
1307
+ # CASE C — only one matched parameterization is eligible
1308
+ #
1309
+ # Retain the available eligible parameterization.
1310
+ #
1311
+ # Important:
1312
+ # The LRT is performed only after slope composition has been
1313
+ # fixed. Thus the two compared models contain exactly the same
1314
+ # random-effects variables and differ only in whether their
1315
+ # participant-level covariance parameters are estimated.
1316
+ # ============================================================
1317
+
1318
+
1319
+ results_summary <- list()
1320
+
1321
+
1322
+ dv_registry <- df_all %>%
1323
+ distinct(
1324
+ `Stage of Reading`,
1325
+ `Reading Measure`,
1326
+ `Dependent Variable Name`
1327
+ ) %>%
1328
+ arrange(
1329
+ `Stage of Reading`
1330
+ )
1331
+
1332
+
1333
+ message(
1334
+ "\n",
1335
+ strrep("=", 80)
1336
+ )
1337
+
1338
+
1339
+ message(
1340
+ "STARTING STEP 5 — FINAL RANDOM-SLOPE DECISIONS"
1341
+ )
1342
+
1343
+
1344
+ message(
1345
+ "Dataset: Affective Provo"
1346
+ )
1347
+
1348
+
1349
+ message(
1350
+ "Stage 1: minimum-BIC eligible slope composition"
1351
+ )
1352
+
1353
+
1354
+ message(
1355
+ "Stage 2: matched correlated/uncorrelated LRT"
1356
+ )
1357
+
1358
+
1359
+ message(
1360
+ strrep("=", 80)
1361
+ )
1362
+
1363
+
1364
+ for (i in seq_len(nrow(dv_registry))) {
1365
+
1366
+
1367
+ # ----------------------------------------------------------
1368
+ # 7.1 Current DV Metadata
1369
+ # ----------------------------------------------------------
1370
+
1371
+ stage <- dv_registry$
1372
+ `Stage of Reading`[i]
1373
+
1374
+ measure <- dv_registry$
1375
+ `Reading Measure`[i]
1376
+
1377
+ dv <- dv_registry$
1378
+ `Dependent Variable Name`[i]
1379
+
1380
+
1381
+ message(
1382
+ "\n",
1383
+ strrep("-", 72)
1384
+ )
1385
+
1386
+
1387
+ message(
1388
+ "Stage ",
1389
+ stage,
1390
+ " — ",
1391
+ measure,
1392
+ " — ",
1393
+ dv
1394
+ )
1395
+
1396
+
1397
+ # ----------------------------------------------------------
1398
+ # 7.2 Retrieve Selected Slope Composition
1399
+ # ----------------------------------------------------------
1400
+
1401
+ selected_row <- selected_slope_structures %>%
1402
+ filter(
1403
+ `Dependent Variable Name` == dv
1404
+ )
1405
+
1406
+
1407
+ if (nrow(selected_row) != 1) {
1408
+
1409
+ stop(
1410
+ "Expected exactly one selected minimum-BIC slope ",
1411
+ "composition for ",
1412
+ dv,
1413
+ ", but found ",
1414
+ nrow(selected_row),
1415
+ "."
1416
+ )
1417
+ }
1418
+
1419
+
1420
+ selected_formula <-
1421
+ selected_row$
1422
+ Selected_Random_Slope_Structure[1]
1423
+
1424
+
1425
+ selected_key <-
1426
+ selected_row$
1427
+ Selected_Slope_Set_Key[1]
1428
+
1429
+
1430
+ selected_min_bic <-
1431
+ selected_row$
1432
+ Selected_Structure_Minimum_BIC[1]
1433
+
1434
+
1435
+ n_random_slopes <-
1436
+ count_random_slopes(
1437
+ selected_formula
1438
+ )
1439
+
1440
+
1441
+ # ----------------------------------------------------------
1442
+ # 7.3 Retrieve Matched Parameterizations
1443
+ # ----------------------------------------------------------
1444
+
1445
+ comparison_set <- selected_structure_comparison %>%
1446
+ filter(
1447
+ `Dependent Variable Name` == dv,
1448
+ Slope_Set_Key == selected_key
1449
+ )
1450
+
1451
+
1452
+ row_corr <- comparison_set %>%
1453
+ filter(
1454
+ `Random-Slope Structure` ==
1455
+ "Correlated"
1456
+ )
1457
+
1458
+
1459
+ row_uncorr <- comparison_set %>%
1460
+ filter(
1461
+ `Random-Slope Structure` ==
1462
+ "Uncorrelated"
1463
+ )
1464
+
1465
+
1466
+ corr_ok <- (
1467
+ nrow(row_corr) == 1
1468
+ )
1469
+
1470
+
1471
+ uncorr_ok <- (
1472
+ nrow(row_uncorr) == 1
1473
+ )
1474
+
1475
+
1476
+ # ----------------------------------------------------------
1477
+ # 7.4 Initialize Decision Variables
1478
+ # ----------------------------------------------------------
1479
+
1480
+ winner_type <- "None"
1481
+
1482
+ winner_formula <- selected_formula
1483
+
1484
+ winner_bic <- NA_real_
1485
+
1486
+ winner_aic <- NA_real_
1487
+
1488
+ winner_llf <- NA_real_
1489
+
1490
+ winner_nobs <- NA_integer_
1491
+
1492
+ decision_method <- NA_character_
1493
+
1494
+ decision_reason <- NA_character_
1495
+
1496
+ lrt_statistic <- NA_real_
1497
+
1498
+ lrt_df <- NA_integer_
1499
+
1500
+ lrt_p_value <- NA_real_
1501
+
1502
+
1503
+ # ----------------------------------------------------------
1504
+ # 7.5 CASE A — Random-Intercept-Only Structure
1505
+ # ----------------------------------------------------------
1506
+
1507
+ if (n_random_slopes == 0L) {
1508
+
1509
+
1510
+ if (!corr_ok) {
1511
+
1512
+ stop(
1513
+ "The selected random-intercept-only candidate is ",
1514
+ "missing from the correlated/shared Step 4 family for ",
1515
+ dv,
1516
+ "."
1517
+ )
1518
+ }
1519
+
1520
+
1521
+ if (uncorr_ok) {
1522
+
1523
+ stop(
1524
+ "The random-intercept-only candidate unexpectedly ",
1525
+ "appears in the uncorrelated family for ",
1526
+ dv,
1527
+ ". Step 4 should represent this shared structure once."
1528
+ )
1529
+ }
1530
+
1531
+
1532
+ winner_type <-
1533
+ "Random Intercept Only"
1534
+
1535
+
1536
+ winner_formula <-
1537
+ row_corr$re_formula[1]
1538
+
1539
+
1540
+ winner_bic <-
1541
+ row_corr$bic[1]
1542
+
1543
+
1544
+ winner_aic <-
1545
+ row_corr$aic[1]
1546
+
1547
+
1548
+ winner_llf <-
1549
+ row_corr$llf[1]
1550
+
1551
+
1552
+ winner_nobs <-
1553
+ row_corr$nobs[1]
1554
+
1555
+
1556
+ lrt_df <- 0L
1557
+
1558
+
1559
+ decision_method <-
1560
+ "Minimum BIC; covariance comparison not applicable"
1561
+
1562
+
1563
+ decision_reason <- paste(
1564
+ "The minimum-BIC eligible candidate was the",
1565
+ "random-intercept-only structure. Because it contains",
1566
+ "no participant-level random slopes, there are no",
1567
+ "random-effect covariance parameters to test and",
1568
+ "correlated versus uncorrelated parameterization is",
1569
+ "not applicable."
1570
+ )
1571
+
1572
+
1573
+ # ----------------------------------------------------------
1574
+ # 7.6 CASE B — Both Matched Parameterizations Available
1575
+ # ----------------------------------------------------------
1576
+
1577
+ } else if (
1578
+ corr_ok &&
1579
+ uncorr_ok
1580
+ ) {
1581
+
1582
+
1583
+ # --------------------------------------------------------
1584
+ # Verify Equal Observation Counts
1585
+ # --------------------------------------------------------
1586
+
1587
+ if (
1588
+ row_corr$nobs[1] !=
1589
+ row_uncorr$nobs[1]
1590
+ ) {
1591
+
1592
+ stop(
1593
+ "Cannot perform matched correlated/uncorrelated ",
1594
+ "comparison for ",
1595
+ dv,
1596
+ ": observation counts differ."
1597
+ )
1598
+ }
1599
+
1600
+
1601
+ # --------------------------------------------------------
1602
+ # Verify Same Selected Slope Composition
1603
+ # --------------------------------------------------------
1604
+
1605
+ corr_key <- canonical_slope_key(
1606
+ row_corr$re_formula[1]
1607
+ )
1608
+
1609
+
1610
+ uncorr_key <- canonical_slope_key(
1611
+ row_uncorr$re_formula[1]
1612
+ )
1613
+
1614
+
1615
+ if (
1616
+ corr_key != selected_key ||
1617
+ uncorr_key != selected_key
1618
+ ) {
1619
+
1620
+ stop(
1621
+ "Matched parameterization comparison failed for ",
1622
+ dv,
1623
+ ": correlated and uncorrelated models do not contain ",
1624
+ "the selected random-slope composition."
1625
+ )
1626
+ }
1627
+
1628
+
1629
+ # --------------------------------------------------------
1630
+ # Calculate LRT Degrees of Freedom
1631
+ # --------------------------------------------------------
1632
+
1633
+ lrt_df <- covariance_df_difference(
1634
+ selected_formula
1635
+ )
1636
+
1637
+
1638
+ if (lrt_df <= 0L) {
1639
+
1640
+ stop(
1641
+ "Internal LRT error for ",
1642
+ dv,
1643
+ ": a slope-containing structure produced a ",
1644
+ "non-positive covariance-parameter df difference."
1645
+ )
1646
+ }
1647
+
1648
+
1649
+ # --------------------------------------------------------
1650
+ # Calculate Likelihood-Ratio Statistic
1651
+ # --------------------------------------------------------
1652
+
1653
+ raw_lrt_statistic <- (
1654
+ 2 *
1655
+ (
1656
+ row_corr$llf[1] -
1657
+ row_uncorr$llf[1]
1658
+ )
1659
+ )
1660
+
1661
+
1662
+ # Small negative values can arise from numerical optimizer
1663
+ # differences even though the correlated model is the less
1664
+ # constrained parameterization.
1665
+
1666
+ lrt_statistic <- max(
1667
+ 0,
1668
+ raw_lrt_statistic
1669
+ )
1670
+
1671
+
1672
+ lrt_p_value <- pchisq(
1673
+ lrt_statistic,
1674
+ df = lrt_df,
1675
+ lower.tail = FALSE
1676
+ )
1677
+
1678
+
1679
+ # --------------------------------------------------------
1680
+ # Apply Original Decision Rule
1681
+ # --------------------------------------------------------
1682
+
1683
+ if (lrt_p_value < 0.05) {
1684
+
1685
+ winner_type <-
1686
+ "Correlated"
1687
+
1688
+ winner_formula <-
1689
+ row_corr$re_formula[1]
1690
+
1691
+ winner_bic <-
1692
+ row_corr$bic[1]
1693
+
1694
+ winner_aic <-
1695
+ row_corr$aic[1]
1696
+
1697
+ winner_llf <-
1698
+ row_corr$llf[1]
1699
+
1700
+ winner_nobs <-
1701
+ row_corr$nobs[1]
1702
+
1703
+
1704
+ decision_reason <- paste0(
1705
+ "The selected minimum-BIC slope composition was ",
1706
+ "available under both parameterizations. The matched ",
1707
+ "correlated-versus-uncorrelated likelihood-ratio test ",
1708
+ "was significant (p=",
1709
+ sprintf(
1710
+ "%.4f",
1711
+ lrt_p_value
1712
+ ),
1713
+ "), so the correlated parameterization was retained."
1714
+ )
1715
+
1716
+
1717
+ } else {
1718
+
1719
+ winner_type <-
1720
+ "Uncorrelated"
1721
+
1722
+ winner_formula <-
1723
+ row_uncorr$re_formula[1]
1724
+
1725
+ winner_bic <-
1726
+ row_uncorr$bic[1]
1727
+
1728
+ winner_aic <-
1729
+ row_uncorr$aic[1]
1730
+
1731
+ winner_llf <-
1732
+ row_uncorr$llf[1]
1733
+
1734
+ winner_nobs <-
1735
+ row_uncorr$nobs[1]
1736
+
1737
+
1738
+ decision_reason <- paste0(
1739
+ "The selected minimum-BIC slope composition was ",
1740
+ "available under both parameterizations. The matched ",
1741
+ "correlated-versus-uncorrelated likelihood-ratio test ",
1742
+ "was not significant (p=",
1743
+ sprintf(
1744
+ "%.4f",
1745
+ lrt_p_value
1746
+ ),
1747
+ "), so the uncorrelated parameterization was retained ",
1748
+ "on grounds of parsimony."
1749
+ )
1750
+ }
1751
+
1752
+
1753
+ decision_method <-
1754
+ "Minimum-BIC slope composition + matched LRT"
1755
+
1756
+
1757
+ # ----------------------------------------------------------
1758
+ # 7.7 CASE C — Only Correlated Parameterization Available
1759
+ # ----------------------------------------------------------
1760
+
1761
+ } else if (
1762
+ corr_ok &&
1763
+ !uncorr_ok
1764
+ ) {
1765
+
1766
+
1767
+ winner_type <-
1768
+ "Correlated"
1769
+
1770
+
1771
+ winner_formula <-
1772
+ row_corr$re_formula[1]
1773
+
1774
+
1775
+ winner_bic <-
1776
+ row_corr$bic[1]
1777
+
1778
+
1779
+ winner_aic <-
1780
+ row_corr$aic[1]
1781
+
1782
+
1783
+ winner_llf <-
1784
+ row_corr$llf[1]
1785
+
1786
+
1787
+ winner_nobs <-
1788
+ row_corr$nobs[1]
1789
+
1790
+
1791
+ decision_method <-
1792
+ "Minimum-BIC slope composition; only correlated eligible"
1793
+
1794
+
1795
+ decision_reason <- paste(
1796
+ "The selected minimum-BIC slope composition had no",
1797
+ "selection-eligible uncorrelated counterpart; the",
1798
+ "eligible correlated parameterization was retained."
1799
+ )
1800
+
1801
+
1802
+ # ----------------------------------------------------------
1803
+ # 7.8 CASE C — Only Uncorrelated Parameterization Available
1804
+ # ----------------------------------------------------------
1805
+
1806
+ } else if (
1807
+ !corr_ok &&
1808
+ uncorr_ok
1809
+ ) {
1810
+
1811
+
1812
+ winner_type <-
1813
+ "Uncorrelated"
1814
+
1815
+
1816
+ winner_formula <-
1817
+ row_uncorr$re_formula[1]
1818
+
1819
+
1820
+ winner_bic <-
1821
+ row_uncorr$bic[1]
1822
+
1823
+
1824
+ winner_aic <-
1825
+ row_uncorr$aic[1]
1826
+
1827
+
1828
+ winner_llf <-
1829
+ row_uncorr$llf[1]
1830
+
1831
+
1832
+ winner_nobs <-
1833
+ row_uncorr$nobs[1]
1834
+
1835
+
1836
+ decision_method <-
1837
+ "Minimum-BIC slope composition; only uncorrelated eligible"
1838
+
1839
+
1840
+ decision_reason <- paste(
1841
+ "The selected minimum-BIC slope composition had no",
1842
+ "selection-eligible correlated counterpart; the",
1843
+ "eligible uncorrelated parameterization was retained."
1844
+ )
1845
+
1846
+
1847
+ # ----------------------------------------------------------
1848
+ # 7.9 No Matched Eligible Parameterization
1849
+ # ----------------------------------------------------------
1850
+
1851
+ } else {
1852
+
1853
+
1854
+ winner_type <-
1855
+ "None"
1856
+
1857
+
1858
+ winner_formula <-
1859
+ NA_character_
1860
+
1861
+
1862
+ decision_method <-
1863
+ "No eligible matched parameterization"
1864
+
1865
+
1866
+ decision_reason <- paste(
1867
+ "No selection-eligible parameterization was available",
1868
+ "for the selected minimum-BIC slope composition."
1869
+ )
1870
+ }
1871
+
1872
+
1873
+ # ----------------------------------------------------------
1874
+ # 7.10 Store Final Decision
1875
+ # ----------------------------------------------------------
1876
+
1877
+ results_summary[[dv]] <- tibble(
1878
+
1879
+ Stage =
1880
+ stage,
1881
+
1882
+ Reading_Measure =
1883
+ measure,
1884
+
1885
+ DV =
1886
+ dv,
1887
+
1888
+
1889
+ Selected_Slope_Structure =
1890
+ selected_formula,
1891
+
1892
+
1893
+ Selected_N_Random_Slopes =
1894
+ n_random_slopes,
1895
+
1896
+
1897
+ Minimum_BIC_For_Slope_Selection =
1898
+ selected_min_bic,
1899
+
1900
+
1901
+ Correlated_Available =
1902
+ corr_ok,
1903
+
1904
+
1905
+ BIC_Correlated =
1906
+ if (corr_ok) {
1907
+ row_corr$bic[1]
1908
+ } else {
1909
+ NA_real_
1910
+ },
1911
+
1912
+
1913
+ AIC_Correlated =
1914
+ if (corr_ok) {
1915
+ row_corr$aic[1]
1916
+ } else {
1917
+ NA_real_
1918
+ },
1919
+
1920
+
1921
+ LogLik_Correlated =
1922
+ if (corr_ok) {
1923
+ row_corr$llf[1]
1924
+ } else {
1925
+ NA_real_
1926
+ },
1927
+
1928
+
1929
+ Uncorrelated_Available =
1930
+ uncorr_ok,
1931
+
1932
+
1933
+ BIC_Uncorrelated =
1934
+ if (uncorr_ok) {
1935
+ row_uncorr$bic[1]
1936
+ } else {
1937
+ NA_real_
1938
+ },
1939
+
1940
+
1941
+ AIC_Uncorrelated =
1942
+ if (uncorr_ok) {
1943
+ row_uncorr$aic[1]
1944
+ } else {
1945
+ NA_real_
1946
+ },
1947
+
1948
+
1949
+ LogLik_Uncorrelated =
1950
+ if (uncorr_ok) {
1951
+ row_uncorr$llf[1]
1952
+ } else {
1953
+ NA_real_
1954
+ },
1955
+
1956
+
1957
+ LRT_Statistic =
1958
+ lrt_statistic,
1959
+
1960
+
1961
+ LRT_df =
1962
+ lrt_df,
1963
+
1964
+
1965
+ LRT_p_value =
1966
+ lrt_p_value,
1967
+
1968
+
1969
+ Final_Structure_Type =
1970
+ winner_type,
1971
+
1972
+
1973
+ Final_Random_Slope_Structure =
1974
+ winner_formula,
1975
+
1976
+
1977
+ Final_N_Random_Slopes =
1978
+ if (!is.na(winner_formula)) {
1979
+ count_random_slopes(
1980
+ winner_formula
1981
+ )
1982
+ } else {
1983
+ NA_integer_
1984
+ },
1985
+
1986
+
1987
+ Final_BIC =
1988
+ winner_bic,
1989
+
1990
+
1991
+ Final_AIC =
1992
+ winner_aic,
1993
+
1994
+
1995
+ Final_LogLik =
1996
+ winner_llf,
1997
+
1998
+
1999
+ Final_N =
2000
+ winner_nobs,
2001
+
2002
+
2003
+ Decision_Method =
2004
+ decision_method,
2005
+
2006
+
2007
+ Decision_Reason =
2008
+ decision_reason
2009
+ )
2010
+
2011
+
2012
+ # ----------------------------------------------------------
2013
+ # 7.11 Report Final Decision
2014
+ # ----------------------------------------------------------
2015
+
2016
+ message(
2017
+ "Selected slopes : ",
2018
+ selected_formula
2019
+ )
2020
+
2021
+
2022
+ message(
2023
+ "Number of slopes : ",
2024
+ n_random_slopes
2025
+ )
2026
+
2027
+
2028
+ message(
2029
+ "Minimum BIC : ",
2030
+ round(
2031
+ selected_min_bic,
2032
+ 3
2033
+ )
2034
+ )
2035
+
2036
+
2037
+ message(
2038
+ "Correlated match : ",
2039
+ if (corr_ok) {
2040
+ paste0(
2041
+ "BIC=",
2042
+ round(
2043
+ row_corr$bic[1],
2044
+ 3
2045
+ )
2046
+ )
2047
+ } else {
2048
+ "Not eligible / unavailable"
2049
+ }
2050
+ )
2051
+
2052
+
2053
+ message(
2054
+ "Uncorrelated match : ",
2055
+ if (uncorr_ok) {
2056
+ paste0(
2057
+ "BIC=",
2058
+ round(
2059
+ row_uncorr$bic[1],
2060
+ 3
2061
+ )
2062
+ )
2063
+ } else {
2064
+ "Not eligible / unavailable"
2065
+ }
2066
+ )
2067
+
2068
+
2069
+ message(
2070
+ "LRT : ",
2071
+ if (is.na(lrt_p_value)) {
2072
+ "Not applicable"
2073
+ } else {
2074
+ paste0(
2075
+ "Chi-square=",
2076
+ round(
2077
+ lrt_statistic,
2078
+ 3
2079
+ ),
2080
+ ", df=",
2081
+ lrt_df,
2082
+ ", p=",
2083
+ sprintf(
2084
+ "%.4f",
2085
+ lrt_p_value
2086
+ )
2087
+ )
2088
+ }
2089
+ )
2090
+
2091
+
2092
+ message(
2093
+ "Final structure : ",
2094
+ winner_type
2095
+ )
2096
+
2097
+
2098
+ message(
2099
+ "Decision method : ",
2100
+ decision_method
2101
+ )
2102
+ }
2103
+
2104
+
2105
+
2106
+
2107
+
2108
+ # ============================================================
2109
+ # CELL 8 — ASSEMBLE FINAL DECISION TABLE
2110
+ # ============================================================
2111
+ # Purpose:
2112
+ # Combine the DV-specific decisions generated in Cell 7 into
2113
+ # one ordered final decision table.
2114
+ #
2115
+ # The resulting table records:
2116
+ #
2117
+ # - minimum-BIC selected random-slope composition
2118
+ # - number of selected random slopes
2119
+ # - matched correlated model statistics
2120
+ # - matched uncorrelated model statistics
2121
+ # - LRT statistic
2122
+ # - LRT degrees of freedom
2123
+ # - LRT p-value
2124
+ # - final covariance parameterization
2125
+ # - final random-slope structure
2126
+ # - final fit statistics
2127
+ # - decision method and interpretation
2128
+ # ============================================================
2129
+
2130
+
2131
+ final_decisions <- bind_rows(
2132
+ results_summary
2133
+ ) %>%
2134
+ arrange(
2135
+ Stage
2136
+ )
2137
+
2138
+
2139
+ print(
2140
+ final_decisions
2141
+ )
2142
+
2143
+
2144
+
2145
+
2146
+
2147
+ # ============================================================
2148
+ # CELL 9 — FINAL CONSISTENCY CHECKS
2149
+ # ============================================================
2150
+ # Purpose:
2151
+ # Perform defensive validation of the completed Step 5
2152
+ # decision table before results are exported.
2153
+ #
2154
+ # Checks:
2155
+ # 1. Exactly one decision row exists for every duration DV.
2156
+ # 2. Dependent-variable identifiers are unique.
2157
+ # 3. Reading-stage identifiers are unique.
2158
+ # 4. Final structure labels are valid.
2159
+ # 5. Selected models contain finite BIC/AIC/log-likelihood.
2160
+ # 6. Selected models contain valid positive observation
2161
+ # counts.
2162
+ # 7. Final random-slope counts agree with the selected
2163
+ # random-slope formula.
2164
+ # 8. Every LRT has valid statistic, df, and p-value.
2165
+ # 9. LRTs occur only for slope-containing structures having
2166
+ # both matched parameterizations available.
2167
+ # 10. Random-intercept-only selections do not receive an LRT.
2168
+ # ============================================================
2169
+
2170
+
2171
+ # ------------------------------------------------------------
2172
+ # 9.1 One Final Decision Per DV
2173
+ # ------------------------------------------------------------
2174
+
2175
+ if (
2176
+ nrow(final_decisions) !=
2177
+ nrow(dv_registry)
2178
+ ) {
2179
+
2180
+ stop(
2181
+ "Final decision table does not contain exactly one row ",
2182
+ "for every duration DV."
2183
+ )
2184
+ }
2185
+
2186
+
2187
+ # ------------------------------------------------------------
2188
+ # 9.2 Confirm DV Uniqueness
2189
+ # ------------------------------------------------------------
2190
+
2191
+ if (
2192
+ anyDuplicated(
2193
+ final_decisions$DV
2194
+ ) > 0
2195
+ ) {
2196
+
2197
+ stop(
2198
+ "Duplicate dependent-variable decisions detected in the ",
2199
+ "final Step 5 decision table."
2200
+ )
2201
+ }
2202
+
2203
+
2204
+ # ------------------------------------------------------------
2205
+ # 9.3 Confirm Stage Uniqueness
2206
+ # ------------------------------------------------------------
2207
+
2208
+ if (
2209
+ anyDuplicated(
2210
+ final_decisions$Stage
2211
+ ) > 0
2212
+ ) {
2213
+
2214
+ stop(
2215
+ "Duplicate reading-stage decisions detected."
2216
+ )
2217
+ }
2218
+
2219
+
2220
+ # ------------------------------------------------------------
2221
+ # 9.4 Validate Final Structure Labels
2222
+ # ------------------------------------------------------------
2223
+
2224
+ valid_final_structure_types <- c(
2225
+ "Correlated",
2226
+ "Uncorrelated",
2227
+ "Random Intercept Only",
2228
+ "None"
2229
+ )
2230
+
2231
+
2232
+ unexpected_final_structure_types <- setdiff(
2233
+ unique(
2234
+ final_decisions$Final_Structure_Type
2235
+ ),
2236
+ valid_final_structure_types
2237
+ )
2238
+
2239
+
2240
+ if (
2241
+ length(
2242
+ unexpected_final_structure_types
2243
+ ) > 0
2244
+ ) {
2245
+
2246
+ stop(
2247
+ "Unexpected final random-effects structure type(s): ",
2248
+ paste(
2249
+ unexpected_final_structure_types,
2250
+ collapse = ", "
2251
+ )
2252
+ )
2253
+ }
2254
+
2255
+
2256
+ # ------------------------------------------------------------
2257
+ # 9.5 Identify DVs With a Selected Final Model
2258
+ # ------------------------------------------------------------
2259
+
2260
+ has_final_model <- (
2261
+ final_decisions$Final_Structure_Type !=
2262
+ "None"
2263
+ )
2264
+
2265
+
2266
+ # ------------------------------------------------------------
2267
+ # 9.6 Validate Final Fit Statistics
2268
+ # ------------------------------------------------------------
2269
+
2270
+ if (
2271
+ any(
2272
+ has_final_model &
2273
+ (
2274
+ !is.finite(
2275
+ final_decisions$Final_BIC
2276
+ ) |
2277
+ !is.finite(
2278
+ final_decisions$Final_AIC
2279
+ ) |
2280
+ !is.finite(
2281
+ final_decisions$Final_LogLik
2282
+ )
2283
+ )
2284
+ )
2285
+ ) {
2286
+
2287
+ stop(
2288
+ "At least one selected final model has a missing, invalid, ",
2289
+ "or non-finite BIC/AIC/log-likelihood value."
2290
+ )
2291
+ }
2292
+
2293
+
2294
+ # ------------------------------------------------------------
2295
+ # 9.7 Validate Final Observation Counts
2296
+ # ------------------------------------------------------------
2297
+
2298
+ if (
2299
+ any(
2300
+ has_final_model &
2301
+ (
2302
+ is.na(
2303
+ final_decisions$Final_N
2304
+ ) |
2305
+ final_decisions$Final_N <= 0
2306
+ )
2307
+ )
2308
+ ) {
2309
+
2310
+ stop(
2311
+ "At least one selected final model has a missing or ",
2312
+ "non-positive observation count."
2313
+ )
2314
+ }
2315
+
2316
+
2317
+ # ------------------------------------------------------------
2318
+ # 9.8 Validate Final Random-Slope Structures
2319
+ # ------------------------------------------------------------
2320
+
2321
+ if (
2322
+ any(
2323
+ has_final_model &
2324
+ is.na(
2325
+ final_decisions$
2326
+ Final_Random_Slope_Structure
2327
+ )
2328
+ )
2329
+ ) {
2330
+
2331
+ stop(
2332
+ "At least one selected final model is missing its random-",
2333
+ "slope structure specification."
2334
+ )
2335
+ }
2336
+
2337
+
2338
+ # ------------------------------------------------------------
2339
+ # 9.9 Verify Final Random-Slope Counts
2340
+ # ------------------------------------------------------------
2341
+
2342
+ expected_final_slope_counts <- vapply(
2343
+ final_decisions$
2344
+ Final_Random_Slope_Structure,
2345
+ function(x) {
2346
+
2347
+ if (is.na(x)) {
2348
+
2349
+ return(
2350
+ NA_integer_
2351
+ )
2352
+ }
2353
+
2354
+
2355
+ count_random_slopes(
2356
+ x
2357
+ )
2358
+ },
2359
+ integer(1)
2360
+ )
2361
+
2362
+
2363
+ slope_count_mismatch <- which(
2364
+ has_final_model &
2365
+ (
2366
+ is.na(
2367
+ final_decisions$
2368
+ Final_N_Random_Slopes
2369
+ ) |
2370
+ final_decisions$
2371
+ Final_N_Random_Slopes !=
2372
+ expected_final_slope_counts
2373
+ )
2374
+ )
2375
+
2376
+
2377
+ if (
2378
+ length(
2379
+ slope_count_mismatch
2380
+ ) > 0
2381
+ ) {
2382
+
2383
+ stop(
2384
+ "Final random-slope count is inconsistent with the ",
2385
+ "selected random-slope formula for ",
2386
+ length(
2387
+ slope_count_mismatch
2388
+ ),
2389
+ " DV(s)."
2390
+ )
2391
+ }
2392
+
2393
+
2394
+ # ------------------------------------------------------------
2395
+ # 9.10 Validate LRT Results
2396
+ # ------------------------------------------------------------
2397
+
2398
+ lrt_performed <- (
2399
+ !is.na(
2400
+ final_decisions$LRT_p_value
2401
+ )
2402
+ )
2403
+
2404
+
2405
+ if (
2406
+ any(
2407
+ lrt_performed &
2408
+ (
2409
+ !is.finite(
2410
+ final_decisions$LRT_Statistic
2411
+ ) |
2412
+ final_decisions$LRT_Statistic < 0 |
2413
+ is.na(
2414
+ final_decisions$LRT_df
2415
+ ) |
2416
+ final_decisions$LRT_df <= 0 |
2417
+ !is.finite(
2418
+ final_decisions$LRT_p_value
2419
+ ) |
2420
+ final_decisions$LRT_p_value < 0 |
2421
+ final_decisions$LRT_p_value > 1
2422
+ )
2423
+ )
2424
+ ) {
2425
+
2426
+ stop(
2427
+ "Invalid likelihood-ratio test result detected."
2428
+ )
2429
+ }
2430
+
2431
+
2432
+ # ------------------------------------------------------------
2433
+ # 9.11 Verify LRT Is Restricted to Matched Slope Models
2434
+ # ------------------------------------------------------------
2435
+
2436
+ if (
2437
+ any(
2438
+ lrt_performed &
2439
+ (
2440
+ !final_decisions$
2441
+ Correlated_Available |
2442
+ !final_decisions$
2443
+ Uncorrelated_Available |
2444
+ final_decisions$
2445
+ Selected_N_Random_Slopes <= 0
2446
+ )
2447
+ )
2448
+ ) {
2449
+
2450
+ stop(
2451
+ "An LRT was recorded without two matched eligible ",
2452
+ "slope-containing parameterizations."
2453
+ )
2454
+ }
2455
+
2456
+
2457
+ # ------------------------------------------------------------
2458
+ # 9.12 Verify LRT Degrees of Freedom
2459
+ # ------------------------------------------------------------
2460
+
2461
+ expected_lrt_df <- vapply(
2462
+ final_decisions$
2463
+ Selected_Slope_Structure,
2464
+ covariance_df_difference,
2465
+ integer(1)
2466
+ )
2467
+
2468
+
2469
+ lrt_df_mismatch <- which(
2470
+ lrt_performed &
2471
+ (
2472
+ final_decisions$LRT_df !=
2473
+ expected_lrt_df
2474
+ )
2475
+ )
2476
+
2477
+
2478
+ if (
2479
+ length(
2480
+ lrt_df_mismatch
2481
+ ) > 0
2482
+ ) {
2483
+
2484
+ stop(
2485
+ "LRT degrees of freedom are inconsistent with the ",
2486
+ "selected random-slope composition for ",
2487
+ length(
2488
+ lrt_df_mismatch
2489
+ ),
2490
+ " DV(s)."
2491
+ )
2492
+ }
2493
+
2494
+
2495
+ # ------------------------------------------------------------
2496
+ # 9.13 Verify Random-Intercept-Only Handling
2497
+ # ------------------------------------------------------------
2498
+
2499
+ intercept_only <- (
2500
+ final_decisions$
2501
+ Selected_N_Random_Slopes == 0
2502
+ )
2503
+
2504
+
2505
+ if (
2506
+ any(
2507
+ intercept_only &
2508
+ !is.na(
2509
+ final_decisions$LRT_p_value
2510
+ )
2511
+ )
2512
+ ) {
2513
+
2514
+ stop(
2515
+ "Random-intercept-only structures must not receive a ",
2516
+ "correlated-versus-uncorrelated LRT."
2517
+ )
2518
+ }
2519
+
2520
+
2521
+ if (
2522
+ any(
2523
+ intercept_only &
2524
+ final_decisions$
2525
+ Final_Structure_Type !=
2526
+ "Random Intercept Only"
2527
+ )
2528
+ ) {
2529
+
2530
+ stop(
2531
+ "A selected random-intercept-only structure received an ",
2532
+ "unexpected final parameterization label."
2533
+ )
2534
+ }
2535
+
2536
+
2537
+ # ------------------------------------------------------------
2538
+ # 9.14 Validate LRT-Based Final Decisions
2539
+ # ------------------------------------------------------------
2540
+
2541
+ if (
2542
+ any(
2543
+ lrt_performed &
2544
+ final_decisions$LRT_p_value < 0.05 &
2545
+ final_decisions$Final_Structure_Type !=
2546
+ "Correlated"
2547
+ )
2548
+ ) {
2549
+
2550
+ stop(
2551
+ "At least one significant matched LRT did not produce a ",
2552
+ "correlated final structure."
2553
+ )
2554
+ }
2555
+
2556
+
2557
+ if (
2558
+ any(
2559
+ lrt_performed &
2560
+ final_decisions$LRT_p_value >= 0.05 &
2561
+ final_decisions$Final_Structure_Type !=
2562
+ "Uncorrelated"
2563
+ )
2564
+ ) {
2565
+
2566
+ stop(
2567
+ "At least one nonsignificant matched LRT did not produce ",
2568
+ "an uncorrelated final structure."
2569
+ )
2570
+ }
2571
+
2572
+
2573
+ # ------------------------------------------------------------
2574
+ # 9.15 Warn if Any DV Has No Final Eligible Model
2575
+ # ------------------------------------------------------------
2576
+
2577
+ if (
2578
+ any(
2579
+ final_decisions$
2580
+ Final_Structure_Type ==
2581
+ "None"
2582
+ )
2583
+ ) {
2584
+
2585
+ no_model_dvs <- final_decisions$DV[
2586
+ final_decisions$
2587
+ Final_Structure_Type ==
2588
+ "None"
2589
+ ]
2590
+
2591
+
2592
+ warning(
2593
+ "No final selection-eligible random-effects model was ",
2594
+ "identified for: ",
2595
+ paste(
2596
+ no_model_dvs,
2597
+ collapse = ", "
2598
+ )
2599
+ )
2600
+ }
2601
+
2602
+
2603
+ # ------------------------------------------------------------
2604
+ # 9.16 Confirm Successful Final Validation
2605
+ # ------------------------------------------------------------
2606
+
2607
+ if (
2608
+ all(
2609
+ final_decisions$
2610
+ Final_Structure_Type !=
2611
+ "None"
2612
+ )
2613
+ ) {
2614
+
2615
+ message(
2616
+ "Final consistency checks passed: exactly one valid final ",
2617
+ "random-effects decision was identified for every DV."
2618
+ )
2619
+ }
2620
+
2621
+
2622
+
2623
+
2624
+
2625
+ # ============================================================
2626
+ # CELL 10 — CREATE FINAL STEP 5 WORKBOOK
2627
+ # ============================================================
2628
+ # Purpose:
2629
+ # Export:
2630
+ #
2631
+ # Final_Decisions
2632
+ # → final random-slope and covariance decision for
2633
+ # each duration DV
2634
+ #
2635
+ # Selected_Structure_Comparison
2636
+ # → eligible correlated and uncorrelated versions of
2637
+ # the minimum-BIC selected slope composition
2638
+ #
2639
+ # This output mirrors the two-stage decision framework:
2640
+ #
2641
+ # BIC selects slope composition
2642
+ # ↓
2643
+ # matched LRT selects covariance parameterization
2644
+ # ============================================================
2645
+
2646
+
2647
+ wb <- createWorkbook()
2648
+
2649
+
2650
+ # ------------------------------------------------------------
2651
+ # 10.1 Final Decisions
2652
+ # ------------------------------------------------------------
2653
+
2654
+ addWorksheet(
2655
+ wb,
2656
+ "Final_Decisions"
2657
+ )
2658
+
2659
+
2660
+ writeData(
2661
+ wb,
2662
+ "Final_Decisions",
2663
+ final_decisions,
2664
+ withFilter = TRUE
2665
+ )
2666
+
2667
+
2668
+ # ------------------------------------------------------------
2669
+ # 10.2 Selected Structure Comparison
2670
+ # ------------------------------------------------------------
2671
+
2672
+ addWorksheet(
2673
+ wb,
2674
+ "Selected_Structure_Comparison"
2675
+ )
2676
+
2677
+
2678
+ writeData(
2679
+ wb,
2680
+ "Selected_Structure_Comparison",
2681
+ selected_structure_comparison,
2682
+ withFilter = TRUE
2683
+ )
2684
+
2685
+
2686
+
2687
+
2688
+
2689
+ # ============================================================
2690
+ # CELL 11 — EXCEL STYLING
2691
+ # ============================================================
2692
+
2693
+
2694
+ # ------------------------------------------------------------
2695
+ # 11.1 Define Styles
2696
+ # ------------------------------------------------------------
2697
+
2698
+ style_header <- createStyle(
2699
+ textDecoration = "bold",
2700
+ halign = "center",
2701
+ valign = "center",
2702
+ border = "TopBottomLeftRight",
2703
+ borderStyle = "thin"
2704
+ )
2705
+
2706
+
2707
+ style_border <- createStyle(
2708
+ border = "TopBottomLeftRight",
2709
+ borderStyle = "thin"
2710
+ )
2711
+
2712
+
2713
+ style_stage1 <- createStyle(
2714
+ fgFill = "#E0F7FA"
2715
+ )
2716
+
2717
+
2718
+ style_stage2 <- createStyle(
2719
+ fgFill = "#E8F5E9"
2720
+ )
2721
+
2722
+
2723
+ style_stage3 <- createStyle(
2724
+ fgFill = "#FFF3E0"
2725
+ )
2726
+
2727
+
2728
+ style_stage4 <- createStyle(
2729
+ fgFill = "#F3E5F5"
2730
+ )
2731
+
2732
+
2733
+ # ------------------------------------------------------------
2734
+ # 11.2 Apply Header Styles
2735
+ # ------------------------------------------------------------
2736
+
2737
+ addStyle(
2738
+ wb,
2739
+ "Final_Decisions",
2740
+ style_header,
2741
+ rows = 1,
2742
+ cols = seq_len(
2743
+ ncol(final_decisions)
2744
+ ),
2745
+ gridExpand = TRUE,
2746
+ stack = TRUE
2747
+ )
2748
+
2749
+
2750
+ addStyle(
2751
+ wb,
2752
+ "Selected_Structure_Comparison",
2753
+ style_header,
2754
+ rows = 1,
2755
+ cols = seq_len(
2756
+ ncol(
2757
+ selected_structure_comparison
2758
+ )
2759
+ ),
2760
+ gridExpand = TRUE,
2761
+ stack = TRUE
2762
+ )
2763
+
2764
+
2765
+
2766
+
2767
+
2768
+ # ============================================================
2769
+ # CELL 12 — STAGE-SPECIFIC FINAL-DECISION FORMATTING
2770
+ # ============================================================
2771
+
2772
+
2773
+ rows_s1 <- which(
2774
+ final_decisions$Stage == 1
2775
+ ) + 1
2776
+
2777
+ rows_s2 <- which(
2778
+ final_decisions$Stage == 2
2779
+ ) + 1
2780
+
2781
+ rows_s3 <- which(
2782
+ final_decisions$Stage == 3
2783
+ ) + 1
2784
+
2785
+ rows_s4 <- which(
2786
+ final_decisions$Stage == 4
2787
+ ) + 1
2788
+
2789
+
2790
+ if (length(rows_s1) > 0) {
2791
+
2792
+ addStyle(
2793
+ wb,
2794
+ "Final_Decisions",
2795
+ style_stage1,
2796
+ rows = rows_s1,
2797
+ cols = seq_len(
2798
+ ncol(final_decisions)
2799
+ ),
2800
+ gridExpand = TRUE,
2801
+ stack = TRUE
2802
+ )
2803
+ }
2804
+
2805
+
2806
+ if (length(rows_s2) > 0) {
2807
+
2808
+ addStyle(
2809
+ wb,
2810
+ "Final_Decisions",
2811
+ style_stage2,
2812
+ rows = rows_s2,
2813
+ cols = seq_len(
2814
+ ncol(final_decisions)
2815
+ ),
2816
+ gridExpand = TRUE,
2817
+ stack = TRUE
2818
+ )
2819
+ }
2820
+
2821
+
2822
+ if (length(rows_s3) > 0) {
2823
+
2824
+ addStyle(
2825
+ wb,
2826
+ "Final_Decisions",
2827
+ style_stage3,
2828
+ rows = rows_s3,
2829
+ cols = seq_len(
2830
+ ncol(final_decisions)
2831
+ ),
2832
+ gridExpand = TRUE,
2833
+ stack = TRUE
2834
+ )
2835
+ }
2836
+
2837
+
2838
+ if (length(rows_s4) > 0) {
2839
+
2840
+ addStyle(
2841
+ wb,
2842
+ "Final_Decisions",
2843
+ style_stage4,
2844
+ rows = rows_s4,
2845
+ cols = seq_len(
2846
+ ncol(final_decisions)
2847
+ ),
2848
+ gridExpand = TRUE,
2849
+ stack = TRUE
2850
+ )
2851
+ }
2852
+
2853
+
2854
+
2855
+
2856
+
2857
+ # ============================================================
2858
+ # CELL 13 — BORDERS, WIDTHS, AND FREEZE PANES
2859
+ # ============================================================
2860
+
2861
+
2862
+ # ------------------------------------------------------------
2863
+ # 13.1 Final Decisions
2864
+ # ------------------------------------------------------------
2865
+
2866
+ addStyle(
2867
+ wb,
2868
+ "Final_Decisions",
2869
+ style_border,
2870
+ rows = seq_len(
2871
+ nrow(final_decisions) + 1
2872
+ ),
2873
+ cols = seq_len(
2874
+ ncol(final_decisions)
2875
+ ),
2876
+ gridExpand = TRUE,
2877
+ stack = TRUE
2878
+ )
2879
+
2880
+
2881
+ setColWidths(
2882
+ wb,
2883
+ "Final_Decisions",
2884
+ cols = seq_len(
2885
+ ncol(final_decisions)
2886
+ ),
2887
+ widths = "auto"
2888
+ )
2889
+
2890
+
2891
+ freezePane(
2892
+ wb,
2893
+ "Final_Decisions",
2894
+ firstRow = TRUE
2895
+ )
2896
+
2897
+
2898
+ # ------------------------------------------------------------
2899
+ # 13.2 Selected Structure Comparison
2900
+ # ------------------------------------------------------------
2901
+
2902
+ addStyle(
2903
+ wb,
2904
+ "Selected_Structure_Comparison",
2905
+ style_border,
2906
+ rows = seq_len(
2907
+ nrow(
2908
+ selected_structure_comparison
2909
+ ) + 1
2910
+ ),
2911
+ cols = seq_len(
2912
+ ncol(
2913
+ selected_structure_comparison
2914
+ )
2915
+ ),
2916
+ gridExpand = TRUE,
2917
+ stack = TRUE
2918
+ )
2919
+
2920
+
2921
+ setColWidths(
2922
+ wb,
2923
+ "Selected_Structure_Comparison",
2924
+ cols = seq_len(
2925
+ ncol(
2926
+ selected_structure_comparison
2927
+ )
2928
+ ),
2929
+ widths = "auto"
2930
+ )
2931
+
2932
+
2933
+ freezePane(
2934
+ wb,
2935
+ "Selected_Structure_Comparison",
2936
+ firstRow = TRUE
2937
+ )
2938
+
2939
+
2940
+
2941
+
2942
+
2943
+ # ============================================================
2944
+ # CELL 14 — SAVE FINAL STEP 5 WORKBOOK
2945
+ # ============================================================
2946
+
2947
+ saveWorkbook(
2948
+ wb,
2949
+ OUTPUT_FILE,
2950
+ overwrite = TRUE
2951
+ )
2952
+
2953
+
2954
+ message(
2955
+ "\n",
2956
+ strrep("=", 80)
2957
+ )
2958
+
2959
+ message(
2960
+ "STEP 5 COMPLETED SUCCESSFULLY"
2961
+ )
2962
+
2963
+ message(
2964
+ "Dataset: Affective Provo"
2965
+ )
2966
+
2967
+ message(
2968
+ "Final DV decisions: ",
2969
+ nrow(
2970
+ final_decisions
2971
+ )
2972
+ )
2973
+
2974
+ message(
2975
+ "Output: ",
2976
+ OUTPUT_FILE
2977
+ )
2978
+
2979
+ message(
2980
+ strrep("=", 80)
2981
+ )