-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDyadicDataAnalysis.Rmd
More file actions
3799 lines (3035 loc) · 125 KB
/
Copy pathDyadicDataAnalysis.Rmd
File metadata and controls
3799 lines (3035 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Distinguishable and Exchangeable Dyads: Bayesian Multilevel Modelling"
subtitle: "Cross-Sectional and Intensive Longitudinal APIM and DIM"
author: "Pascal M. Küng"
date: "last-modified"
abstract: >
This tutorial presents applied Bayesian multilevel modelling for dyadic data,
covering both distinguishable and exchangeable dyads. We develop cross-sectional
and intensive longitudinal variants of the Actor–Partner Interdependence Model
(APIM) and the Dyad–Individual Model (DIM), demonstrate their algebraic
equivalence, and discuss implications for interpretation. Using simulated data,
we provide fully reproducible code to rebuild the models and assess parameter
recovery. The tutorial offers comprehensive {brms} implementations, including
random-effects structures, heterogeneous residual variances, compound-symmetry
residuals, and optional AR(1) processes. We illustrate diagnostics and model
comparison and show how to extract dyad-level variance–covariance components.
keywords:
- dyadic data
- APIM
- DIM
- Bayesian multilevel modelling
- brms
- cmdstanr
- longitudinal diary data
- compound symmetry
- leave-one-out cross-validation
format:
revealjs:
embed-resources: true
mathjax: embed
theme: default
slide-number: "c/t"
progress: true
hash: true
preview-links: auto
auto-animate: true
code-line-numbers: true
incremental: false
code-overflow: wrap
code-copy: true
code-tools: false
toc: false
df-print: default
transition: slide
transition-speed: fast
link-external-newwindow: true
footer: "<span>Dyadic Multilevel Modelling • brms/cmdstanr • Pascal Küng</span>"
css: Embed/styles.css
include-after-body: Embed/fit-scroll-blocks.html
pdf:
pdf-engine: xelatex
include-in-header:
text: |
% Code/output wrapping
\usepackage{fvextra}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{fontsize=\small,breaklines,breakanywhere,commandchars=\\\{\}}
\fvset{breaklines,breakanywhere}
% Tighter tables and more flexible line breaking
\usepackage{etoolbox}
\AtBeginEnvironment{longtable}{\setlength{\tabcolsep}{4pt}\renewcommand{\arraystretch}{0.95}\small}
\AtBeginEnvironment{CSLReferences}{\small}
\emergencystretch=2em
\usepackage{pdflscape}
\usepackage{needspace}
include-before-body:
text: |
\RecustomVerbatimEnvironment{Highlighting}{Verbatim}{fontsize=\scriptsize,breaklines,breakanywhere,commandchars=\\\{\}}
toc: false
toc-depth: 2
number-sections: true
papersize: a4
geometry: ["margin=1in"]
colorlinks: true
df-print: default
lang: en
bibliography:
- Embed/Temp.bib
- Embed/Rpackages.bib
csl: Embed/apa.csl
nocite: |
@R-brms, @R-bmlm, @R-easystats, @R-DHARMa, @R-tidyverse, @R-cmdstanr, @R-loo, @R-rstan, @R-MASS, @R-nlme
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
cache.lazy = FALSE,
cache.extra = paste(
"dyadMLM-canonical-column-schema-v3",
if (knitr::is_latex_output()) "pdf-output-font-v1" else "html-output"
)
)
rm(list = ls())
gc()
default_output_hook <- knitr::knit_hooks$get("output")
knitr::knit_hooks$set(output = function(x, options) {
out <- default_output_hook(x, options)
if (knitr::is_latex_output()) {
return(paste0("\\begingroup\\scriptsize\n", out, "\n\\endgroup\n"))
}
out
})
library(glue)
options(knitr.kable.NA = "", width = 120)
if (knitr::is_html_output()) {
# kableExtra's HTML table helper initializes tooltips with jQuery.
knitr::knit_meta_add(list(jquerylib::jquery_core()))
}
```
::: {.content-visible when-format="pdf"}
> **Interactive HTML version (recommended):**
> The tutorial is best viewed as [interactive slides](https://pascal-kueng.github.io/05DyadicDataAnalysis/DyadicDataAnalysis.html).
> This PDF is a static archival version for indexing, citation, and long-term reference.
**DOI:** [10.5281/zenodo.17400655](https://doi.org/10.5281/zenodo.17400655)
**Suggested citation:** Küng, P. M. (2026). *Distinguishable and Exchangeable Dyads: Bayesian Multilevel Modelling* (Version 2.0.12) [Report]. Zenodo. [https://doi.org/10.5281/zenodo.17400655](https://doi.org/10.5281/zenodo.17400655)
The [GitHub repository](https://github.com/Pascal-Kueng/05DyadicDataAnalysis) contains the source, helpers, model code, and quick guides.
:::
## Overview
* Distinguishable Dyads
* Cross-Sectional APIM
* Longitudinal APIM
* Exchangeable Dyads
* Cross-Sectional APIM
* Cross-Sectional DIM
* Equivalence between APIM and DIM
* Longitudinal DIM
* Longitudinal APIM
## Quick Access
For readers who want the model code and reporting tables without the full tutorial:
* [Distinguishable dyads quick guide](distinguishable-dyads-quick-guide.pdf)
* [Exchangeable dyads quick guide](exchangeable-dyads-quick-guide.pdf)
## Preparing Dyadic Data with `dyadMLM`
[`dyadMLM`](https://pascal-kueng.github.io/dyadMLM/) prepares dyadic data for multilevel models [@dyadMLM2026]. It:
* validates long-format dyadic data
* supports cross-sectional and intensive longitudinal designs
* creates model-ready variables for APIM, DIM, and DSM specifications
* handles distinguishable, exchangeable, and mixed dyad compositions
Install the current [R-universe version](https://pascal-kueng.r-universe.dev/dyadMLM),
using CRAN for dependencies:
```r
install.packages("dyadMLM", repos = c(
"https://pascal-kueng.r-universe.dev",
"https://cloud.r-project.org"
))
```
[Getting started](https://pascal-kueng.github.io/dyadMLM/articles/getting-started.html) · [Function reference](https://pascal-kueng.github.io/dyadMLM/reference/index.html) · [Source code](https://github.com/Pascal-Kueng/dyadMLM)
## Loading Libraries and setting CmdStan Backend
Some functions used in this presentation are sourced from the files available
in the folder 00_R_Functions.
```{r load-libraries, results='hide', message=FALSE, warning=FALSE}
library(tidyverse)
library(dyadMLM)
library(brms)
library(glmmTMB)
library(easystats)
library(DiagrammeR)
library(DHARMa)
library(MASS)
library(purrr)
source(file.path('00_R_Functions', 'ReportModels.R'))
source(file.path('00_R_Functions', 'PrettyTables.R'))
print_apim_preview <- function(df) {
preview_cols <- c(
"userID", "coupleID", "gender", ".is_male", ".is_female",
".member_contrast_arbitrary", "satisfaction",
".communication_gmc_actor", ".communication_gmc_partner"
)
df <- df |>
dplyr::select(dplyr::any_of(preview_cols))
print_df(head(df))
}
options(
brms.backend = 'cmdstanr',
brms.file_refit = 'on_change'
)
```
```{r simulate-cross-sectional-data, echo=FALSE, results='hide', cache=TRUE}
# --- Packages (explicit namespacing avoids conflicts) ---
set.seed(123)
# --- 1. Define Simulation Parameters ---
# Sample Size
n_het <- 550 # Number of heterosexual couples
n_ss <- 400 # Number of same-sex couples
n_total <- n_het + n_ss
# Residual SDs by gender / dyad type (unchanged)
sd_e_het_female <- 1.1
sd_e_het_male <- 1.4
sd_e_ss_female <- 0.9 # (SS individuals coded female in this example)
# sd_e_ss_male <- ... # if you add male–male couples
# --- NEW: Residual correlations by dyad type (compound symmetry) ---
rho_e_het <- 0.30
rho_e_ss <- 0.40
# Fixed Effects (the "true" values we want to recover)
gamma_0_het_female <- 5.5
gamma_0_het_male <- 4.5
gamma_0_ss_person <- 5.35
gamma_a_het_female <- 1.6
gamma_a_het_male <- 1.8
gamma_a_ss_person <- 0.2
gamma_p_het_female <- 0.3
gamma_p_het_male <- 0.2
gamma_p_ss_person <- 0.25
# Variance Components
sd_x <- 1.5 # SD of the predictor (communication)
r_x <- 0.4 # Correlation between partners' communication
# --- UPDATED: smaller, more realistic random slope SDs ---
# (Feel free to tweak; these are modest to reflect heterogeneity without dominating)
sd_u0j <- 0.8 # baseline random intercept SD (unused directly below; see group-specific)
sd_uaj <- 0.15 # (legacy overall; using group-specific below)
sd_upj <- 0.12
cor_u0a <- 0.20
cor_u0p <- 0.15
cor_uap <- -0.10
sd_e <- 1.2 # legacy scalar residual SD (not used now that we do sex-specific)
# --- 2. Simulate Dyad-Level Variables ---
dyad_data <- tibble::tibble(coupleID = 1:n_total)
# -- 2a: SEPARATE variance components for each group (UPDATED slopes) --
# Heterosexual couples
sd_u0j_het <- 0.8
sd_uaj_het <- 0.15 # was 0.3
sd_upj_het <- 0.12 # was 0.2
cor_u0a_het <- 0.20 # was 0.25
cor_u0p_het <- 0.15 # same
cor_uap_het <- -0.10 # same
# Same-sex couples
sd_u0j_ss <- 1.0
sd_uaj_ss <- 0.12 # was 0.2
sd_upj_ss <- 0.15 # was 0.25
cor_u0a_ss <- 0.10
cor_u0p_ss <- -0.05
cor_uap_ss <- 0.00
# -- 2b: Variance-covariance matrices --
cov_matrix_u_het <- matrix(c(
sd_u0j_het^2, cor_u0a_het*sd_u0j_het*sd_uaj_het, cor_u0p_het*sd_u0j_het*sd_upj_het,
cor_u0a_het*sd_u0j_het*sd_uaj_het, sd_uaj_het^2, cor_uap_het*sd_uaj_het*sd_upj_het,
cor_u0p_het*sd_u0j_het*sd_upj_het, cor_uap_het*sd_uaj_het*sd_upj_het, sd_upj_het^2
), nrow = 3, byrow = TRUE)
cov_matrix_u_ss <- matrix(c(
sd_u0j_ss^2, cor_u0a_ss*sd_u0j_ss*sd_uaj_ss, cor_u0p_ss*sd_u0j_ss*sd_upj_ss,
cor_u0a_ss*sd_u0j_ss*sd_uaj_ss, sd_uaj_ss^2, cor_uap_ss*sd_uaj_ss*sd_upj_ss,
cor_u0p_ss*sd_u0j_ss*sd_upj_ss, cor_uap_ss*sd_uaj_ss*sd_upj_ss, sd_upj_ss^2
), nrow = 3, byrow = TRUE)
# -- 2c: Generate random effects separately for each group --
random_effects_het <- MASS::mvrnorm(n = n_het, mu = c(0, 0, 0), Sigma = cov_matrix_u_het)
random_effects_ss <- MASS::mvrnorm(n = n_ss, mu = c(0, 0, 0), Sigma = cov_matrix_u_ss)
# -- 2d: Combine into one dataframe --
het_df_re <- tibble::tibble(
coupleID = 1:n_het,
u_0j = random_effects_het[, 1],
u_aj = random_effects_het[, 2],
u_pj = random_effects_het[, 3]
)
ss_df_re <- tibble::tibble(
coupleID = (n_het + 1):n_total,
u_0j = random_effects_ss[, 1],
u_aj = random_effects_ss[, 2],
u_pj = random_effects_ss[, 3]
)
combined_re <- dplyr::bind_rows(het_df_re, ss_df_re)
# Generate correlated predictor scores for partners (same as before)
cov_matrix_x <- matrix(c(sd_x^2, r_x*sd_x^2, r_x*sd_x^2, sd_x^2), nrow = 2)
partner_scores <- MASS::mvrnorm(n = n_total, mu = c(5, 5), Sigma = cov_matrix_x)
# Join combined RE with main dyad data
dyad_data <- dyad_data %>%
dplyr::mutate(
communication_p1 = partner_scores[, 1],
communication_p2 = partner_scores[, 2]
) %>%
dplyr::left_join(combined_re, by = "coupleID")
# --- 3. Create Person-Level (Long) Dataframe ---
person1 <- dyad_data %>% dplyr::select(coupleID, communication = communication_p1) %>% dplyr::mutate(p_num = 1)
person2 <- dyad_data %>% dplyr::select(coupleID, communication = communication_p2) %>% dplyr::mutate(p_num = 2)
df <- dplyr::bind_rows(person1, person2) %>%
dplyr::arrange(coupleID, p_num) %>%
dplyr::mutate(userID = paste0(coupleID, "_", p_num)) %>%
dplyr::select(userID, coupleID, communication, p_num)
# Assign gender (1 = female, 2 = male)
het_couples <- 1:n_het
ss_couples <- (n_het + 1):n_total
df <- df %>%
dplyr::mutate(
gender = dplyr::case_when(
coupleID %in% het_couples & p_num == 1 ~ 1,
coupleID %in% het_couples & p_num == 2 ~ 2,
coupleID %in% ss_couples ~ 1
)
)
temp_df_for_outcome <- df %>%
dplyr::group_by(coupleID) %>%
dplyr::mutate(
communication_actor = communication,
communication_partner = communication[2:1]
) %>%
dplyr::ungroup() %>%
dplyr::left_join(dyad_data, by = "coupleID") %>%
dplyr::mutate(
# Center predictors before generating outcome (grand-mean)
c_comm_actor = communication_actor - mean(communication_actor),
c_comm_partner = communication_partner - mean(communication_partner),
# Deterministic part
satisfaction_deterministic = dplyr::case_when(
gender == 1 & coupleID <= n_het ~ gamma_0_het_female + gamma_a_het_female * c_comm_actor + gamma_p_het_female * c_comm_partner,
gender == 2 & coupleID <= n_het ~ gamma_0_het_male + gamma_a_het_male * c_comm_actor + gamma_p_het_male * c_comm_partner,
gender == 1 & coupleID > n_het ~ gamma_0_ss_person + gamma_a_ss_person * c_comm_actor + gamma_p_ss_person * c_comm_partner
)
)
# --- NEW: Residuals with compound symmetry (per dyad) & sex-specific SDs -------
resid_pairs <- tibble::tibble(coupleID = 1:n_total) %>%
dplyr::mutate(
sd1 = ifelse(coupleID <= n_het, sd_e_het_female, sd_e_ss_female), # p1: het=female, ss=female
sd2 = ifelse(coupleID <= n_het, sd_e_het_male, sd_e_ss_female), # p2: het=male, ss=female
rho = ifelse(coupleID <= n_het, rho_e_het, rho_e_ss)
) %>%
dplyr::rowwise() %>%
dplyr::mutate(
e_pair = list(MASS::mvrnorm(
n = 1, mu = c(0, 0),
Sigma = matrix(c(sd1^2, rho*sd1*sd2,
rho*sd1*sd2, sd2^2), nrow = 2)
))
) %>%
dplyr::ungroup() %>%
tidyr::unnest_wider(e_pair, names_sep = "") %>%
dplyr::rename(e1 = e_pair1, e2 = e_pair2)
# Attach residuals and finish outcome
temp_df_for_outcome <- temp_df_for_outcome %>%
dplyr::left_join(resid_pairs, by = "coupleID") %>%
dplyr::mutate(
e_i = ifelse(p_num == 1, e1, e2),
satisfaction = satisfaction_deterministic +
u_0j + (u_aj * c_comm_actor) + (u_pj * c_comm_partner) + e_i
) %>%
dplyr::select(-e1, -e2)
# Finalize: ORIGINAL OUTPUT FORMAT
df <- temp_df_for_outcome %>%
dplyr::select(userID, coupleID, gender, communication, satisfaction) %>%
dplyr::mutate(
gender = factor(gender, levels = c(1, 2), labels = c("female", "male"))
)
```
# Distinguishable Dyads
# Distinguishable Dyads - Cross-Sectional APIM
## Distinguishable Dyads - Data: Simulated Dyads
```{r data-dist-apim-raw-preview}
print_df(head(df))
```
## Distinguishable Dyads - Cross-Sectional APIM

[e.g., @kenny2006dyadic; @kennyPartnerEffectsRelationship1999; @kennyDyadicDataAnalysis2011]
## Distinguishable Dyads - Preparing Data
```{r data-dist-apim-prepare, results='hide', message=FALSE, warning=FALSE, cache=TRUE, dependson='simulate-cross-sectional-data'}
df_apim <- prepare_dyad_data(
data = df,
dyad = coupleID,
member = userID,
role = gender,
predictors = communication,
model_types = "apim",
keep_compositions = "female-male",
include_arbitrary_member_contrast = TRUE,
add_apim_gmc_predictors = TRUE,
seed = 123
)
print_apim_preview(df_apim)
```
## Distinguishable Dyads - Preparing Data
```{r data-dist-apim-preview, echo=FALSE}
print_apim_preview(df_apim)
```
For the likelihood-based constraint comparison, the glmmTMB models below use
`.communication_gmc_actor` and `.communication_gmc_partner`. The Bayesian models
retain the raw actor and partner scores because centering also changes the
intercept's prior interpretation.
## Distinguishable Dyads - Fitting the Model in glmmTMB
- `glmmTMB` models residual variance/dispersion via `dispformula`, but residual covariance is handled through random-effect covariance structures.
- For Gaussian mixed models, `dispformula = ~ 0` fixes the residual variance to a tiny value. This pushes the Gaussian residual variance into the random-effect block.
- In this Gaussian dyadic model, the `us(0 + .is_male + .is_female | coupleID)` block therefore represents the 2x2 residual variance-covariance structure between partners.
- For non-Gaussian models, this is not an ordinary residual covariance on the response scale. The same random-effect trick adds latent Gaussian heterogeneity/correlation on the linear predictor scale.
- Do **not** use `dispformula = ~ 0` as a general non-Gaussian residual-covariance trick. For families with an estimable dispersion parameter, `dispformula` models that family-specific parameter via a log link; for families without one, such as Poisson or binomial, it is ignored. Partner-specific dispersion, e.g. `dispformula = ~ 0 + .is_male + .is_female`, is only appropriate when the family has a dispersion parameter and this is substantively intended.
## Distinguishable Dyads - Fitting the Model in glmmTMB
```{r fit-dist-apim-glmmtmb, results='hide', message=FALSE, warning=FALSE, cache=TRUE, dependson='data-dist-apim-prepare'}
#| code-line-numbers: "1-13|15-16|18-21|23-27|29-30"
model_dist_apim_glmmtmb <- glmmTMB(
satisfaction ~
# Remove global intercept, introduce male and female intercepts.
0 + .is_male + .is_female +
# Actor effect for male and female
.communication_gmc_actor:.is_male +
.communication_gmc_actor:.is_female +
# Partner effect for male and female
.communication_gmc_partner:.is_male +
.communication_gmc_partner:.is_female +
# Modelling residual non-independence with an unstructured 2x2 covariance.
us(0 + .is_male + .is_female | coupleID)
# Gaussian response:
# dispformula = ~ 0 fixes residual variance to a tiny value,
# pushing the Gaussian residual variance into this random-effect block.
, dispformula = ~ 0
# Non-Gaussian responses:
# dispformula is family-specific dispersion, or ignored for families
# without a dispersion parameter. Do not use ~0 as a residual trick.
# If dispersion exists and should differ by partner, use e.g.:
# dispformula = ~ 0 + .is_male + .is_female
, data = df_apim
, family = gaussian
)
```
## Distinguishable Dyads - Fitting the Model in glmmTMB
Note that 'unstructured' is the default in glmmTMB, so instead of
`us(0 + .is_male + .is_female | coupleID)`
we could also remove `us` and simply write
`(0 + .is_male + .is_female | coupleID)`.
An unstructured covariance matrix gives `.is_male` and `.is_female` their own
variance and freely estimates their correlation. With more than two members
(e.g., triads), it would estimate a separate correlation for every pair.
For two partners, the covariance matrix is:
$$
\boldsymbol{\Sigma} =
\begin{pmatrix}
\sigma^2_{female} & \rho\,\sigma_{female}\sigma_{male} \\
\rho\,\sigma_{female}\sigma_{male} & \sigma^2_{male}
\end{pmatrix}.
$$
## Distinguishable Dyads - Fitting the Model in glmmTMB
```{r results-dist-apim-glmmtmb, echo=FALSE, class.output='model-summary-output', cache=TRUE, dependson='fit-dist-apim-glmmtmb'}
summary(model_dist_apim_glmmtmb)
```
## glmmTMB: Diagnostics with Near-Zero Gaussian Sigma {.smaller}
With `dispformula = ~ 0`, `glmmTMB` fixes the Gaussian observation-level
residual SD near zero because the dyadic variance and covariance are represented
by the random-effect block [@R-glmmTMB]. DHARMa's default conditional simulation
therefore contains almost no observation-level variation. For a marginal check,
resimulate the random effects and interpret the result for that target
[@R-DHARMa]:
```r
dharma_glmmtmb <- DHARMa::simulateResiduals(
model_dist_apim_glmmtmb,
n = 1000,
simulateREs = "unconditional"
)
```
## Distinguishable Dyads - Fitting the Model in brms
In brms, we can use brms-provided residual covariance structures directly. We do not have to set residuals internally to zero.
```{r fit-dist-apim-brms, results='hide', message=FALSE, warning=FALSE, cache=TRUE, dependson='data-dist-apim-prepare'}
#| code-line-numbers: "1-13|15-21|23-28|30-41"
formula_dist_apim_b <- bf(
satisfaction ~
# Remove global intercept, introduce male and female intercepts.
0 + .is_male + .is_female +
# Actor effect for male and female
.communication_actor:.is_male +
.communication_actor:.is_female +
# Partner effect for male and female
.communication_partner:.is_male +
.communication_partner:.is_female +
# Gender indexes the two within-couple residual positions.
unstr(time = gender, gr = coupleID),
# Allowing two distinct residual variances for males vs females:
sigma = ~ 0 + .is_male + .is_female
)
priors_dist_apim_b <- c(
# prior(normal(2, 3), class = "Intercept"),
prior(normal(0, 5), class = "b"),
prior(student_t(3, 0, 1.5), class = "b", dpar = "sigma"),
prior(lkj(2), class = "cortime")
)
model_dist_apim_b <- brm(
formula = formula_dist_apim_b,
data = df_apim,
family = gaussian(link = identity),
prior = priors_dist_apim_b,
chains = 4,
cores = 4,
iter = 2000,
warmup = 1000,
seed = 123,
file = file.path('brms_cache', 'example1_dist_apim_b') # Cache the model
)
```
## Distinguishable Dyads - Fitting the Model in brms
```{r results-dist-apim-brms-raw, echo=FALSE, class.output='model-summary-output', cache=TRUE, dependson='fit-dist-apim-brms'}
summary(model_dist_apim_b)
```
## Distinguishable Dyads - Poisson Covariance in brms {.smaller}
Poisson has no separately estimated observation-level residual SD. For
distinguishable dyads, we therefore use correlated role-specific dyad effects.
The non-Gaussian `unstr()` formulation instead has one common latent SD and
would impose equal role variances [@R-brms]. We simulate an actual count outcome
rather than discretize continuous `satisfaction`.
## Distinguishable Dyads - Fitting the Poisson Model in brms
```{r simulate-dist-apim-poisson-data, include=FALSE, cache=TRUE, dependson='data-dist-apim-prepare'}
set.seed(124)
latent_by_dyad <- df_apim |>
dplyr::distinct(coupleID) |>
dplyr::arrange(coupleID)
latent_effects <- MASS::mvrnorm(
n = nrow(latent_by_dyad),
mu = c(0, 0),
Sigma = matrix(
c(0.25^2, 0.30 * 0.25 * 0.40,
0.30 * 0.25 * 0.40, 0.40^2),
nrow = 2
)
)
latent_by_dyad <- latent_by_dyad |>
dplyr::mutate(
latent_female = latent_effects[, 1],
latent_male = latent_effects[, 2]
)
df_apim_count <- df_apim |>
dplyr::left_join(latent_by_dyad, by = "coupleID") |>
dplyr::mutate(
count_eta =
.is_female * (
log(6) +
0.18 * (.communication_actor - mean(.communication_actor)) +
0.06 * (.communication_partner - mean(.communication_partner)) +
latent_female
) +
.is_male * (
log(5) +
0.20 * (.communication_actor - mean(.communication_actor)) +
0.04 * (.communication_partner - mean(.communication_partner)) +
latent_male
),
satisfaction_count = stats::rpois(dplyr::n(), exp(count_eta))
) |>
dplyr::select(-latent_female, -latent_male, -count_eta)
```
```{r fit-dist-apim-brms-poisson, results='hide', message=FALSE, warning=FALSE, cache=TRUE, dependson='simulate-dist-apim-poisson-data'}
#| code-line-numbers: "1-13|15-21|23-28|29-41"
formula_dist_apim_c <- bf(
satisfaction_count ~
# Remove global intercept, introduce male and female intercepts.
0 + .is_male + .is_female +
# Actor effect for male and female
.communication_actor:.is_male +
.communication_actor:.is_female +
# Partner effect for male and female
.communication_partner:.is_male +
.communication_partner:.is_female +
# Model within-dyad dependence with correlated Gaussian random effects.
# Poisson has no separately estimated residual-dispersion parameter.
(0 + .is_male + .is_female | coupleID)
# sigma ~ 0 + .is_male + .is_female
)
priors_dist_apim_c <- c(
prior(normal(0, 5), class = "b"),
prior(student_t(3, 0, 1.5), class = "sd"),
prior(lkj(2), class = "cor")
)
model_dist_apim_c <- brm(
formula = formula_dist_apim_c,
data = df_apim_count,
family = poisson(),
prior = priors_dist_apim_c,
chains = 4,
cores = 4,
iter = 2000,
warmup = 1000,
seed = 123,
file = file.path('brms_cache', 'example1_dist_apim_c') # Cache the model
)
```
## Poisson Model in brms: Results
```{r results-dist-apim-brms-poisson-raw, echo=FALSE, class.output='model-summary-output', cache=TRUE, dependson='fit-dist-apim-brms-poisson'}
summary(model_dist_apim_c)
```
## Distinguishable Dyads - Fitting the Model in glmmTMB
```{r fit-dist-apim-glmmtmb-poisson, results='hide', message=FALSE, warning=FALSE, cache=TRUE, dependson='simulate-dist-apim-poisson-data'}
model_glmmTMB_dist_apim_c <- glmmTMB(
satisfaction_count ~
# Remove global intercept, introduce male and female intercepts.
0 + .is_male + .is_female +
# Actor effect for male and female
.communication_actor:.is_male +
.communication_actor:.is_female +
# Partner effect for male and female
.communication_partner:.is_male +
.communication_partner:.is_female +
# Model within-dyad dependence with correlated Gaussian random effects.
# Poisson has no separately estimated residual-dispersion parameter.
(0 + .is_male + .is_female | coupleID)
, data = df_apim_count
, family = poisson()
)
```
## Poisson Model in glmmTMB: Results
```{r results-dist-apim-glmmtmb-poisson-raw, echo=FALSE, class.output='model-summary-output', cache=TRUE, dependson='fit-dist-apim-glmmtmb-poisson'}
summary(model_glmmTMB_dist_apim_c)
```
## Distinguishable Dyads - Check Model Convergence and Fit
Check Rhats and Effective Sample Sizes (ESS_tail and ESS_bulk) directly from the brms summary. Additionally you can (using Model B as an example):
```{r diag-dist-apim-hmc, cache = TRUE, message=TRUE, dependson='fit-dist-apim-brms'}
# In brms 2.23, draws from either Stan backend are stored as a stanfit here.
rstan::check_hmc_diagnostics(model_dist_apim_b$fit)
```
## Distinguishable Dyads - Check Model Convergence and Fit
```{r eval=FALSE}
plot(model_dist_apim_b, ask = FALSE)
```
```{r echo=FALSE}
n_plot_variables <- if (knitr::is_latex_output()) 1 else 3
p1 <- plot(
model_dist_apim_b,
ask = FALSE,
nvariables = n_plot_variables,
plot = FALSE
)
p1[[2]] # Inspect all parameters; show a compact subset in this tutorial.
```
## Distinguishable Dyads - Check Model Convergence and Fit
```{r pp-dist-apim-dens, cache = TRUE, dependson='fit-dist-apim-brms'}
pp_check(model_dist_apim_b, 'dens_overlay_grouped', group = '.is_male')
```
## Distinguishable Dyads - Check Model Convergence and Fit
```{r pp-dist-apim-ecdf, cache = TRUE, dependson='fit-dist-apim-brms'}
pp_check(model_dist_apim_b, 'ecdf_overlay_grouped', group = '.is_male')
```
## Distinguishable Dyads - Check Model Convergence and Fit
```{r diag-dist-apim-dharma, cache = TRUE, dependson='fit-dist-apim-brms'}
# Custom function to make DHARMa work with brms (see file 'Functions')
DHARMa.check_brms(model_dist_apim_b)
```
## Distinguishable Dyads - Check Model Convergence and Fit {.smaller}
- Diagnose convergence, residual fit, and predictive accuracy separately;
check coding, scaling, priors, and identifiability before changing the model.
- Choose the family and link from the outcome and substantive assumptions—for
example, `cumulative()` for ordered outcomes or `bernoulli()` for binary data.
- If chains are healthy, more post-warmup draws can raise ESS. More warmup helps
adaptation, while higher `adapt_delta` specifically targets divergences
[@R-brms].
## Excursion: Generalized Dyadic Models
For Gaussian outcomes, residual covariance has a direct response-scale interpretation:
- partner-specific residual variances
- partner residual correlations
- same-day residual covariance in ILD data
For non-Gaussian outcomes, the same syntax usually does **not** estimate an ordinary residual covariance.
Instead, random-effect covariance terms represent latent Gaussian heterogeneity on the link scale.
## Excursion: Count vs Binary Outcomes
For count outcomes, latent partner covariance is often useful and can be estimable:
- Poisson or negative-binomial models can include dyad-level latent covariance terms
- estimates live on the log-link scale
- covariance parameters need diagnostics and sensitivity checks
For dichotomous outcomes, the same idea is much harder:
- each partner contributes only `0` or `1` per occasion
- many latent variance-correlation combinations can imply similar pair probabilities
- same-day binary covariance is especially weakly identified
## Excursion: Practical Warning
Binary dyadic covariance models can converge mechanically while still being unreliable.
Watch for:
- variance estimates near zero or extremely large
- correlations near `-1` or `1`
- low ESS, divergent transitions, or strong prior sensitivity
- different software giving very different covariance estimates
## Excursion: Practical Strategy
Practical default:
- estimate simpler structures first
- use informative priors if fitting latent binary covariance in brms
- treat same-day binary partner covariance as a specialized model, not a routine extension
- if the main goal is fixed effects, consider simpler random effects or robust/clustered inference
## Distinguishable Dyads - Results
```{r results-dist-apim-brms, echo = FALSE, cache=TRUE, dependson='fit-dist-apim-brms'}
summary_dist_apim_b <- summarize_brms(
model_dist_apim_b,
exponentiate_sigma = TRUE,
stats_to_report = c('CI', 'Rhat', 'ESS')
)
print_df(
summary_dist_apim_b,
rows_to_pack = list(
'Fixed Effects' = c(1,6),
'Residual Structure' = c(7,9)
)
)
```
NOTE: brms estimates sigma on the log scale. In the tables, sigmas are exponentiated to show residual SDs on the response scale, like glmmTMB output.
# Distinguishable Dyads
# Distinguishable Dyads - Intensive Longitudinal APIM (L-APIM)
## Distinguishable Dyads - L-APIM - Raw Data
```{r simulate-longitudinal-data, echo=FALSE, results='hide', cache=TRUE}
# Simulate Data
set.seed(123)
# ===============================
# 1) Design
# ===============================
n_couples <- 100
days <- 0:54
T_per <- length(days)
# People per couple: p1 = female, p2 = male
persons <- tibble(
coupleID = rep(1:n_couples, each = 2),
p_num = rep(1:2, times = n_couples),
gender = ifelse(p_num == 1, 1L, 2L), # 1=female, 2=male
is_female = as.integer(gender == 1L),
is_male = as.integer(gender == 2L),
userID = paste0(coupleID, "_", p_num)
)
# ===============================
# 2) Fixed effects (edit as desired)
# ===============================
# Intercepts & time trends by gender
b0_female <- 5.5; b0_male <- 4.7 # depends on centering, not meaningful when recovered.
b_time_female <- 0.01; b_time_male <- -0.005 # must be small because over 55 days!
# Between-person APIM (effects of person-mean support)
b_bp_actor_f <- 1.5; b_bp_partner_f <- 0.5
b_bp_actor_m <- 1.2; b_bp_partner_m <- 0.3
# Within-person APIM (effects of daily deviations)
b_wp_actor_f <- 0.4; b_wp_partner_f <- 0.2
b_wp_actor_m <- 0.2; b_wp_partner_m <- 0.1 # hard to detect!
# ===============================
# 3) Couple-level random effects (full var-cov)
# Vector: [b0_m, b0_f, time_m, time_f, wpA_m, wpP_m, wpA_f, wpP_f]
# ===============================
sd_re <- c(0.70, 0.80, 0.015, 0.015, 0.10, 0.08, 0.10, 0.08)
R <- matrix(0.15, 8, 8); diag(R) <- 1
Sigma_re <- diag(sd_re) %*% R %*% diag(sd_re)
RE <- MASS::mvrnorm(n_couples, mu = rep(0, 8), Sigma = Sigma_re) |>
as_tibble(.name_repair = ~c("re_b0_m","re_b0_f","re_time_m","re_time_f",
"re_wpA_m","re_wpP_m","re_wpA_f","re_wpP_f")) |>
mutate(coupleID = 1:n_couples)
# ===============================
# 4) Provided support (predictor)
# - Person means correlated within couple
# - Daily AR(1) within-person; cross-partner correlated innovations
# ===============================
mu_sup_f <- 5.0; sd_mu_f <- 0.8
mu_sup_m <- 4.8; sd_mu_m <- 0.8
rho_couple_mean <- 0.50
Sigma_mu <- matrix(c(sd_mu_f^2, rho_couple_mean*sd_mu_f*sd_mu_m,
rho_couple_mean*sd_mu_f*sd_mu_m, sd_mu_m^2), 2)
mu_pairs <- MASS::mvrnorm(n_couples, mu = c(mu_sup_f, mu_sup_m), Sigma = Sigma_mu)
mu_df <- tibble(
coupleID = rep(1:n_couples, each = 2),
p_num = rep(1:2, times = n_couples),
mu_sup = c(rbind(mu_pairs[,1], mu_pairs[,2]))
)
phi_sup <- 0.4
sd_sup_wp <- 0.8
sd_eta_sup <- sqrt(sd_sup_wp^2 * (1 - phi_sup^2))
rho_sup_day <- 0.3
Sigma_eta_day <- matrix(c(sd_eta_sup^2, rho_sup_day*sd_eta_sup^2,
rho_sup_day*sd_eta_sup^2, sd_eta_sup^2), 2)
sim_support_one_couple <- function(cid) {
eta <- MASS::mvrnorm(T_per, mu = c(0,0), Sigma = Sigma_eta_day)
sup <- matrix(NA_real_, nrow = T_per, ncol = 2)
sup[1,] <- eta[1,] / sqrt(1 - phi_sup^2) # stationary init
for (t in 2:T_per) sup[t,] <- phi_sup * sup[t-1,] + eta[t,]
tibble(coupleID = cid, diaryday = days, sup_f = sup[,1], sup_m = sup[,2])
}
support_time <- purrr::map_dfr(1:n_couples, sim_support_one_couple)
support_long <- support_time |>
tidyr::pivot_longer(c(sup_f, sup_m), names_to = "who", values_to = "sup_cwp") |>
dplyr::mutate(p_num = ifelse(who == "sup_f", 1L, 2L)) |>
dplyr::select(-who) |>
dplyr::left_join(mu_df, by = c("coupleID","p_num")) |>
dplyr::mutate(provided_support = mu_sup + sup_cwp) |>
dplyr::select(coupleID, diaryday, p_num, provided_support, sup_cwp)
# ===============================
# 5) Assemble panel & partner lookups (safe keys)
# ===============================
panel <- tidyr::expand_grid(coupleID = 1:n_couples, diaryday = days, p_num = 1:2) |>
dplyr::left_join(persons, by = c("coupleID","p_num")) |>
dplyr::left_join(support_long, by = c("coupleID","diaryday","p_num"))
panel <- panel |>
dplyr::group_by(coupleID, diaryday) |>
dplyr::mutate(
provided_support_partner = provided_support[3 - p_num],
sup_cwp_partner = sup_cwp[3 - p_num]
) |>
dplyr::ungroup()
mu_actor_tbl <- mu_df |> dplyr::rename(mu_actor = mu_sup)
mu_partner_tbl <- mu_df |> dplyr::mutate(p_num = 3 - p_num) |> dplyr::rename(mu_partner = mu_sup)
panel <- panel |>
dplyr::left_join(mu_actor_tbl, by = c("coupleID","p_num")) |>
dplyr::left_join(mu_partner_tbl, by = c("coupleID","p_num"))
# ===============================
# 6) Same-day couple×day random effect (common shocks)
# ===============================
use_day_RE <- TRUE # set FALSE to remove same-day shock
sd_day <- 0.17
if (use_day_RE) {
day_shock <- tidyr::expand_grid(coupleID = 1:n_couples, diaryday = days) |>
dplyr::mutate(z_day = rnorm(n(), 0, sd_day))
panel <- panel |> dplyr::left_join(day_shock, by = c("coupleID","diaryday"))
} else {
panel <- panel |> dplyr::mutate(z_day = 0)
}