-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.Rmd
2155 lines (1786 loc) · 88.9 KB
/
20.Rmd
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
```{r, echo = FALSE, cachse = FALSE}
knitr::opts_chunk$set(fig.retina = 2.5)
knitr::opts_chunk$set(fig.align = "center")
options(width = 100)
```
# Metric Predicted Variable with Multiple Nominal Predictors
> This chapter considers data structures that consist of a metric predicted variable and two (or more) nominal predictors. This chapter extends ideas introduced in the previous chapter, so please read the previous chapter if you have not already...
>
> The traditional treatment of this sort of data structure is called multifactor analysis of variance (ANOVA). Our Bayesian approach will be a hierarchical generalization of the traditional ANOVA model. The chapter also considers generalizations of the traditional models, because it is straight forward in Bayesian software to implement heavy-tailed distributions to accommodate outliers, along with hierarchical structure to accommodate heterogeneous variances in the different groups. [@kruschkeDoingBayesianData2015, pp. 583--584]
## Describing groups of metric data with multiple nominal predictors
Quick reprise:
> Suppose we have two nominal predictors, denoted $\overrightarrow x_1$ and $\overrightarrow x_2$. A datum from the $j$th level of $\overrightarrow x_1$ is denoted $x_{1[j]}$, and analogously for the second factor. The predicted value is a baseline plus a deflection due to the level of factor 1 plus a deflection due to the level of factor 2 plus a residual deflection due to the interaction of factors:
>
> \begin{align*}
> \mu & = \beta_0 + \overrightarrow \beta_1 \cdot \overrightarrow x_1 + \overrightarrow \beta_2 \cdot \overrightarrow x_2 + \overrightarrow \beta_{1 \times 2} \cdot \overrightarrow x_{1 \times 2} \\
> & = \beta_0 + \sum_j \beta_{1[j]} x_{1[j]} + \sum_k \beta_{2[k]} x_{2[k]} + \sum_{j, k} \beta_{1 \times 2[j, k]} x_{1 \times 2[j, k]}
> \end{align*}
>
> The deflections within factors and within the interaction are constrained to sum to zero:
>
> \begin{align*}
> \sum_j \beta_{1[j]} = 0 &&& \text{and} && \sum_k \beta_{2[k]} = 0 \;\;\; \text{and} \\
> \sum_j \beta_{1 \times 2[j, k]} = 0 \text{ for all } k &&& \text{and} && \sum_k \beta_{1 \times 2[j, k]} = 0 \text{ for all } j
> \end{align*}
>
> ([these equations] are repetitions of Equations 15.9 and 15.10, p. 434). The actual data are assumed to be randomly distributed around the predicted value. (pp. 584--585)
### Interaction.
> An important concept of models with multiple predictors is interaction. Interaction means that the effect of a predictor depends on the level of another predictor. A little more technically, interaction is what is left over after the main effects of the factors are added: interaction is the nonadditive influence of the factors. (p. 585)
Here are the data necessary for our version of Figure 20.1, which displays an interaction of two 2-level factors.
```{r, message = F, warning = F}
library(tidyverse)
grand_mean <- 5
deflection_1 <- 1.8
deflection_2 <- 0.2
nonadditive_component <- -1
(
d <-
tibble(x1 = rep(c(-1, 1), each = 2),
x2 = rep(c(1, -1), times = 2)) %>%
mutate(mu_additive = grand_mean + (x1 * deflection_1) + (x2 * deflection_2)) %>%
mutate(mu_multiplicative = mu_additive + (x1 * x2 * nonadditive_component),
# we'll need this to accommodate `position = "dodge"` within `geom_col()`
x1_offset = x1 + x2 * -.45,
# we'll need this for the fill
x2_c = factor(x2, levels = c(1, -1)))
)
```
There's enough going on with the lines, arrows, and titles across the three panels that to my mind it seems easier to make three distinct plots and them join them at the end with syntax from the **patchwork** package. But enough of the settings are common among the panels that it also makes sense to keep from repeating that part of the code. So we'll take a three-step solution. For the first step, we'll make the baseline or foundational plot, which we'll call `p`.
Before we make `p`, let's talk color and theme. For this chapter, we'll carry forward our practice from [Chapter 19][Metric Predicted Variable with One Nominal Predictor] and take our color palette from the **palettetown** package. Our color palette will be #15, which is based on [Beedrill](https://www.pokemon.com/us/pokedex/beedrill).
```{r, warning = F, message = F, fig.height = 3.5}
library(palettetown)
scales::show_col(pokepal(pokemon = 15))
bd <- pokepal(pokemon = 15)
bd
```
Also like in the last chapter, our overall plot theme will be based on the default `theme_grey()` with a good number of adjustments. This time, it will have more of a [`theme_black()`](https://jonlefcheck.net/2013/03/11/black-theme-for-ggplot2-2/) vibe.
```{r}
theme_set(
theme_grey() +
theme(text = element_text(color = bd[3]),
axis.text = element_text(color = bd[3]),
axis.ticks = element_line(color = bd[3]),
legend.background = element_blank(),
legend.box.background = element_blank(),
legend.key = element_rect(fill = bd[1]),
panel.background = element_rect(fill = bd[1], color = bd[3]),
panel.grid = element_blank(),
plot.background = element_rect(fill = bd[1], color = bd[1]),
strip.background = element_rect(fill = alpha(bd[5], 1/3), color = alpha(bd[5], 1/3)),
strip.text = element_text(color = bd[3]))
)
```
Okay, it's time to make `p`, the baseline or foundational plot for our Figure 20.1.
```{r, fig.height = 3, fig.width = 2.75}
p <-
d %>%
ggplot(aes(x = x1, y = mu_multiplicative)) +
geom_col(aes(fill = x2_c),
position = "dodge") +
scale_fill_manual(NULL, values = bd[c(11, 6)], labels = c("x2[1]", "x2[2]")) +
scale_x_continuous(breaks = c(-1, 1), labels = c("x1[1]", "x1[2]")) +
scale_y_continuous(expression(mu), breaks = seq(from = 0, to = 10, by = 2),
expand = expansion(mult = c(0, 0.05))) +
coord_cartesian(ylim = c(0, 10)) +
theme(axis.ticks.x = element_blank(),
legend.position = c(.17, .875))
p
```
Now we have `p`, we'll add panel-specific elements to it, which we'll save as individual objects, `p1`, `p2`, and `p3`. That's step 2. Then for step 3, we'll bring them all together with **patchwork**.
```{r, fig.height = 3, fig.width = 8.25, warning = F, message = F}
# deflection from additive
p1 <-
p +
geom_segment(aes(x = x1_offset, xend = x1_offset,
y = mu_additive, yend = mu_multiplicative),
size = 1.25, color = bd[5],
arrow = arrow(length = unit(.275, "cm"))) +
geom_line(aes(x = x1_offset, y = mu_additive, group = x2),
linetype = 2, color = bd[5]) +
geom_line(aes(x = x1_offset, y = mu_additive, group = x1),
linetype = 2, color = bd[5]) +
coord_cartesian(ylim = c(0, 10)) +
ggtitle("Deflection from additive")
# effect of x1 depends on x2
p2 <-
p +
geom_segment(aes(x = x1_offset, xend = x1_offset,
y = mu_additive, yend = mu_multiplicative),
size = .5, color = bd[5],
arrow = arrow(length = unit(.15, "cm"))) +
geom_line(aes(x = x1_offset, y = mu_additive, group = x2),
linetype = 2, color = bd[5]) +
geom_line(aes(x = x1_offset, y = mu_multiplicative, group = x2),
size = 1.25, color = bd[5]) +
ggtitle("Effect of x1 depends on x2")
# effect of x2 depends on x1
p3 <-
p +
geom_segment(aes(x = x1_offset, xend = x1_offset,
y = mu_additive, yend = mu_multiplicative),
size = .5, color = bd[5],
arrow = arrow(length = unit(.15, "cm"))) +
geom_line(aes(x = x1_offset, y = mu_multiplicative, group = x1),
size = 1.25, color = bd[5]) +
geom_line(aes(x = x1_offset, y = mu_additive, group = x1),
linetype = 2, color = bd[5]) +
ggtitle("Effect of x2 depends on x1")
library(patchwork)
p1 + p2 + p3
```
And in case it's not clear, "the average deflection from baseline due to a predictor... is called the main effect of the predictor. The main effects of the predictors correspond to the dashed lines in the left panel of Figure 20.1" (p. 587). And further
> The left panel of Figure 20.1 highlights the interaction as the nonadditive component, emphasized by the heavy vertical arrows that mark the departure from additivity. The middle panel of Figure 20.1 highlights the interaction by emphasizing that the effect of $x_1$ depends on the level of $x_2$. The heavy lines mark the effect of $x_1$, that is, the changes from level 1 of $x_1$ to level 2 of $x_1$. Notice that the heavy lines have different slopes: The heavy line for level 1 of $x_2$ has a shallower slope than the heavy line for level 2 of $x_2$. The right panel of Figure 20.1 highlights the interaction by emphasizing that the effect of $x_2$ depends on the level of $x_1$. (p. 587)
### Traditional ANOVA.
> As was explained in [Section 19.2][Traditional analysis of variance] (p. 556), the terminology, "analysis of variance," comes from a decomposition of overall data variance into within-group variance and between-group variance... The Bayesian approach is not ANOVA, but is analogous to ANOVA. Traditional ANOVA makes decisions about equality of groups (i.e., null hypotheses) on the basis of $p$ values using a null hypothesis that assumes (i) the data are normally distributed within groups, and (ii) the standard deviation of the data within each group is the same for all groups. The second assumption is sometimes called "homogeneity of variance." The entrenched precedent of ANOVA is why basic models of grouped data make those assumptions, and why the basic models presented in this chapter will also make those assumptions. Later in the chapter, those constraints will be relaxed. (pp. 587--588)
## Hierarchical Bayesian approach
"Our goal is to estimate the main and interaction deflections, and other parameters, based on the observed data" (p. 588).
Figure 20.2 will provides a generic model diagram of how this can work.
```{r, fig.width = 8, fig.height = 6, message = F}
# bracket
p1 <-
tibble(x = .99,
y = .5,
label = "{_}") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 10, hjust = 1, color = bd[2], family = "Times") +
scale_x_continuous(expand = c(0, 0), limits = c(0, 1)) +
ylim(0, 1) +
theme_void()
## plain arrow
# save our custom arrow settings
my_arrow <- arrow(angle = 20, length = unit(0.35, "cm"), type = "closed")
p2 <-
tibble(x = .68,
y = 1,
xend = .68,
yend = .25) %>%
ggplot(aes(x = x, xend = xend,
y = y, yend = yend)) +
geom_segment(arrow = my_arrow, color = bd[3]) +
xlim(0, 1) +
theme_void()
# normal density
p3 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = bd[6]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = bd[3]) +
annotate(geom = "text",
x = c(0, 1.45), y = .6,
hjust = c(.5, 0),
label = c("italic(M)[0]", "italic(S)[0]"),
size = 7, color = bd[3], family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = bd[3]))
# normal density
p4 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = bd[6]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = bd[3]) +
annotate(geom = "text",
x = c(0, 1.15), y = .6,
label = c("0", "sigma[beta][1]"),
hjust = c(.5, 0),
size = 7, color = bd[3], family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = bd[3]))
# normal density
p5 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = bd[6]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = bd[3]) +
annotate(geom = "text",
x = c(0, 1.15), y = .6,
label = c("0", "sigma[beta][2]"),
hjust = c(.5, 0),
size = 7, color = bd[3], family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = bd[3]))
# normal density
p6 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = bd[6]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = bd[3]) +
annotate(geom = "text",
x = c(0, 0.67), y = .6,
hjust = c(.5, 0),
label = c("0", "sigma[beta][1%*%2]"),
size = 7, color = bd[3], family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = bd[3]))
# four annotated arrows
p7 <-
tibble(x = c(.05, .34, .64, .945),
y = c(1, 1, 1, 1),
xend = c(.05, .18, .45, .74),
yend = c(0, 0, 0, 0)) %>%
ggplot(aes(x = x, xend = xend,
y = y, yend = yend)) +
geom_segment(arrow = my_arrow, color = bd[3]) +
annotate(geom = "text",
x = c(.025, .23, .30, .52, .585, .81, .91), y = .5,
label = c("'~'", "'~'", "italic(j)", "'~'", "italic(k)", "'~'", "italic(jk)"),
size = c(10, 10, 7, 10, 7, 10, 7),
color = bd[3], family = "Times", parse = T) +
xlim(0, 1) +
theme_void()
# likelihood formula
p8 <-
tibble(x = .5,
y = .25,
label = "beta[0]+sum()[italic(j)]*beta[1]['['*italic(j)*']']*italic(x)[1]['['*italic(j)*']'](italic(i))+sum()[italic(k)]*beta[2]['['*italic(k)*']']*italic(x)[2]['['*italic(k)*']'](italic(i))+sum()[italic(jk)]*beta[1%*%2]['['*italic(jk)*']']*italic(x)[1%*%2]['['*italic(jk)*']'](italic(i))") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(hjust = .5, size = 7, color = bd[3], parse = T, family = "Times") +
scale_x_continuous(expand = c(0, 0), limits = c(0, 1)) +
ylim(0, 1) +
theme_void()
# half-normal density
p9 <-
tibble(x = seq(from = 0, to = 3, by = .01)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = bd[6]) +
annotate(geom = "text",
x = 1.5, y = .2,
label = "half-normal",
size = 7, color = bd[3]) +
annotate(geom = "text",
x = 1.5, y = .6,
label = "0*','*~italic(S)[sigma]",
size = 7, color = bd[3], family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = bd[3]))
# the final normal density
p10 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = bd[6]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = bd[3]) +
annotate(geom = "text",
x = c(0, 1.15), y = .6,
label = c("mu[italic(i)]", "sigma[italic(y)]"),
hjust = c(.5, 0),
size = 7, color = bd[3], family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = bd[3]))
# an annotated arrow
p11 <-
tibble(x = .4,
y = .5,
label = "'='") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 10, color = bd[3], parse = T, family = "Times") +
geom_segment(x = .5, xend = .5,
y = 1, yend = .1,
arrow = my_arrow, color = bd[3]) +
xlim(0, 1) +
theme_void()
# another annotated arrow
p12 <-
tibble(x = .49,
y = .55,
label = "'~'") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 10, color = bd[3], parse = T, family = "Times") +
geom_segment(x = .79, xend = .4,
y = 1, yend = .2,
arrow = my_arrow, color = bd[3]) +
xlim(0, 1) +
theme_void()
# the final annotated arrow
p13 <-
tibble(x = c(.375, .625),
y = c(1/3, 1/3),
label = c("'~'", "italic(i)")) %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = c(10, 7),
color = bd[3], parse = T, family = "Times") +
geom_segment(x = .5, xend = .5,
y = 1, yend = 0,
arrow = my_arrow, color = bd[3]) +
xlim(0, 1) +
theme_void()
# some text
p14 <-
tibble(x = .5,
y = .5,
label = "italic(y[i])") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 7, color = bd[3], parse = T, family = "Times") +
xlim(0, 1) +
theme_void()
# define the layout
layout <- c(
area(t = 1, b = 1, l = 6, r = 7),
area(t = 1, b = 1, l = 10, r = 11),
area(t = 1, b = 1, l = 14, r = 15),
area(t = 3, b = 4, l = 1, r = 3),
area(t = 3, b = 4, l = 5, r = 7),
area(t = 3, b = 4, l = 9, r = 11),
area(t = 3, b = 4, l = 13, r = 15),
area(t = 2, b = 3, l = 6, r = 7),
area(t = 2, b = 3, l = 10, r = 11),
area(t = 2, b = 3, l = 14, r = 15),
area(t = 6, b = 7, l = 1, r = 15),
area(t = 5, b = 6, l = 1, r = 15),
area(t = 9, b = 10, l = 10, r = 12),
area(t = 12, b = 13, l = 7, r = 9),
area(t = 8, b = 12, l = 7, r = 9),
area(t = 11, b = 12, l = 7, r = 12),
area(t = 14, b = 14, l = 7, r = 9),
area(t = 15, b = 15, l = 7, r = 9)
)
# combine and plot!
(p1 + p1 + p1 + p3 + p4 + p5 + p6 + p2 + p2 + p2 + p8 + p7 + p9 + p10 + p11 + p12 + p13 + p14) +
plot_layout(design = layout) &
ylim(0, 1) &
theme(plot.margin = margin(0, 5.5, 0, 5.5))
```
Wow that plot has a lot of working parts! `r emo::ji("wow")`
### Implementation in ~~JAGS~~ brms.
Below is how to implement the model based on the code from Kruschke's `Jags-Ymet-Xnom2fac-MnormalHom.R` and `Jags-Ymet-Xnom2fac-MnormalHom-Example.R` scripts. With **brms**, we'll need to specify the `stanvars`.
```{r, eval = F}
mean_y <- mean(my_data$y)
sd_y <- sd(my_data$y)
omega <- sd_y / 2
sigma <- 2 * sd_y
s_r <- gamma_a_b_from_omega_sigma(mode = omega, sd = sigma)
stanvars <-
stanvar(mean_y, name = "mean_y") +
stanvar(sd_y, name = "sd_y") +
stanvar(s_r$shape, name = "alpha") +
stanvar(s_r$rate, name = "beta")
```
And before that, of course, make sure you've defined the `gamma_a_b_from_omega_sigma()` function. E.g.,
```{r}
gamma_a_b_from_omega_sigma <- function(mode, sd) {
if (mode <= 0) stop("mode must be > 0")
if (sd <= 0) stop("sd must be > 0")
rate <- (mode + sqrt(mode^2 + 4 * sd^2)) / (2 * sd^2)
shape <- 1 + mode * rate
return(list(shape = shape, rate = rate))
}
```
With the preparatory work done, now all we'd need to do is run the `brm()` code.
```{r, eval = F}
fit <-
brm(data = my_data,
family = gaussian,
y ~ 1 + (1 | factor_1) + (1 | factor_2) + (1 | factor_1:factor_2),
prior = c(prior(normal(mean_y, sd_y * 5), class = Intercept),
prior(gamma(alpha, beta), class = sd),
prior(cauchy(0, sd_y), class = sigma)),
stanvars = stanvars)
```
If you have reason to use different priors for the random effects, you can always specify multiple lines of `class = sd`, each with the appropriate `coef` argument.
The big new element is multiple `(|)` parts in the `formula`. In this simple model type, we're only working random intercepts, in this case with two factors and their interaction. The `formula` above presumes the interaction is not itself coded within the data. But consider the case you have data including a term for the interaction of the two lower-level factors, called `interaction`. In that case, you'd have that last part of the `formula` read `(1 | interaction)`, instead.
### Example: It's only money.
Load the salary data[^6].
```{r, message = F, warning = F}
my_data <- read_csv("data.R/Salary.csv")
glimpse(my_data)
```
We'll follow Kruschke's example on page 593 and modify the `Pos` variable a bit.
```{r}
my_data <-
my_data %>%
mutate(Pos = factor(Pos,
levels = c("FT3", "FT2", "FT1", "NDW", "DST") ,
ordered = T,
labels = c("Assis", "Assoc", "Full", "Endow", "Disting")))
```
With 1080 cases, two factors, and a criterion, these data are a little too unwieldy to look at the individual case level. But if we're tricky on how we aggregate, we can get a good sense of their structure with a `geom_tile()` plot. Here our strategy is to aggregate by our two factors, `Pos` and `Org`. Since our criterion is `Salary`, we'll compute the mean value of the cases within each unique paring, encoded as `m_salary`. Also, we'll get a sense of how many cases there are within each factor pairing with `n`.
```{r, fig.width = 9, fig.height = 2.5, message = F}
my_data %>%
group_by(Pos, Org) %>%
summarise(m_salary = mean(Salary),
n = n()) %>%
ungroup() %>%
mutate(Org = fct_reorder(Org, m_salary),
Pos = fct_reorder(Pos, m_salary)) %>%
ggplot(aes(x = Org, y = Pos, fill = m_salary, label = n)) +
geom_tile() +
geom_text(size = 2.75) +
# everything below this is really just aesthetic flourish
scale_fill_gradient(low = bd[9], high = bd[12],
breaks = c(55e3, 15e4, 26e4),
labels = c("$55K", "$150K", "$260K")) +
scale_x_discrete("Org", expand = c(0, 0)) +
scale_y_discrete("Pos", expand = c(0, 0)) +
theme(axis.text.x = element_text(angle = 90, hjust = 0),
axis.text.y = element_text(hjust = 0),
axis.ticks = element_blank(),
legend.position = "top")
```
Hopefully it's clear that each cell is a unique pairing of `Org` and `Pos`. The cells are color coded by the mean `Salary`. The numbers in the cells give the $n$ cases they represent. When there's no data for a unique combination of `Org` and `Pos`, the cells are left light gray and blank.
Load **brms**.
```{r, warning = F, message = F}
library(brms)
```
Define our `stanvars`.
```{r}
mean_y <- mean(my_data$Salary)
sd_y <- sd(my_data$Salary)
omega <- sd_y / 2
sigma <- 2 * sd_y
s_r <- gamma_a_b_from_omega_sigma(mode = omega, sd = sigma)
stanvars <-
stanvar(mean_y, name = "mean_y") +
stanvar(sd_y, name = "sd_y") +
stanvar(s_r$shape, name = "alpha") +
stanvar(s_r$rate, name = "beta")
```
Now fit the model.
```{r fit20.1}
fit20.1 <-
brm(data = my_data,
family = gaussian,
Salary ~ 1 + (1 | Pos) + (1 | Org) + (1 | Pos:Org),
prior = c(prior(normal(mean_y, sd_y * 5), class = Intercept),
prior(gamma(alpha, beta), class = sd),
prior(cauchy(0, sd_y), class = sigma)),
iter = 4000, warmup = 2000, chains = 4, cores = 4,
seed = 20,
control = list(adapt_delta = 0.999,
max_treedepth = 13),
stanvars = stanvars,
file = "fits/fit20.01")
```
The chains look fine.
```{r, fig.width = 8, fig.height = 6.5}
bayesplot::color_scheme_set(scheme = bd[c(13, 7:9, 11:12)])
plot(fit20.1)
```
Here's the model summary.
```{r}
print(fit20.1)
```
This was a difficult model to fit with **brms**. Stan does well when the criteria are on or close to a standardized metric and these `Salary` data are a far cry from that. Tuning `adapt_delta` and `max_treedepth` went a long way to help the model out.
Okay, let's get ready for our version of Figure 20.3. First, we'll use `tidybayes::add_fitted_draws()` to help organize the necessary posterior draws.
```{r, warning = F, message = F}
library(tidybayes)
# how many draws would you like?
n_draw <- 20
# wrangle
f <-
my_data %>%
distinct(Pos) %>%
expand(Pos,
Org = c("BFIN", "CHEM", "PSY", "ENG")) %>%
add_fitted_draws(fit20.1, n = n_draw, seed = 20,
allow_new_levels = T,
dpar = c("mu", "sigma")) %>%
mutate(ll = qnorm(.025, mean = mu, sd = sigma),
ul = qnorm(.975, mean = mu, sd = sigma)) %>%
mutate(Salary = map2(ll, ul, seq, length.out = 100)) %>%
unnest(Salary) %>%
mutate(density = dnorm(Salary, mu, sigma)) %>%
group_by(.draw) %>%
mutate(density = density / max(density)) %>%
mutate(Org = factor(Org, levels = c("BFIN", "CHEM", "PSY", "ENG")))
glimpse(f)
```
We're ready to plot.
```{r, warning = F, message = F ,fig.height = 5.5, fig.width = 8}
library(ggridges)
f %>%
ggplot(aes(x = Salary, y = Pos)) +
geom_vline(xintercept = fixef(fit20.1)[, 1], color = bd[5]) +
geom_ridgeline(aes(height = density, group = interaction(Pos, .draw),
color = Pos),
fill = NA, show.legend = F,
size = 1/4, scale = 3/4) +
geom_jitter(data = my_data %>%
filter(Org %in% c("BFIN", "CHEM", "PSY", "ENG")) %>%
mutate(Org = factor(Org, levels = c("BFIN", "CHEM", "PSY", "ENG"))),
height = .025, alpha = 1/2, size = 2/3, color = bd[11]) +
scale_color_manual(values = bd[c(14, 13, 8, 12, 3)]) +
scale_x_continuous(breaks = seq(from = 0, to = 300000, length.out = 4),
labels = c("$0", "$100K", "200K", "$300K")) +
coord_cartesian(xlim = c(0, 35e4),
ylim = c(1.25, 5.5)) +
labs(title = "Data with Posterior Predictive Distributions",
subtitle = "The white vertical line is the model-implied grand mean.",
y = "Pos") +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank()) +
facet_wrap(~ Org, ncol = 2)
```
The **brms** package doesn't have a convenience function that returns output quite like what Kruschke displayed in his Table 20.2. But we can get close. The `posterior_summary()` will return posterior means, $SD$s, and percentile-based 95% intervals for all model parameters. Due to space concerns, I'll just show the first ten lines.
```{r}
posterior_summary(fit20.1)[1:10,]
```
I'm not aware of a simple way to extract the effective samples for all parameters within a **brms** fit object. There is no `effsamples()` function. However, we do have `neff_ratio()`, which returns a named vector of the ratios. For space constraints, here we look at the first ten values.
```{r}
neff_ratio(fit20.1)[1:10]
```
The `brms::neff_ratio()` function returns ratios of the effective samples over the total number of post-warmup iterations. So if we know the `neff_ratio()` values and the number of post-warmup iterations, the 'Eff.Sample' values are just a little algebra away. A quick solution is to look at the 'total post-warmup samples' line at the top of our `print()` output. Another way is to extract that information from our `brm()` fit object. I'm not aware of a way to do that directly, but we can extract the iter value (i.e., `fit20.1$fit@sim$iter`), the warmup value (i.e., `fit20.1$fit@sim$warmup`), and the number of chains (i.e., `fit20.1$fit@sim$chains`). With those values in hand, simple algebra will return the `total post-warmup samples` value. E.g.,
```{r}
(n_iter <- (fit20.1$fit@sim$iter - fit20.1$fit@sim$warmup) * fit20.1$fit@sim$chains)
```
And now we have `n_iter`, we can calculate the 'Eff.Sample' values.
```{r}
neff_ratio(fit20.1) %>%
data.frame() %>%
rownames_to_column() %>%
set_names("parameter", "neff_ratio") %>%
mutate(eff_sample = (neff_ratio * n_iter) %>% round(digits = 0)) %>%
select(-neff_ratio) %>%
arrange(parameter) %>%
head()
```
If we're careful, we can use `left_join()` to bind together the posterior summaries and their effective samples like this.
```{r, warning = F, message = F}
post <- posterior_samples(fit20.1)
# extract the means and medians
post %>%
gather() %>%
arrange(key) %>%
group_by(key) %>%
summarise(Mean = mean(value),
Median = median(value)) %>%
# join to them the mode and HDIs
left_join(
post %>%
gather() %>%
group_by(key) %>%
mode_hdi(value) %>%
select(key:.upper) %>%
rename(Mode = value,
HDI_low = .lower,
HDI_high = .upper),
by = "key"
) %>%
# now finally join the effective samples
left_join(
neff_ratio(fit20.1) %>%
as.data.frame() %>%
rownames_to_column() %>%
set_names("key", "neff_ratio") %>%
mutate(eff_sample = (neff_ratio * n_iter)) %>%
select(-neff_ratio) %>%
arrange(key),
by = "key"
) %>%
# here we just reformat a bit
mutate_if(is.double, round, digits = 0) %>%
rename(Parameter = key) %>%
head(n = 10)
```
Our code returned the summaries for all model parameters, including the log posterior (i.e., `lp__`). Since that's way too much output to display, here, we just looked at the first 10. If you wanted to subset the parameters, you could just `filter()` by the `Parameter` column. And if this kind of a table was really important, to you, you might even use the code above as inspiration for a custom function.
As Kruschke then pointed out, "individual salaries vary tremendously around the predicted cell mean" (p. 594), which you can quantify using $\sigma_y$. Here it is using `posterior_summary()`.
```{r}
posterior_summary(fit20.1)["sigma", ]
```
And we can get a better sense of the distribution with a dot plot.
```{r, fig.width = 4, fig.height = 2}
post %>%
ggplot(aes(x = sigma, y = 0)) +
stat_dotsinterval(point_interval = mode_hdi, .width = .95,
justification = -0.04,
shape = 23, stroke = 1/4, point_size = 3, slab_size = 1/4,
color = bd[2], point_color = bd[1], slab_color = bd[1],
point_fill = bd[2], slab_fill = bd[6],
quantiles = 100) +
scale_y_continuous(NULL, breaks = NULL) +
xlab(expression(sigma[y]))
```
As Kruschke pointed out, this parameter is held constant across all subgroups. That is, the subgroups are homogeneous with respect to their variances. We'll relax this constraint later on.
Before we move on to the next section, look above at how many arguments we fiddled with to configure `stat_dotsinterval()`. Given how many more dot plots we have looming in our not-too-distant future, we might go ahead and save these settings as a new function. We'll call it `stat_beedrill()`.
```{r}
stat_beedrill <- function(point_size = 3,
slab_color = bd[1],
quantiles = 100, ...) {
stat_dotsinterval(point_interval = mode_hdi, .width = .95,
shape = 23, stroke = 1/4,
point_size = point_size, slab_size = 1/4,
color = bd[2],
point_color = bd[1], point_fill = bd[2],
slab_color = slab_color, slab_fill = bd[6],
quantiles = quantiles,
# learn more about this at https://github.com/mjskay/ggdist/issues/93
justification = -0.04,
...)
}
```
Note how we hard coded the settings for some of the parameters within the function (e.g., `point_interval`) but allows others to be adjustable with new default settings (e.g., `point_size`).
### Main effect contrasts.
> In applications with multiple levels of the factors, it is virtually always the case that we are interested in comparing particular levels with each other.... These sorts of comparisons, which involve levels of a single factor and collapse across the other factor(s), are called main effect comparisons or contrasts.(p. 595)
The `fitted()` function provides a versatile framework for contrasts among the main effects. Here's the first contrast.
```{r, fig.width = 3, fig.height = 2.5, warning = F, message = F}
# define the new data
nd <-
tibble(Pos = c("Assis", "Assoc"),
Org = "mu")
# feed the new data into `fitted()`
f <-
fitted(fit20.1,
newdata = nd,
summary = F,
allow_new_levels = T) %>%
as_tibble() %>%
set_names("Assis", "Assoc") %>%
mutate(`Assoc vs Assis` = Assoc - Assis)
# plot
f %>%
ggplot(aes(x = `Assoc vs Assis`, y = 0)) +
stat_beedrill() +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "Assoc vs Assis",
x = "Difference")
```
In case you were curious, here are the summary statistics.
```{r, warning = F, message = F}
f %>%
mode_hdi(`Assoc vs Assis`) %>%
select(`Assoc vs Assis`:.upper) %>%
mutate_if(is.double, round, digits = 0)
```
Now make the next two contrasts.
```{r, fig.width = 6, fig.height = 2.5}
nd <-
tibble(Org = c("BFIN", "CHEM", "ENG", "PSY"),
Pos = "mu")
f <-
fitted(fit20.1,
newdata = nd,
summary = F,
allow_new_levels = T) %>%
as_tibble() %>%
set_names("BFIN", "CHEM", "ENG", "PSY") %>%
transmute(`CHEM vs PSY` = CHEM - PSY,
`BFIN vs other 3` = BFIN - (CHEM + ENG + PSY) / 3)
# plot
f %>%
gather() %>%
ggplot(aes(x = value, y = 0)) +
stat_beedrill() +
scale_y_continuous(NULL, breaks = NULL) +
xlab("Difference") +
facet_wrap(~ key, scales = "free")
```
And here are their numeric summaries.
```{r}
f %>%
gather(contrast, mode) %>%
group_by(contrast) %>%
mode_hdi(mode) %>%
select(contrast:.upper) %>%
mutate_if(is.double, round, digits = 0)
```
"year"
For further discussion on marginal contrasts in **brms**, see the discussion in [issue #552]((https://github.com/paul-buerkner/brms/issues/552)) in the **brms** GitHub repo and [this discussion](https://discourse.mc-stan.org/t/how-do-i-get-marginal-effects-for-categorical-variables-to-condition-on-an-average-rather-than-a-category/5323) in the Stan user forums.
### Interaction contrasts and simple effects.
If we'd like to make the simple effects and interaction contrasts like Kruschke displayed in Figure 20.5 within our **tidyverse**/**brms** paradigm, it'll be simplest to just redefine our `nd` data and use `fitted()`, again.
```{r}
# define our new data
nd <-
crossing(Pos = c("Assis", "Full"),
Org = c("CHEM", "PSY"))
# we need to update our col_names
brief_col_names <-
crossing(Pos = c("Assis", "Full"),
Org = c("CHEM", "PSY")) %>%
unite(key, Pos, Org) %>%
pull()
# get the draws with `fitted()`
f1 <-
fitted(fit20.1,
newdata = nd,
summary = F) %>%
# wrangle
as_tibble() %>%
set_names(brief_col_names) %>%
mutate(`Full - Assis @ PSY` = Full_PSY - Assis_PSY,
`Full - Assis @ CHEM` = Full_CHEM - Assis_CHEM) %>%
mutate(`Full.v.Assis (x) CHEM.v.PSY` = `Full - Assis @ CHEM` - `Full - Assis @ PSY`)
# what have we done?
head(f1)
```
It'll take just a tiny bit more wrangling before we're ready to plot.
```{r, fig.width = 8, fig.height = 2.5}
text <-
tibble(key = "Full - Assis @ PSY",
value = 15500,
y = .95,
label = "ROPE") %>%
mutate(key = factor(key, levels = c("Full - Assis @ PSY", "Full - Assis @ CHEM", "Full.v.Assis (x) CHEM.v.PSY")))
f1 %>%
select(-contains("_")) %>%
gather() %>%
mutate(key = factor(key, levels = c("Full - Assis @ PSY", "Full - Assis @ CHEM", "Full.v.Assis (x) CHEM.v.PSY"))) %>%
ggplot(aes(x = value, y = 0)) +
# for kicks and giggles we'll throw in the ROPE
geom_rect(xmin = -1e3, xmax = 1e3,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = bd[7]) +
stat_beedrill() +
geom_text(data = text,
aes(y = y, label = label),
color = bd[7], size = 5) +
scale_y_continuous(NULL, breaks = NULL) +
xlab("Difference") +
facet_wrap(~ key, scales = "free_y")
```
If it was really important that the labels in the $x$-axes were different, like they are in Kruschke's Figure 20.5, you could always make the three plots separately and then bind them together with **patchwork** syntax.
Though he didn't show the results, on page 598 Kruschke mentioned a few other contrasts we might consider. The example entailed comparing the differences within `BFIN` to the average of the other three. Let's walk it out.
```{r}
# define our new data
nd <-
crossing(Pos = c("Assis", "Full"),
Org = c("BFIN", "CHEM", "ENG", "PSY"))
# we need to update our `brief_col_names`
brief_col_names <-
crossing(Pos = c("Assis", "Full"),
Org = c("BFIN", "CHEM", "ENG", "PSY")) %>%
unite(key, Pos, Org) %>%
pull()
# get the draws with `fitted()`
f2 <-
fitted(fit20.1,
newdata = nd,
summary = F) %>%
# wrangle
as_tibble() %>%
set_names(brief_col_names) %>%
mutate(`Full - Assis @ BFIN` = Full_BFIN - Assis_BFIN,
`Full - Assis @ CHEM` = Full_CHEM - Assis_CHEM,
`Full - Assis @ ENG` = Full_ENG - Assis_ENG,
`Full - Assis @ PSY` = Full_PSY - Assis_PSY) %>%
mutate(`Full.v.Assis (x) BFIN.v.the rest` = `Full - Assis @ BFIN` - (`Full - Assis @ CHEM` + `Full - Assis @ ENG` + `Full - Assis @ PSY`) / 3)
# what have we done?
glimpse(f2)
```
Now plot.
```{r, fig.width = 8, fig.height = 4.5}
f2 %>%
select(-contains("_")) %>%
gather() %>%
ggplot(aes(x = value, y = 0)) +
geom_rect(xmin = -1e3, xmax = 1e3,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = bd[7]) +
stat_beedrill() +
scale_y_continuous(NULL, breaks = NULL) +
xlab("Difference") +
facet_wrap(~ key, scales = "free_y", ncol = 3)
```
So while the overall pay averages for those in `BFIN` were larger than those in the other three departments, the differences between full and associate professors within `BFIN` wasn't substantially different from the differences within the other three departments. To be sure, the interquartile range of that last difference distribution fell below both zero and the ROPE, but there's still a lot of spread in the rest of the distribution.
#### Interaction effects: High uncertainty and shrinkage.
"It is important to realize that the estimates of interaction contrasts are typically much more uncertain than the estimates of simple effects or main effects" (p. 598).
If we start with our `fitted()` object `f1`, we can wrangle a bit, compute the HDIs with `tidybayes::mode_hdi()` and then use simple subtraction to compute the interval range for each difference.
```{r, warning = F, message = F}
f1 %>%
select(-contains("_")) %>%
gather() %>%
mutate(key = factor(key, levels = c("Full - Assis @ PSY", "Full - Assis @ CHEM", "Full.v.Assis (x) CHEM.v.PSY"))) %>%
group_by(key) %>%
mode_hdi(value) %>%
select(key:.upper) %>%
mutate(`interval range` = .upper - .lower)
```
Just like Kruschke pointed out in the text, the interval for the interaction estimate was quite larger than the intervals for the simple contrasts.
> This large uncertainty of an interaction contrast is caused by the fact that it involves at least four sources of uncertainty (i.e., at least four groups of data), unlike its component simple effects which each involve only half of those sources of uncertainty. In general, interaction contrasts require a lot of data to estimate accurately. (p. 598)
Gelman has blogged on this, a bit (e.g., [*You need 16 times the sample size to estimate an interaction than to estimate a main effect*](https://andrewgelman.com/2018/03/15/need-16-times-sample-size-estimate-interaction-estimate-main-effect/)).
There is also shrinkage.
> The interaction contrasts also can experience notable shrinkage from the hierarchical model. In the present application, for example, there are 300 interaction deflections (5 levels of seniority times 60 departments) that are assumed to come from a higher- level distribution that has an estimated standard deviation, denoted $\sigma_{\beta 1 \times 2}$ in Figure 20.2. Chances are that most of the 300 interaction deflections will be small, and therefore the estimated standard deviation of the interaction deflections will be small, and therefore the estimated deflections themselves will be shrunken toward zero. This shrinkage is inherently neither good nor bad; it is simply the correct consequence of the model assumptions. The shrinkage can be good insofar as it mitigates false alarms about interactions, but the shrinkage can be bad if it inappropriately obscures meaningful interactions. (p. 598)
Here's that $\sigma_{\beta 1 \times 2}$.
```{r, fig.width = 3.75, fig.height = 2.5}
post %>%
ggplot(aes(x = `sd_Pos:Org__Intercept`, y = 0)) +
stat_beedrill() +
scale_y_continuous(NULL, breaks = NULL)
```
## Rescaling can change interactions, homogeneity, and normality
> When interpreting interactions, it can be important to consider the scale on which the data are measured. This is because an interaction means non-additive effects when measured on the current scale. If the data are nonlinearly transformed to a different scale, then the non-additivity can also change. (p. 599)
Here is Kruschke's initial example of a possible interaction effect of sex and political party with respect to wages.
```{r, fig.width = 3.25, fig.height = 3}
d <-
tibble(monetary_units = c(10, 12, 15, 18),
politics = rep(c("democrat", "republican"), each = 2),