-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch5_multilinear.qmd
More file actions
1607 lines (1321 loc) · 58.2 KB
/
Copy pathch5_multilinear.qmd
File metadata and controls
1607 lines (1321 loc) · 58.2 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
---
format: html
execute:
fig-align: center
echo: false
warning: false
message: false
cache: true
cache.lazy: false
editor: visual
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(fig.align = "center")
library(rethinking)
data(WaffleDivorce)
data(milk)
data(Howell1)
kungHeight <- Howell1
detach(package:rethinking, unload = T)
library(tidyverse)
library(brms)
library(ggrepel)
library(tigris)
library(bayesplot)
library(patchwork)
library(dagitty)
library(ggdag)
library(tidybayes)
```
## TLDR
\[claude\] come up with 3-4 bullet points on what was accomplished in this chapter.
## Motivation
\[claude\] come up with a distrilled paragraph argument for why we should care about muli-variate regression. Here's a section of Richard McElreath's text statistical Rethinking
(1) Statistical “control” for confounds. A confound is something that misleads us about a causal influence—there will be a more precise definition in the next chapter. The spurious waffles and divorce correlation is one possible type of confound, where the confound (southernness) makes a variable with no real importance (Waffle House density) appear to be important. But confounds are diverse. They can hide real important variables just as easily as they can produce false ones.
(2) Multiple causation. A phenomenon may arise from multiple causes. Measurement of each cause is useful, so when we can use the same data to estimate more than one type of influence, we should. Furthermore, when causation is multiple, one cause can hide another.
(3) Interactions. The importance of one variable may depend upon another. For ex- ample, plants benefit from both light and water. But in the absence of either, the other is no benefit at all. Such interactions occur very often. Effective inference about one variable will often depend upon consideration of others.
Claude give a quick description of the waffle divorce data set : Data for the individual States of the United States, describing number of Waffle House diners and various marriage and demographic facts.
Format Location : State name Loc : State abbreviation Population : 2010 population in millions MedianAgeMarriage: 2005-2010 median age at marriage Marriage : 2009 marriage rate per 1000 adults Marriage.SE : Standard error of rate Divorce : 2009 divorce rate per 1000 adults Divorce.SE : Standard error of rate WaffleHouses : Number of diners South : 1 indicates Southern State Slaves1860 : Number of slaves in 1860 census Population1860 : Population from 1860 census PropSlaves1860 : Proportion of total population that were slaves in 1860
```{r plot waffle house vs divorce}
#| fig-width: 5
#| fig-height: 4
WaffleDivorce %>%
ggplot(aes(x = WaffleHouses/Population, y = Divorce)) +
stat_smooth(method = "lm", fullrange = T, linewidth = 1/2,
color = "firebrick4", fill = "firebrick", alpha = 1/5) +
geom_point(size = 1.5, color = "firebrick4", alpha = 1/2) +
geom_text_repel(data = WaffleDivorce %>% filter(Loc %in% c("ME", "OK", "AR", "AL", "GA", "SC", "NJ")),
aes(label = Loc),
size = 3, seed = 1042) + # this makes it reproducible
scale_x_continuous("Waffle Houses per million", limits = c(0, 55)) +
ylab("Divorce rate") +
coord_cartesian(xlim = c(0, 50), ylim = c(5, 15)) +
theme_bw() +
theme(panel.grid = element_blank())
```
Most likely a spurious correlation, waffles don't cause divorces nor vice versa
## Spurious Correlation
Excerpt from Richard McElreath: "Let’s leave waffles behind, at least for the moment. An example that is easier to understand is the correlation between divorce rate and marriage rate (Figure 5.2). The rate at which adults marry is a great predictor of divorce rate, as seen in the left-hand plot in the figure. But does marriage cause divorce? In a trivial sense it obviously does: One cannot get a divorce without first getting married. But there’s no reason high marriage rate must be correlated with divorce."
```{r plot marriage/divorce on US map}
#| fig-width: 8
#| fig-height: 2
WaffleDivorce_states <-
WaffleDivorce %>%
mutate(Divorce_z = (Divorce - mean(Divorce)) / sd(Divorce),
MedianAgeMarriage_z = (MedianAgeMarriage - mean(MedianAgeMarriage)) / sd(MedianAgeMarriage),
Marriage_z = (Marriage - mean(Marriage)) / sd(Marriage)) %>%
right_join(readRDS("externalData/us_states_geometry.rds"),
by = c("Location" = "NAME")) %>%
pivot_longer(ends_with("_z"))
WaffleDivorce_states %>%
ggplot() +
geom_sf(aes(fill = value, geometry = geometry),
size = 0) +
scale_fill_gradient(low = "#f8eaea", high = "firebrick4") +
coord_sf(xlim = c(-29e5, 21e5),
ylim = c(-2e6, 2e6)) +
theme_void() +
theme(legend.position = "none",
strip.text = element_text(margin = margin(0, 0, 0.5, 0))) +
facet_wrap(~name)
```
We see that Divorce rate is high in the south and low in the north midwest and mid atlantic. Marriage rate is high in
```{r DAG representations}
#| fig-width: 8
#| fig-height: 3
dag_coords <-
tibble(name = c("A", "M", "D"),
x = c(1, 3, 2),
y = c(2, 2, 1))
m1 <- dagify("M" ~ "A",
"D" ~ "M" + "A",
coords = dag_coords) %>%
ggplot(aes(x = x, y = y, xend = xend, yend = yend)) +
geom_dag_point(color = "firebrick", alpha = 1/4, size = 10) +
geom_dag_text(color = "firebrick") +
geom_dag_edges(edge_color = "firebrick")+
scale_x_continuous(NULL, breaks = NULL, expand = c(0.1, 0.1)) +
scale_y_continuous(NULL, breaks = NULL, expand = c(0.2, 0.2)) +
theme_bw() +
theme(panel.grid = element_blank())+
labs(title = "Mediated Effect through Marriage Rate")
m2 <- dagify("M" ~ "A",
"D" ~ "A",
coords = dag_coords) %>%
ggplot(aes(x = x, y = y, xend = xend, yend = yend)) +
geom_dag_point(color = "firebrick", alpha = 1/4, size = 10) +
geom_dag_text(color = "firebrick") +
geom_dag_edges(edge_color = "firebrick")+
scale_x_continuous(NULL, breaks = NULL, expand = c(0.1, 0.1)) +
scale_y_continuous(NULL, breaks = NULL, expand = c(0.2, 0.2)) +
theme_bw() +
theme(panel.grid = element_blank())+
labs(title = "Only Direct Effect")
m1 + m2 +
plot_annotation(caption = "A = Marriage Age, M = Marriage Rate, D = Divorce Rate",
theme = theme(plot.caption = element_text(hjust = 0.5, size = 12)))
```
```{r data wrangling, include = FALSE}
WaffleDivorce <- WaffleDivorce %>%
mutate(MedianAgeMarriage_s = (MedianAgeMarriage - mean(MedianAgeMarriage)) / sd(MedianAgeMarriage),
Marriage_s = (Marriage - mean(Marriage)) / sd(Marriage))
```
### Median Marriage Age Model
$$ \textbf{b5.1} $$
$$ \text{Divorce}_i \sim \text{Intercept} + \beta_1 \text{Median Age Marriage}_i $$
```{r model - median marriage age, include = FALSE}
b5.1 <-
brm(data = WaffleDivorce,
family = gaussian,
Divorce ~ 1 + MedianAgeMarriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.01")
at <- c(-3, -2, -1, 0, 1, 2, 3)
simModel <- as_tibble(as_draws_df(b5.1)) %>%
mutate(simMarriageAge = seq(from = -3, to = 3.5, length.out = n()),
simDivorceEst = Intercept + (b_MedianAgeMarriage_s * simMarriageAge),
simDivorce = rnorm(n(), simDivorceEst, sd = sigma))
```
::: panel-tabset
#### 📈 μ vs full distribution
```{r mu vs full heat plot median marriage age}
#| fig-width: 8
#| fig-height: 4
# Find global limits across both datasets
ymin <- min(c(simModel$simDivorce, simModel$simDivorceEst, WaffleDivorce$Divorce))
ymax <- max(c(simModel$simDivorce, simModel$simDivorceEst, WaffleDivorce$Divorce))
modelEst_plot <- ggplot() +
stat_density_2d(data = simModel,
aes(x = simMarriageAge, y = simDivorceEst, fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = MedianAgeMarriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults",
title = "Divorce Rate ~ Median Marriage Age", subtitle = "Mu estimate")+
theme_minimal()+
scale_x_continuous("Median Age ",
breaks = at,
labels = round(at * sd(WaffleDivorce$MedianAgeMarriage) +
mean(WaffleDivorce$MedianAgeMarriage), 1)) +
scale_y_continuous(limits = c(ymin, ymax), expand = c(0, 0))+
guides(fill = "none")
model_plot <- ggplot() +
stat_density_2d(data = simModel,
aes(x = simMarriageAge, y = simDivorce, fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = MedianAgeMarriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults", subtitle = "Full Distribution")+
theme_minimal()+
scale_x_continuous("Median Age ",
breaks = at,
labels = round(at * sd(WaffleDivorce$MedianAgeMarriage) +
mean(WaffleDivorce$MedianAgeMarriage), 1)) +
scale_y_continuous(limits = c(ymin, ymax), expand = c(0, 0))+
guides(fill = "none")
modelEst_plot + model_plot + plot_layout(guides = "collect")
```
#### 🎛 Parameters
```{r summary median marriage age}
#| fig-width: 10
#| fig-height: 2
as_tibble(b5.1) %>%
rename("Median Marriage Age" = b_MedianAgeMarriage_s) %>%
dplyr::select(c(`Median Marriage Age`, `Intercept`)) %>%
pivot_longer(cols = everything(),
names_to = "Covariate",
values_to = "Effect") %>%
ggplot(aes(x = `Effect`, y = reorder(Covariate, `Effect`))) +
stat_halfeye(point_interval = median_qi, .width = .95,
fill = "firebrick4") +
labs(x = "Effect on Divorce Rate",
y = NULL) +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank(),
panel.grid = element_blank())
```
#### ⚙️ Code
```{r show model, echo = TRUE}
b5.1 <-
brm(data = WaffleDivorce,
family = gaussian,
Divorce ~ 1 + MedianAgeMarriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.01")
```
#### 🌌 Prior Vs Posterior
```{r prior vs post heat plot - median marriage age}
#| fig-width: 8
#| fig-height: 4
sim_n <- 1e3
prior_sim <- tibble(simMarriageAge = seq(from = -3, to = 3.5, length.out = sim_n),
simDivorceAge = rnorm(sim_n,
mean = (rnorm(sim_n, 10, 10) + (rnorm(sim_n) * simMarriageAge)),
sd = runif(sim_n, min = 0, max = 10)))
ymin <- min(simModel$Estimate, WaffleDivorce$Divorce, prior_sim$simDivorceAge)
ymax <- max(simModel$Estimate, WaffleDivorce$Divorce, prior_sim$simDivorceAge)
prior_plot <- ggplot(data = prior_sim, aes(x = simMarriageAge, y = simDivorceAge)) +
stat_density_2d(aes(fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = MedianAgeMarriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults",
title = "Divorce Rate ~ Median Marriage Age", subtitle = "Prior")+
scale_y_continuous(limits = c(ymin, ymax), expand = c(0, 0)) +
theme_minimal()+
# here it is!
scale_x_continuous("Median Age ",
breaks = at,
labels = round(at * sd(WaffleDivorce$MedianAgeMarriage) + mean(WaffleDivorce$MedianAgeMarriage), 1))+
guides(fill = "none")
post_plot <- ggplot() +
stat_density_2d(data = simModel,
aes(x = simMarriageAge, y = simDivorce, fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = MedianAgeMarriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults",
subtitle = "Posterior")+
scale_y_continuous(limits = c(ymin, ymax), expand = c(0, 0))+
theme_minimal()+
scale_x_continuous("Median Age ",
breaks = at,
labels = round(at * sd(WaffleDivorce$MedianAgeMarriage) + mean(WaffleDivorce$MedianAgeMarriage), 1))+
guides(fill = "none")
prior_plot + post_plot + plot_layout(guides = "collect")
```
:::
The regression of Divorce Rate on Age of Marriage, tells us only that the total influence of age at marriage is strongly negative with divorce rate.
### Marriage Rate
$$ \textbf{b5.2} $$
$$ \text{Divorce}_i \sim \text{Intercept} + \beta_1 \text{Marriage % Rate}_i $$
```{r marriage % rate model - marriage % rate, include = FALSE}
b5.2 <-
brm(data = WaffleDivorce,
family = gaussian,
Divorce ~ 1 + Marriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.02")
simModel.02 <- as_tibble(as_draws_df(b5.2)) %>%
mutate(simMarriage = seq(from = -3, to = 3.5, length.out = n()),
simDivorceEst = Intercept + (b_Marriage_s * simMarriage),
simDivorce = rnorm(n(), simDivorceEst, sd = sigma))
```
::: panel-tabset
#### 📈 μ vs full distribution
```{r mu - marriage rate}
# Find global limits across both datasets
ymin_mRate <- min(c(simModel.02$simDivorce, simModel.02$simDivorceEst, WaffleDivorce$Divorce))
ymax_mRate <- max(c(simModel.02$simDivorce, simModel.02$simDivorceEst, WaffleDivorce$Divorce))
modelEst_plot_mRate <- ggplot() +
stat_density_2d(data = simModel.02,
aes(x = simMarriage, y = simDivorceEst, fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = Marriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults",
title = "Divorce Rate ~ Marriage Rate", subtitle = "Mu estimate")+
theme_minimal()+
scale_x_continuous("Marriage rate per 1000 adults ",
breaks = at,
labels = round(at * sd(WaffleDivorce$Marriage) +
mean(WaffleDivorce$Marriage), 1)) +
scale_y_continuous(limits = c(ymin_mRate, ymax_mRate), expand = c(0, 0)) +
guides(fill = "none")
```
```{r full heat plot marriage rate}
#| fig-width: 8
#| fig-height: 4
model_plot_mRate <- ggplot() +
stat_density_2d(data = simModel.02,
aes(x = simMarriage, y = simDivorce, fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = Marriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults", subtitle = "Full Distribution")+
theme_minimal()+
scale_x_continuous("Marriage rate per 1000 adults",
breaks = at,
labels = round(at * sd(WaffleDivorce$Marriage) +
mean(WaffleDivorce$Marriage), 1)) +
scale_y_continuous(limits = c(ymin_mRate, ymax_mRate), expand = c(0, 0))+
guides(fill = "none")
combined_plot_mRate <- modelEst_plot_mRate + model_plot_mRate + plot_layout(guides = "collect")
combined_plot_mRate
```
#### 🎛 Parameters
```{r summary b5.2}
#| fig-width: 10
#| fig-height: 2
as_tibble(b5.2) %>%
rename("Marriage Rate" = b_Marriage_s) %>%
dplyr::select(c(`Marriage Rate`, `Intercept`)) %>%
pivot_longer(cols = everything(),
names_to = "Covariate",
values_to = "Effect") %>%
ggplot(aes(x = `Effect`, y = reorder(Covariate, `Effect`))) +
stat_halfeye(point_interval = median_qi, .width = .95,
fill = "firebrick4") +
labs(x = "Effect on Divorce Rate",
y = NULL) +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank(),
panel.grid = element_blank())
```
#### ⚙️ Code
```{r show model 5.2, echo = TRUE}
b5.2 <-
brm(data = WaffleDivorce,
family = gaussian,
Divorce ~ 1 + Marriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.02")
```
#### 🌌 Prior Vs Posterior
```{r prior vs post heat plot - marriage rate}
#| fig-width: 8
#| fig-height: 4
sim_n <- 1e3
prior_sim <- tibble(simMarriageRate = seq(from = -3, to = 3.5, length.out = sim_n),
simDivorceAge = rnorm(sim_n,
mean = (rnorm(sim_n, 10, 10) + (rnorm(sim_n) * simMarriageRate)),
sd = runif(sim_n, min = 0, max = 10)))
ymin <- min(simModel$Estimate, WaffleDivorce$Divorce, prior_sim$simDivorceAge)
ymax <- max(simModel$Estimate, WaffleDivorce$Divorce, prior_sim$simDivorceAge)
prior_plot <- ggplot(data = prior_sim, aes(x = simMarriageRate, y = simDivorceAge)) +
stat_density_2d(aes(fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = Marriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults",
title = "Divorce Rate ~ Median Marriage Age", subtitle = "Prior")+
scale_y_continuous(limits = c(ymin, ymax), expand = c(0, 0)) +
theme_minimal()+
# here it is!
scale_x_continuous("Median Age ",
breaks = at,
labels = round(at * sd(WaffleDivorce$Marriage) + mean(WaffleDivorce$Marriage), 1))+
guides(fill = "none")
post_plot <- ggplot() +
stat_density_2d(data = simModel.02,
aes(x = simMarriage, y = simDivorce, fill = after_stat(ndensity)),
geom = "raster", contour = FALSE) +
scale_fill_viridis_c(option = "magma") +
geom_point(data = WaffleDivorce,
aes(x = Marriage_s, y = Divorce),
shape = 21, color = "white", fill = "black", lwd = 3, alpha = .8)+
labs(y = "Divorce rate per 1000 adults",
subtitle = "Posterior")+
scale_y_continuous(limits = c(ymin, ymax), expand = c(0, 0))+
theme_minimal()+
scale_x_continuous("Median Age ",
breaks = at,
labels = round(at * sd(WaffleDivorce$Marriage) + mean(WaffleDivorce$Marriage), 1))+
guides(fill = "none")
prior_plot + post_plot + plot_layout(guides = "collect")
```
:::
### Combined Multi-linear model
$$ \textbf{b5.3} $$
$$ \text{Divorce}_i \sim \text{Intercept} + \beta_1 \text{Marriage % Rate}_i + \beta_2 \text{Median Marriage Age}_i $$
```{r model - marriage age + marriage rate, include = FALSE}
b5.3 <- brm(data = WaffleDivorce,
family = gaussian,
Divorce ~ 1 + Marriage_s + MedianAgeMarriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.031")
simModel.03 <- as_tibble(as_draws_df(b5.3)) %>%
mutate(simMarriageAge = rnorm(n()),
simMarriageRate = rnorm(n()),
simDivorceEst = Intercept + (b_MedianAgeMarriage_s * simMarriageAge) + (b_Marriage_s * simMarriageRate),
simDivorce = rnorm(n(), simDivorceEst, sd = sigma))
```
::: panel-tabset
#### 🎛️ Parameters
```{r b5.3 params}
#| fig-width: 10
#| fig-height: 2
as_tibble(b5.3) %>%
rename("Marriage Rate" = b_Marriage_s,
"Median Marriage Age" = b_MedianAgeMarriage_s) %>%
dplyr::select(c(`Marriage Rate`, `Median Marriage Age`, `Intercept`)) %>%
pivot_longer(cols = everything(),
names_to = "Covariate",
values_to = "Effect") %>%
ggplot(aes(x = `Effect`, y = reorder(Covariate, `Effect`))) +
stat_halfeye(point_interval = median_qi, .width = .95,
fill = "firebrick4") +
labs(x = "Effect on Divorce Rate",
y = NULL) +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank(),
panel.grid = element_blank())
```
#### ⚙️ Code
```{r show model 5.3, echo = TRUE}
b5.3 <- brm(data = WaffleDivorce,
family = gaussian,
Divorce ~ 1 + Marriage_s + MedianAgeMarriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.031")
```
:::
### Diagnosing Multi-linear models
:::: panel-tabset
#### Predictor Residual Plot
::: panel-tabset
##### Marriage Rate
```{r Marriage Rate Residuals}
#| fig-width: 10
#| fig-height: 4
b5.4 <-
brm(data = WaffleDivorce,
family = gaussian,
Marriage_s ~ 1 + MedianAgeMarriage_s,
prior = c(prior(normal(0, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.04.2")
fitted_B5.4 <-
fitted(b5.4) %>%
as_tibble() %>%
bind_cols(WaffleDivorce)
rateFitted <- fitted_B5.4 %>%
ggplot(aes(x = MedianAgeMarriage_s, y = Marriage_s)) +
geom_point(size = 2, shape = 1, color = "firebrick4") +
geom_segment(aes(xend = MedianAgeMarriage_s, yend = Estimate),
linewidth = 1/4) +
geom_line(aes(y = Estimate),
color = "firebrick4") +
coord_cartesian(ylim = range(WaffleDivorce$Marriage_s)) +
theme_bw() +
theme(panel.grid = element_blank())
r_b5.4 <-
residuals(b5.4) %>%
# to use this in ggplot2, we need to make it a tibble or data frame
as_tibble() %>%
bind_cols(WaffleDivorce)
# for the annotation at the top
text <-
tibble(Estimate = c(- 1, 1),
Divorce = 14,
label = c("More Marriages", "Less Marriages"))
# plot
rateResidual <- r_b5.4 %>%
ggplot(aes(x = Estimate, y = Divorce)) +
stat_smooth(method = "lm", fullrange = T,
color = "firebrick4", fill = "firebrick4",
alpha = 1/5, linewidth = 1/2) +
geom_vline(xintercept = 0, linetype = 2, color = "grey50") +
geom_point(size = 2, color = "firebrick4", alpha = 2/3) +
geom_text(data = text,
aes(label = label)) +
scale_x_continuous("Marriage rate residuals", limits = c(-2, 2)) +
coord_cartesian(xlim = range(r_b5.4$Estimate),
ylim = c(6, 14.1)) +
theme_bw() +
theme(panel.grid = element_blank())
rateFitted + rateResidual
```
Little relationship between divorce and marriage rates, once we have accounted for the effect of Median Marriage Age
##### Median Marriage Age
```{r Median Age Residuals, include = FALSE}
b5.4b <-
brm(data = WaffleDivorce,
family = gaussian,
MedianAgeMarriage_s ~ 1 + Marriage_s,
prior = c(prior(normal(0, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma, ub = 10)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/b05.04b")
fitted_B5.4b <-
fitted(b5.4b) %>%
as_tibble() %>%
bind_cols(WaffleDivorce)
AgeFitted <- fitted_B5.4b %>%
ggplot(aes(x = Marriage_s, y = MedianAgeMarriage_s)) +
geom_point(size = 2, shape = 1, color = "firebrick4") +
geom_segment(aes(xend = Marriage_s, yend = Estimate),
linewidth = 1/4) +
geom_line(aes(y = Estimate),
color = "firebrick4") +
coord_cartesian(ylim = range(WaffleDivorce$MedianAgeMarriage_s)) +
theme_bw() +
theme(panel.grid = element_blank())
r_b5.4b <-
residuals(b5.4b) %>%
# to use this in ggplot2, we need to make it a tibble or data frame
as_tibble() %>%
bind_cols(WaffleDivorce)
```
```{r}
#| fig-width: 10
#| fig-height: 4
text <-
tibble(Estimate = c(- 0.7, 0.5),
Divorce = 14.1,
label = c("younger", "older"))
# extract the residuals
AgeResidual <- residuals(b5.4b) %>%
as_tibble() %>%
bind_cols(WaffleDivorce) %>%
# plot
ggplot(aes(x = Estimate, y = Divorce)) +
stat_smooth(method = "lm", fullrange = T,
color = "firebrick4", fill = "firebrick4",
alpha = 1/5, linewidth = 1/2) +
geom_vline(xintercept = 0, linetype = 2, color = "grey50") +
geom_point(size = 2, color = "firebrick4", alpha = 2/3) +
geom_text(data = text,
aes(label = label)) +
scale_x_continuous("Age of marriage residuals", limits = c(-2, 3)) +
coord_cartesian(xlim = range(r_b5.4b$Estimate),
ylim = c(6, 14.1)) +
theme_bw() +
theme(panel.grid = element_blank())
AgeFitted + AgeResidual
```
Negative relationship between divorce and marriage age, even after we have accounted for the effect of the Marriage % Rate
:::
#### Posterior Prediction Plots
```{r Observed vs Fitted plot 5.3}
#| fig-width: 6
#| fig-height: 4
observed_vs_fitted_plot <-
fitted(b5.3) %>%
as_tibble() %>%
bind_cols(WaffleDivorce) %>%
ggplot(aes(x = Divorce, y = Estimate)) +
geom_abline(linetype = 2, color = "grey50", linewidth = 0.5) +
geom_point(size = 1.5, color = "firebrick4", alpha = 3/4) +
geom_linerange(aes(ymin = Q2.5, ymax = Q97.5),
linewidth = 1/4, color = "firebrick4") +
geom_linerange(aes(ymin = Estimate - Est.Error,
ymax = Estimate + Est.Error),
linewidth = 1/2, color = "firebrick4") +
# Note our use of the dot placeholder, here: https://magrittr.tidyverse.org/reference/pipe.html
geom_text(data = . %>% filter(Loc %in% c("ID", "UT", "NJ", "ME", "AR", "AL")),
aes(label = Loc),
hjust = 0, nudge_x = - 0.65) +
labs(x = "Observed divorce",
y = "Predicted divorce",) +
theme_bw() +
theme(panel.grid = element_blank())
observed_vs_fitted_plot
```
#### Causal Counterfactual Plots
```{r}
#| fig-width: 10
#| fig-height: 4
n_size = 300
simMarriages_age <- as_tibble(as_draws_df(b5.4)) %>%
mutate(MedianAgeMarriage_s = seq(from = -3, to = 3.5, length.out = n()),
simMarriageRateEst = Intercept + (b_MedianAgeMarriage_s * MedianAgeMarriage_s),
Marriage_s = rnorm(n(), simMarriageRateEst, sd = sigma)) %>%
dplyr::select(c(MedianAgeMarriage_s, Marriage_s)) %>%
slice_sample(n = n_size)
simMRatePred <- as_tibble(predict(b5.4, simMarriages_age)) %>%
cbind(simMarriages_age)
simDRatePred <- as_tibble(predict(b5.3, simMarriages_age)) %>%
cbind(simMarriages_age)
mcf_plot <- ggplot(data = simMRatePred, aes(x = MedianAgeMarriage_s, y = Marriage_s)) +
geom_ribbon(aes(ymin = Q2.5, ymax = Q97.5),
fill = "firebrick", alpha = .4)+
geom_smooth(method = "lm", color = "red4")+
scale_x_continuous("Set Median Age of Marriage",
breaks = at,
labels = round(at * sd(WaffleDivorce$MedianAgeMarriage) +
mean(WaffleDivorce$MedianAgeMarriage))) +
scale_y_continuous("Marriage Rate per 1000",
breaks = at,
labels = round(at * sd(WaffleDivorce$Marriage) +
mean(WaffleDivorce$Marriage))) +
labs(title = "Marriage Rate if you set Marriage Age")+
theme_minimal()
dcf_plot <- ggplot(data = simDRatePred, aes(x = MedianAgeMarriage_s, y = Estimate)) +
geom_ribbon(aes(ymin = Q2.5, ymax = Q97.5),
fill = "firebrick", alpha = .4)+
geom_smooth(method = "lm", color = "red4")+
scale_x_continuous("Set Median Age of Marriage",
breaks = at,
labels = round(at * sd(WaffleDivorce$MedianAgeMarriage) +
mean(WaffleDivorce$MedianAgeMarriage))) +
labs(y = "Divorce Rate per 1000", title = "Divorce Rate if you set Marriage Age")+
theme_minimal()
mcf_plot + dcf_plot
```
::::
"This procedure also brings home the message that regression models measure the remaining association of each predictor with the out- come, after already knowing the other predictors. In computing the predictor residual plots, you had to perform those calculations yourself. In the unified multivariate model, it all hap- pens automatically. Nevertheless, it is useful to keep this fact in mind, because regressions can behave in surprising ways as a result."
### Solving the DAG
From McElreath, "Age of marriage influences divorce in two ways. First it can have a direct effect, perhaps because younger people change faster than older people and are therefore more likely to grow incompatible with a partner. Second, it can have an indirect effect by influencing the marriage rate. If people get married earlier, then the marriage rate may rise, because there are more young people. Consider for example if an evil dictator forced everyone to marry at age 65. Since a smaller fraction of the population lives to 65 than to 25, forcing delayed marriage will also reduce the marriage rate. If marriage rate itself has any direct effect on divorce, maybe by making marriage more or less normative, then some of that direct effect could be the indirect effect of age at marriage."
```{r parameter comparison}
posterior_comparison <- bind_cols(
as_draws_df(b5.1) %>%
transmute(`b5.1_beta[" Median Marriage Age"]` = b_MedianAgeMarriage_s),
as_draws_df(b5.2) %>%
transmute(`b5.2_beta[" Marriage % Rate"]` = b_Marriage_s),
as_draws_df(b5.3) %>%
transmute(`b5.3_beta[" Median Marriage Age"]` = b_MedianAgeMarriage_s,
`b5.3_beta[" Marriage % Rate"]` = b_Marriage_s)
) %>%
pivot_longer(everything()) %>%
separate(name, into = c("fit", "parameter"), sep = "_")
# Create the plot with distributions
posterior_comparison %>%
ggplot(aes(x = value, y = fit)) +
stat_halfeye(point_interval = median_qi, .width = .95,
fill = "firebrick4", alpha = 0.8) +
labs(x = "Beta Coefficient Estimates",
y = "Model",
title = "Posterior Distributions for Different Models") +
theme_bw() +
theme(panel.grid = element_blank(),
strip.background = element_rect(fill = "transparent", color = "transparent"),
axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank()) +
facet_wrap(~ parameter, ncol = 1, labeller = label_parsed, scales = "free_x")
```
Once we know median age at marriage for a State, there is little or no additional predictive power in also knowing the rate of marriage in that State.
::: panel-tabset
#### US Map Residual
```{r}
#| fig-width: 6
#| fig-height: 4
deviance_plot_map <-
fitted(b5.3) %>%
as_tibble() %>%
bind_cols(WaffleDivorce) %>%
right_join(readRDS("externalData/us_states_geometry.rds"),
by = c("Location" = "NAME")) %>%
mutate(deviance = Divorce -Estimate) %>%
pivot_longer("deviance") %>%
ggplot() +
geom_sf(aes(fill = value, geometry = geometry),
size = 0) +
scale_fill_gradient(low = "#f8eaea", high = "firebrick4") +
coord_sf(xlim = c(-29e5, 21e5),
ylim = c(-2e6, 2e6)) +
theme_void() +
theme(legend.position = "none",
strip.text = element_text(margin = margin(0, 0, 0.5, 0))) +
labs(title = "Model Residuals By State", caption = "White = Over-estimateed Divorce, Red = Under-estimated Divorce")
deviance_plot_map
```
#### States by Residual
```{r}
#| fig-width: 3
#| fig-height: 6
residuals_plot <-
residuals(b5.3) %>%
as_tibble() %>%
rename(f_ll = Q2.5,
f_ul = Q97.5) %>%
bind_cols(
predict(b5.3) %>%
as_tibble() %>%
transmute(p_ll = Q2.5,
p_ul = Q97.5),
WaffleDivorce
) %>%
# here we put our `predict()` intervals into a deviance metric
mutate(p_ll = Divorce - p_ll,
p_ul = Divorce - p_ul) %>%
# now plot!
ggplot(aes(x = reorder(Loc, Estimate), y = Estimate)) +
geom_hline(yintercept = 0, linewidth = 1/2,
color = "firebrick4", alpha = 1/10) +
geom_pointrange(aes(ymin = f_ll, ymax = f_ul),
linewidth = 2/5, shape = 20, color = "firebrick4") +
geom_segment(aes(y = Estimate - Est.Error,
yend = Estimate + Est.Error,
x = Loc,
xend = Loc),
linewidth = 1, color = "firebrick4") +
geom_segment(aes(y = p_ll, yend = p_ul,
x = Loc, xend = Loc),
linewidth = 3, color = "firebrick4", alpha = 1/10) +
labs(x = NULL, y = NULL) +
coord_flip(ylim = c(-6, 5)) +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0, size = 7, margin = margin(r = 5)),
axis.text.x = element_text(size = 7),
axis.ticks.y = element_blank(),
panel.grid = element_blank(),
plot.margin = margin(20, 20, 20, 20))
residuals_plot
```
#### Waffle House Effect
```{r}
#| fig-width: 6
#| fig-height: 4
waffleHouseEffect_plot <-
residuals(b5.3) %>%
as_tibble() %>%
bind_cols(WaffleDivorce) %>%
mutate(wpc = WaffleHouses / Population) %>%
ggplot(aes(x = wpc, y = Estimate)) +
geom_point(size = 1.5, color = "firebrick4", alpha = 1/2) +
stat_smooth(method = "lm", fullrange = T,
color = "firebrick4", linewidth = 1/2,
fill = "firebrick", alpha = 1/5) +
geom_text_repel(data = . %>% filter(Loc %in% c("ME", "AR", "MS", "AL", "GA", "SC", "ID")),
aes(label = Loc),
seed = 5.6) +
scale_x_continuous("Waffles per capita", limits = c(0, 45)) +
ylab("Divorce error") +
coord_cartesian(xlim = range(0, 40)) +
theme_bw() +
theme(panel.grid = element_blank())
waffleHouseEffect_plot
```
:::
## Masked Relationships
New data set Comparative primate milk composition data, from Table 2 of Hinde and Milligan. 2011. Evolutionary Anthropology 20:9-23.
species: Species name
kcal.per.g: Kilocalories per gram of milk
mass: Body mass of mother, in kilograms
neocortex.perc: Percent of brain mass that is neocortex
```{r milk wrangling, include = FALSE}
milk %>%
select(kcal.per.g, mass, neocortex.perc) %>%
pairs(col = "firebrick4")
milk2 <- milk %>%
filter(!is.na(neocortex.perc)) %>%
mutate(neocortex.perc_s = (neocortex.perc - mean(neocortex.perc))/sd(neocortex.perc),
kcal.per.g_s = (kcal.per.g - mean(kcal.per.g))/sd(kcal.per.g),
mass_s = (mass - mean(mass))/sd(mass))
```
### Neocortex % Effect on Milk Calories
```{r neocortex percent model, include = FALSE}
milk.01 <-
brm(data = milk2,
family = gaussian,
kcal.per.g_s ~ 1 + neocortex.perc_s,
prior = c(prior(normal(0, .2), class = Intercept),
prior(normal(0, .5), class = b),
prior(exponential(1), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5, backend = "cmdstanr", silent = 2,
file = "fits/milk.01.6")
at <- c(-3, -2, -1, 0, 1, 2, 3)
plot(milk.01)
simMilk <- as_tibble(as_draws_df(milk.01)) %>%
mutate(simNeocortexPerc = seq(from = -3, to = 3, length.out = n()),
simKcalEst = Intercept + (b_neocortex.perc_s * simNeocortexPerc),
simKcal = rnorm(n(), simKcalEst, sd = sigma))
```
::: panel-tabset
#### 📈 μ vs full distribution
```{r mu vs full heat plot milk neocortex}
#| fig-width: 10