-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChapter05final.R
More file actions
executable file
·1433 lines (1155 loc) · 49.1 KB
/
Chapter05final.R
File metadata and controls
executable file
·1433 lines (1155 loc) · 49.1 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
#=======================================
# R code for Chapter 5 of "Bayesian GLMs in R for Ecology"
# by Mark Warren & Carl Smith
#=======================================
#Load packages
library(lattice)
library(ggplot2)
library(GGally)
library(tidyverse)
library(mgcv)
library(plyr)
library(lme4)
library(car)
library(devtools)
library(ggpubr)
library(qqplotr)
library(geiger)
library(INLA)
library(brinla)
library(gridExtra)
library(rlang)
#=======================================
# Import the data
ga <- read_csv(file = "stickleback.csv")
str(ga)
#=======================================
# The 9 steps to fitting a Bayesian GLM are:
# 1. State the question
# 2. Perform data exploration
# 3. Select a statistical model
# 4. Specify and justify priors
# 5. Fit the model
# 6. Obtain the posterior distribution
# 7. Conduct model checks
# 8. Interpret and present model output
# 9. Visualise the results
#=======================================
# 1. STATE THE QUESTION
#=======================================
# The aim of this study is to understand what ecological variables select
# for lateral plate number in 3-spined sticklebacks on North Uist:
# We will use an Information Theory approach to formulate a set of
# competing hypothesis and examine which is best supported by the data
models <- tibble(
model = c("M01", "M02", "M03", "M04", "M05", "M06", "M07", "M08", "M09"),
model_form = c("vert", "ph", "inve", "alt + dist", "alt + area", "comp", "vert + ph", "vert + comp", "ph + sl"),
ref = c("Hoogland et al. (1956)", "Giles (1983)", "Reimchen (1994)", "Raeymaekers et al. (2007)",
"Lucek et al. (2016)", "MacColl et al (2013)", "Spence et al. (2013)", "Magalhaes et al. (2016)", "Smith et al. (2020)")
)
models
#=======================================
# 2. PERFORM DATA EXPLORATION
#=======================================
# MISSING VALUES?
colSums(is.na(ga))
# loch dist alt area ph comp inve vert sl plate
# 0 0 0 0 0 0 0 0 0 0
#No missing data
#=======================================
# OUTLIERS
# A multi-panel Cleveland dotplot to examine continuous variables
# Fig. 5.1
#Add row numbers
ga <- ga %>%
mutate(order = seq(1:nrow(ga)))
My_theme <- theme(panel.background = element_blank(),
panel.border = element_rect(fill = NA, size = 1),
strip.background = element_rect(fill = "white",
color = "white", size = 1),
text = element_text(size = 14),
panel.grid.major = element_line(colour = "white", size = 0.1),
panel.grid.minor = element_line(colour = "white", size = 0.1))
#Write a function
multi_dotplot <- function(filename, Xvar, Yvar){
filename %>%
ggplot(aes(x = {{Xvar}})) +
#Note the double curly brackets from rlang package - it allows us to pass unquoted col names
geom_point(aes(y = {{Yvar}})) +
theme_bw() +
My_theme +
coord_flip() +
labs(x = "Order of Data")
}
#Choose variables
p1 <- multi_dotplot(ga, order, dist)
p2 <- multi_dotplot(ga, order, alt)
p3 <- multi_dotplot(ga, order, area)
p4 <- multi_dotplot(ga, order, ph)
p5 <- multi_dotplot(ga, order, sl)
p6 <- multi_dotplot(ga, order, plate)
#Create grid and plot
grid.arrange(p1, p2, p3, p4, p5, p6, nrow = 2)
#Log transform area
ga$log_area <- log10((ga$area))
# Compare area and log_area
# Fig 5.2
p7 <- multi_dotplot(ga, order, log_area)
grid.arrange(p3, p7, nrow = 1)
# Better
#=======================================
# DISTRIBUTION OF THE DEPENDENT VARIABLE
#Fig 5.3 Frequency polygon plot of plate number
ga %>%
ggplot(aes(plate)) +
geom_freqpoly( bins = 9) +
labs(x = "Number of lateral plates", y = "Frequency") +
My_theme +
theme(panel.border = element_rect(colour = "black", fill=NA, size = 1))
#=======================================
# BALANCE
# Examine the balance of categorical variables
table(ga$comp)
# no yes
# 33 24
table(ga$inve)
# no yes
# 32 25
table(ga$vert)
# no yes
# 8 49
#=======================================
# COLLINEARITY
ga %>%
ggpairs(columns = c("dist", "alt", "log_area", "ph", "comp", "inve", "vert", "sl"),
aes(alpha = 0.8), lower = list(continuous = "smooth_loess",
combo = wrap("facethist", binwidth = 5))) + My_theme
# A weak positive correlation between sl and pH
#Calculate Variance Inflation Factor (VIF)
round(vif(glm(plate ~ ph + sl, family = "poisson", data = ga)),2)
# ph sl
# 1.95 1.95
# Some variance inflation but <3
#=======================================
# ZEROS IN THE RESPONSE VARIABLE
round((sum(ga$plate == 0) / nrow(ga))*100,0)
#11% zeros
# Not clear whether this is problematic at this stage...
#=======================================
# RELATIONSHIPS
# Fig. 5.5
My_theme <- theme(panel.background = element_blank(),
panel.border = element_rect(fill = NA, size = 1),
strip.background = element_rect(fill = "white",
color = "white", size = 1),
text = element_text(size = 14),
panel.grid.major = element_line(colour = "white", size = 0.1),
panel.grid.minor = element_line(colour = "white", size = 0.1))
grid.arrange(
ga %>%
ggplot() +
geom_point(aes(x = dist, y = plate), alpha = 0.5) +
geom_smooth(aes(x = dist, y = plate), method = 'lm', se=FALSE)+
labs(x = "Distance (km)", y = "Plate number") +
My_theme,
ga %>%
ggplot() +
geom_point(aes(x = alt, y = plate), alpha = 0.5) +
geom_smooth(aes(x = alt, y = plate), method = 'lm', se=FALSE)+
labs(x = "Altitude (m)", y = "Plate number") +
My_theme,
ga %>%
ggplot() +
geom_point(aes(x = ph, y = plate), alpha = 0.5) +
geom_smooth(aes(x = ph, y = plate), method = 'lm', se=FALSE)+
labs(x = "pH", y = "Plate number") +
My_theme,
ga %>%
ggplot() +
geom_point(aes(x = sl, y = plate), alpha = 0.5) +
geom_smooth(aes(x = sl, y = plate), method = 'lm', se=FALSE)+
labs(x = "SL (mm)", y = "Plate number") +
My_theme,
nrow = 2)
# Categorical covariates
# Fig. 5.6
label_inve <- c("no" = "No invertebrate predators",
"yes" = "Invertebrate predators")
label_vert <- c("no" = "No vertebrate predators",
"yes" = "Vertebrate predators")
ggplot() +
geom_boxplot(data = ga, aes(y = plate, x = comp), fill = "gray88") +
geom_jitter(data = ga, aes(y = plate, x = comp),
size = 2, width = 0.05, height = 0.1) +
xlab("Competitors present") + ylab("Plate number")+
theme(text = element_text(size=13)) +
theme(panel.background = element_blank())+
theme(panel.border = element_rect(fill = NA, colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))+
theme(strip.text = element_text(size = 12, face="italic")) +
facet_grid(vert ~ inve,
scales = "fixed", space = "fixed",
labeller=labeller (vert = label_vert,
inve = label_inve))
#=======================================
# 3. SELECT A STATISTICAL MODEL
#=======================================
# Plate number is a count, and includes zeros but
# no negative values
# Poisson distribution is an appropriate starting point
# Use an IT approach and formulate a series of a priori models
#=======================================
# 4. SPECIFY PRIORS
#=======================================
# Fit each model with default priors and with informative
# priors based on pilot data from Smith et al. (2020) J Zool
# ======================================
# 5. FIT MODELS
#=======================================
# Specify the formulae for the a priori models
f01 <- plate ~ vert
f02 <- plate ~ ph
f03 <- plate ~ inve
f04 <- plate ~ alt + dist
f05 <- plate ~ alt + log_area
f06 <- plate ~ comp
f07 <- plate ~ vert + ph
f08 <- plate ~ vert + comp
f09 <- plate ~ ph + sl
# Models M01-10 with default priors
M01 <- inla(f01, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M02 <- inla(f02, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M03 <- inla(f03, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M04 <- inla(f04, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M05 <- inla(f05, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M06 <- inla(f06, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M07 <- inla(f07, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M08 <- inla(f08, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
M09 <- inla(f09, control.compute = list(dic = TRUE),
family = "poisson", data = ga)
# Extract DICs
DefDIC <- c(M01$dic$dic,M02$dic$dic,M03$dic$dic,
M04$dic$dic,M05$dic$dic,M06$dic$dic,
M07$dic$dic,M08$dic$dic,M09$dic$dic)
# Add weighting
DefDIC.weights <- aicw(DefDIC)
# Add names
DefDIC.weights %>%
mutate(model = c("M01","M02","M03",
"M04","M05","M06",
"M07","M08","M09")) %>%
select(model, everything()) %>%
arrange(fit) %>%
mutate(across(2:4, round, 2))
# Print DICs
dprint.def <- print (DefDIC.weights,
abbrev.names = FALSE)
# Order DICs by fit
round(dprint.def[order(dprint.def$fit),],2)
# fit delta w
# M09 190.97 0.00 0.79
# M02 194.29 3.32 0.15
# M07 196.01 5.04 0.06
# M04 219.77 28.81 0.00
# M05 224.46 33.49 0.00
# M08 231.96 40.99 0.00
# M01 236.48 45.51 0.00
# M06 243.70 52.73 0.00
# M03 246.54 55.57 0.00
#=======================================
# Models I01-10 with informative priors
I01 <- inla(f01, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = 2.1,
prec.intercept = 0.5^(-2),
mean = list(vertyes = 1.4),
prec = list(vertyes = 0.6^(-2))))
I02 <- inla(f02, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = -3.3,
prec.intercept = 0.8^(-2),
mean = list(ph = 0.7),
prec = list(ph = 0.2^(-2))))
I03 <- inla(f03, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = 1.1,
prec.intercept = 0.3^(-2),
mean = list(inveyes = 0.4),
prec = list(inveyes = 0.3^(-2))))
I04 <- inla(f04, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = 2.5,
prec.intercept = 0.3^(-2),
mean = list(alt = -0.01,
dist = -0.1),
prec = list(alt = 0.1^(-2),
dist = 0.1^(-2))))
I05 <- inla(f05, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = 2.9,
prec.intercept = 0.7^(-2),
mean = list(alt = -0.01,
log_area = -0.02),
prec = list(alt = 0.1^(-2),
log_area = 0.1^(-2))))
I06 <- inla(f06, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = 1.6,
prec.intercept = 0.3^(-2),
mean = list(compyes = 0.5),
prec = list(compyes = 0.3^(-2))))
I07 <- inla(f07, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = -4.8,
prec.intercept = 1.9^(-2),
mean = list(vertyes = 0.6,
ph = 0.6),
prec = list(vertyes = 0.5^(-2),
ph = 0.2^(-2))))
I08 <- inla(f08, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = 1.7,
prec.intercept = 0.4^(-2),
mean = list(vertyes = 0.7,
compyes = 0.9),
prec = list(vertyes = 0.3^(-2),
compyes = 0.3^(-2))))
I09 <- inla(f09, family = "poisson", data = ga,
control.compute = list(dic = TRUE),
control.fixed = list(mean.intercept = -3.4,
prec.intercept = 0.6^(-2),
mean = list(ph = 0.5,
sl = 0.1),
prec = list(ph = 0.2^(-2),
sl = 0.05^(-2))))
# Extract DICs
InfDIC <- c(I01$dic$dic, I02$dic$dic, I03$dic$dic,
I04$dic$dic, I05$dic$dic, I06$dic$dic,
I07$dic$dic, I08$dic$dic, I09$dic$dic)
# Add weighting
InfDIC.weights <- aicw(InfDIC)
# Add names
rownames(InfDIC.weights) <- c("I01","I02","I03",
"I04","I05","I06",
"I07","I08","I09")
# Print DICs
dprint.inf <- print (InfDIC.weights,
abbrev.names = FALSE)
# Order DICs by fit
round(dprint.inf[order(dprint.inf$fit),],2)
# fit delta w
# I09 189.39 0.00 0.84
# I02 193.34 3.95 0.12
# I07 195.43 6.03 0.04
# I04 219.46 30.07 0.00
# I05 224.38 34.98 0.00
# I08 234.29 44.90 0.00
# I01 236.59 47.19 0.00
# I06 243.45 54.06 0.00
# I03 245.97 56.58 0.00
# Compare best default and informative models
ComDIC <- c(M09$dic$dic, I09$dic$dic)
DIC <- cbind(ComDIC)
rownames(DIC) <- c("default priors","informative priors")
round(DIC,0)
# ComDIC
# default priors 191
# informative priors 189
# I09 has a marginally better fit
#=======================================
# 6. OBTAIN THE POSTERIOR DISTRIBUTION
#=======================================
# A. Best-fitting default model (M09)
# Posterior mean values and 95% CI for fixed effects (default)
M09Betas <- M09$summary.fixed[,c("mean", "sd",
"0.025quant",
"0.975quant")]
round(M09Betas, digits = 3)
# mean sd 0.025quant 0.975quant
# (Intercept) -4.011 0.657 -5.305 -2.724
# ph 0.488 0.126 0.242 0.735
# sl 0.052 0.022 0.007 0.095
# The first column shows the posterior mean, the second the
# standard deviation and the third and fourth columns show the
# 2.5% and 97.5% quantiles of the posterior distribution.
# These two latter values are the 95% credible intervals; there is
# a 95% probability that the regression parameters fall within these
# intervals.
# If 0 lies outside this interval we conclude that the regression parameter
# is statistically 'important’. This is the Bayesian equivalent of
# ‘significant’ in a frequentist model.
# Instead of summarising the posterior distribution of the fixed effects
# with a posterior mean and a 95% credible interval, we can also plot
# the posterior distributions - available in the object `M10$marginals.fixed`.
# Plot posterior distributions for fixed parameters
# Fig. 5.7
# Model intercept (Beta1)
PosteriorBeta1.M09 <- as.data.frame(M09$marginals.fixed$`(Intercept)`)
PriorBeta1.M09 <- data.frame(x = PosteriorBeta1.M09[,"x"],
y = dnorm(PosteriorBeta1.M09[,"x"],0,0))
Beta1mean.M09 <- M09Betas["(Intercept)", "mean"]
Beta1lo.M09 <- M09Betas["(Intercept)", "0.025quant"]
Beta1up.M09 <- M09Betas["(Intercept)", "0.975quant"]
beta1 <- ggplot() +
annotate("rect", xmin = Beta1lo.M09, xmax = Beta1up.M09,
ymin = 0, ymax = 0.62, fill = "gray88") +
geom_line(data = PosteriorBeta1.M09,
aes(y = y, x = x), lwd = 1.2) +
geom_line(data = PriorBeta1.M09,
aes(y = y, x = x), color = "gray55", lwd = 1.2) +
xlab("Intercept") +
ylab("Density") +
xlim(-8,1) + ylim(0,0.62) +
geom_vline(xintercept = 0, linetype = "dotted") +
geom_vline(xintercept = Beta1mean.M09, linetype = "dashed") +
theme(text = element_text(size=13)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# ph (Beta2)
PosteriorBeta2.M09 <- as.data.frame(M09$marginals.fixed$`ph`)
PriorBeta2.M09 <- data.frame(x = PosteriorBeta2.M09[,"x"],
y = dnorm(PosteriorBeta2.M09[,"x"],0,31.6))
Beta2mean.M09 <- M09Betas["ph", "mean"]
Beta2lo.M09 <- M09Betas["ph", "0.025quant"]
Beta2up.M09 <- M09Betas["ph", "0.975quant"]
beta2 <- ggplot() +
annotate("rect", xmin = Beta2lo.M09, xmax = Beta2up.M09,
ymin = 0, ymax = 3.3, fill = "gray88") +
geom_line(data = PosteriorBeta2.M09,
aes(y = y, x = x), lwd = 1.2) +
geom_line(data = PriorBeta2.M09,
aes(y = y, x = x), color = "gray55", lwd = 1.2) +
xlab("Slope for pH") +
ylab("Density") +
xlim(-0.5,1.5) + ylim(0,3.3) +
geom_vline(xintercept = 0, linetype = "dotted") +
geom_vline(xintercept = Beta2mean.M09, linetype = "dashed") +
theme(text = element_text(size=13)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# SL (Beta3)
PosteriorBeta3.M09 <- as.data.frame(M09$marginals.fixed$`sl`)
PriorBeta3.M09 <- data.frame(x = PosteriorBeta3.M09[,"x"],
y = dnorm(PosteriorBeta3.M09[,"x"],0,31.6))
Beta3mean.M09 <- M09Betas["sl", "mean"]
Beta3lo.M09 <- M09Betas["sl", "0.025quant"]
Beta3up.M09 <- M09Betas["sl", "0.975quant"]
beta3 <- ggplot() +
annotate("rect", xmin = Beta3lo.M09, xmax = Beta3up.M09,
ymin = 0, ymax = 20, fill = "gray88") +
geom_line(data = PosteriorBeta3.M09,
aes(y = y, x = x), lwd = 1.2) +
geom_line(data = PriorBeta3.M09,
aes(y = y, x = x), color = "gray55", lwd = 1.2) +
xlab("Slope for SL") +
ylab("Density") +
xlim(-0.05,0.15) + ylim(0,20) +
geom_vline(xintercept = 0, linetype = "dotted") +
geom_vline(xintercept = Beta3mean.M09, linetype = "dashed") +
theme(text = element_text(size=13)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# Combine plots
ggarrange(beta1, beta2, beta3,
labels = c("A", "B", "C"),
ncol = 2, nrow = 2)
# These density functions look normally distributed because INLA assumes
# that the posterior distributions of the betas are Gaussian.
#=======================================
# B. Informative model (I09)
# Posterior mean values and 95% CI for fixed effects (informative)
I09Betas <- I09$summary.fixed[,c("mean", "sd",
"0.025quant",
"0.975quant")]
round(I09Betas, digits = 2)
# mean sd 0.025quant 0.975quant
# (Intercept) -3.74 0.43 -4.59 -2.89
# ph 0.44 0.10 0.25 0.62
# sl 0.05 0.02 0.02 0.09
# The first column shows the posterior mean, the second the
# standard deviation and the third and fourth columns show the
# 2.5% and 97.5% quantiles of the posterior distribution.
# Plot posterior distributions for fixed parameters
# Fig. 5.8
# Model intercept (Beta1)
PosteriorBeta1.I09 <- as.data.frame(I09$marginals.fixed$`(Intercept)`)
PriorBeta1.I09 <- data.frame(x = PosteriorBeta1.I09[,"x"],
y = dnorm(PosteriorBeta1.I09[,"x"],-3.4,0.6))
Beta1mean.I09 <- I09Betas["(Intercept)", "mean"]
Beta1lo.I09 <- I09Betas["(Intercept)", "0.025quant"]
Beta1up.I09 <- I09Betas["(Intercept)", "0.975quant"]
Ibeta1 <- ggplot() +
annotate("rect", xmin = Beta1lo.I09, xmax = Beta1up.I09,
ymin = 0, ymax = 1, fill = "gray88") +
geom_line(data = PosteriorBeta1.I09,
aes(y = y, x = x), lwd = 1.2) +
geom_line(data = PriorBeta1.I09,
aes(y = y, x = x), color = "gray55", lwd = 1.2) +
xlab("Intercept") +
ylab("Density") +
xlim(-8,1) + ylim(0,1) +
geom_vline(xintercept = 0, linetype = "dotted") +
geom_vline(xintercept = Beta1mean.I09, linetype = "dashed") +
theme(text = element_text(size=13)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# ph (Beta2)
PosteriorBeta2.I09 <- as.data.frame(I09$marginals.fixed$`ph`)
PriorBeta2.I09 <- data.frame(x = PosteriorBeta2.I09[,"x"],
y = dnorm(PosteriorBeta2.I09[,"x"],0.5,0.2))
Beta2mean.I09 <- I09Betas["ph", "mean"]
Beta2lo.I09 <- I09Betas["ph", "0.025quant"]
Beta2up.I09 <- I09Betas["ph", "0.975quant"]
Ibeta2 <- ggplot() +
annotate("rect", xmin = Beta2lo.I09, xmax = Beta2up.I09,
ymin = 0, ymax = 4.5, fill = "gray88") +
geom_line(data = PosteriorBeta2.I09,
aes(y = y, x = x), lwd = 1.2) +
geom_line(data = PriorBeta2.I09,
aes(y = y, x = x), color = "gray55", lwd = 1.2) +
xlab("Slope for pH") +
ylab("Density") +
xlim(-0.5,1.5) + ylim(0,4.5) +
geom_vline(xintercept = 0, linetype = "dotted") +
geom_vline(xintercept = Beta2mean.I09, linetype = "dashed") +
theme(text = element_text(size=13)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# SL (Beta3)
PosteriorBeta3.I09 <- as.data.frame(I09$marginals.fixed$`sl`)
PriorBeta3.I09 <- data.frame(x = PosteriorBeta3.I09[,"x"],
y = dnorm(PosteriorBeta3.I09[,"x"],0.1,0.05))
Beta3mean.I09 <- I09Betas["sl", "mean"]
Beta3lo.I09 <- I09Betas["sl", "0.025quant"]
Beta3up.I09 <- I09Betas["sl", "0.975quant"]
Ibeta3 <- ggplot() +
annotate("rect", xmin = Beta3lo.I09, xmax = Beta3up.I09,
ymin = 0, ymax = 25, fill = "gray88") +
geom_line(data = PosteriorBeta3.I09,
aes(y = y, x = x), lwd = 1.2) +
geom_line(data = PriorBeta3.I09,
aes(y = y, x = x), color = "gray55", lwd = 1.2) +
xlab("Slope for SL") +
ylab("Density") +
xlim(-0.05,0.15) + ylim(0,25) +
geom_vline(xintercept = 0, linetype = "dotted") +
geom_vline(xintercept = Beta3mean.I09, linetype = "dashed") +
theme(text = element_text(size=13)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1))+
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# Combine plots
ggarrange(Ibeta1, Ibeta2, Ibeta3,
labels = c("A", "B", "C"),
ncol = 2, nrow = 2)
#=======================================
# Compare with frequentist Poisson GLM
Freq <- glm(plate ~ ph + sl,
family = "poisson",
data = ga)
round(summary(Freq)$coef[,1:4],3)
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) -4.013 0.657 -6.106 0.000
# ph 0.488 0.126 3.885 0.000
# sl 0.052 0.022 2.316 0.021
# Posterior mean values and 95% CI for fixed effects (default priors)
round(M09Betas, digits = 3)
# mean sd 0.025quant 0.975quant
# (Intercept) -4.011 0.657 -5.305 -2.724
# ph 0.488 0.126 0.242 0.735
# sl 0.052 0.022 0.007 0.095
# Posterior mean values and 95% CI for fixed effects (informative priors)
round(I09Betas, digits = 3)
# mean sd 0.025quant 0.975quant
# (Intercept) -3.737 0.432 -4.585 -2.891
# ph 0.436 0.095 0.249 0.623
# sl 0.054 0.019 0.018 0.091
pivot_wider(round(M09Betas, digits = 2) %>%
mutate(term = c("(Intercept)", "ph", "sl")) %>%
select(term, mean, sd) %>%
unite(param, mean, sd, sep = ", sd="),
names_from = term,
values_from = param)
kable(
bind_rows(
pivot_wider(broom::tidy(Freq)%>%
mutate_if(is.numeric, round, 2) %>%
select(term, estimate, std.error) %>%
unite(param, estimate, std.error, sep = ", sd="),
names_from = term,
values_from = c(param)),
pivot_wider(round(M09Betas, digits = 2) %>%
mutate(term = c("(Intercept)", "ph", "sl")) %>%
select(term, mean, sd) %>%
unite(param, mean, sd, sep = ", sd="),
names_from = term,
values_from = param),
pivot_wider(round(I09Betas, digits = 2) %>%
mutate(term = c("(Intercept)", "ph", "sl")) %>%
select(term, mean, sd) %>%
unite(param, mean, sd, sep = ", sd="),
names_from = term,
values_from = param)
)%>%
mutate(Model = c("Frequentist", "Bayesian (default)", "Bayesian (informative)")) %>%
select(Model, everything()),
align = "lccrr",
format = "html", col.names = c("Model", "Intercept", "pH", "sl"),
caption = 'Comparison of model parameters for frequentist,
Bayesian model with non-informative and informative priors of Poisson
GLM model to investigate the evolution of lateral plate number in three-spined sticklebacks on North Uist.'
) %>%
kable_styling(bootstrap_options = "striped", full_width = F)
#=======================================
# 7. MODEL CHECKS
#=======================================
# A. Model selection
# We have used an IT approach to conduct model selection, setting up
# alternative plausible models and testing among them using the DIC
# The rank order of models with default priors is:
round(dprint.def[order(dprint.def$fit),],2)
# fit delta w
# M09 190.97 0.00 0.79
# M02 194.29 3.32 0.15
# M07 196.01 5.04 0.06
# M04 219.77 28.81 0.00
# M05 224.46 33.49 0.00
# M08 231.96 40.99 0.00
# M01 236.48 45.51 0.00
# M06 243.70 52.73 0.00
# M03 246.54 55.57 0.00
# And with informative priors:
round(dprint.inf[order(dprint.inf$fit),],2)
# fit delta w
# I09 189.39 0.00 0.84
# I02 193.34 3.95 0.12
# I07 195.40 6.00 0.04
# I04 219.46 30.07 0.00
# I05 224.38 34.98 0.00
# I08 231.71 42.32 0.00
# I01 236.40 47.00 0.00
# I06 244.07 54.68 0.00
# I03 246.33 56.94 0.00
# In each case model 09 is the best-fitting, with the model
# with informative priors marginally better than the model
# with default priors
# Compare best-fitting models with non-informative and informative priors
dic2 <- c(M09$dic$dic, I09$dic$dic)
DIC2 <- cbind(dic2)
rownames(DIC2) <- c("default priors","informative priors")
round(DIC2,0)
# default priors 191
# informative priors 189
# These are essentially the same
#=======================================
# B. Dispersion
# (Just for model with informative priors)
# Poisson GLMs assume that the mean and variance of the response variable
# increase at the same rate. This assumption must be confirmed.
# Overdispersion means that a Poisson distribution does not adequately
# model the variance and is not appropriate for the analysis.
# We will implement the 7-step protocol of Zuur et al. (2017)
# to determine whether the Poisson GLM is over- or under-dispersed.
# 1. Apply Poisson GLM in INLA
# 2. Simulate a set of regression parameters from the posterior distribution
# 3. Calculate expected values
# 4. Simulate count data using the rpois function
# 5. Calculate Pearson residuals for simulated data
# 6. Repeat steps 2-5 x 1000 times
# 7. Compare sums of squared Pearson residuals with observed data
# 1. Refit the model with the 'config = TRUE' option,
# which permits us to simulate regression parameters.
I09 <- inla(f09, family = "poisson", data = ga,
control.compute = list(config = TRUE),
control.predictor = list(compute = TRUE),
control.fixed = list(mean.intercept = -3.4,
prec.intercept = 0.6^(-2),
mean = list(ph = 0.5,
sl = 0.1),
prec = list(ph = 0.2^(-2),
sl = 0.05^(-2))))
# 2. Simulate regression parameters using the inla.posterior.sample
# function to simulate from the model. The output is
# stored in the Sim object.
set.seed(1966)
SimData <- inla.posterior.sample(n = 1, result = I09)
# This gives an object with 60 rows for this
# data set and model. The first 57
# rows are simulated values for eta = X * beta,
# where X is the matrix with covariates, and
# the last 3 rows are simulated regression parameters.
# This is just one set of simulated values
# (i.e. n = 1 in the function above).
SimData[[1]]$latent
# 3: Calculate predicted values
BetaRows <- 58:60 #Last 3 rows are the betas
BetaRows <- (nrow(SimData[[1]]$latent) - 2):nrow(SimData[[1]]$latent)
Betas <- SimData[[1]]$latent[BetaRows]
Betas #These are the simulated betas (from the joint distribution)
# Now get the corresponding X matrix so that INLA can calculate X * Betas.
X <- model.matrix(~ ph + sl, data = ga)
# And now we can calculate: exp(X * Betas)
mu <- exp(X %*% Betas)
# 4. Simulate count data
Ysim <- rpois(n = nrow(ga), lambda = mu)
# We now have 57 simulated values that
# correspond to the observed covariate values.
# 5: Calculate summary statistic
mu1 <- I09$summary.fitted.values[,"mean"]
Es <- (Ysim - mu1) /sqrt(mu1)
N <- nrow(ga)
Npar <- length(BetaRows)
round(sum(Es^2) / (N - Npar),1)
# This should be close to 1.
# Step 6: Repeat steps 2 – 5 x 1000 times
SimData <- inla.posterior.sample(n = 1000, result = I09)
# We have 1000 simulated mean values from the model.
# Extract the simulated betas and predict plate number.
N <- nrow(ga)
Ysim <- matrix(nrow = N, ncol = 1000)
mu.sim <- matrix(nrow = N, ncol = 1000)
for (i in 1:1000){
Betas <- SimData[[i]]$latent[BetaRows]
mu.sim[,i] <- exp(X %*% Betas)
Ysim[,i] <- rpois(n = N, lambda = exp(X %*% Betas))
}
# 7: Compare simulation results and observed data
E1 <- (ga$plate - mu1) /sqrt(mu1)
Dispersion <- sum(E1^2) / (N - Npar)
# We calculate the same statistic for
# each of the simulated data sets.
Dispersion.sim <- NULL
for(i in 1:1000){
e2 <- (Ysim[,i] - mu.sim[,i]) /sqrt(mu.sim[,i])
Dispersion.sim[i] <- sum(e2^2) / (N - Npar)
}
# Plot the simulated results
# Fig. 5.9
par(mfrow = c(1,1), mar = c(5,5,2,2), cex.lab = 1.3)
hist(Dispersion.sim,
xlab = "Model dispersion",
ylab = "Frequency",
main = "",
xlim = c(0, 2.5),
breaks = 16)
# And identify the dispersion for the original Poisson GLM
points(x = Dispersion,
y = 0,
pch = 19,
cex = 2.5,
col = 1)
# The dispersion statistic for the
# observed data is at the lower end of
# the simulated data sets, indicating that
# the variation in the observed data is lower
# than is expected for a Poisson distribution,
# which indicates mild under-dispersion.
#=======================================
# C. Posterior predictive check
I09.pred <- inla(f09, family = "poisson", data = ga,
control.predictor = list(link = 1,
compute = TRUE),
control.compute = list(dic = TRUE,
cpo = TRUE),
control.fixed = list(mean.intercept = -3.4,
prec.intercept = 0.6^(-2),
mean = list(ph = 0.5,
sl = 0.1),
prec = list(ph = 0.2^(-2),
sl = 0.05^(-2))))
ppp <- vector(mode = "numeric", length = nrow(ga))
for(i in (1:nrow(ga))) {
ppp[i] <- inla.pmarginal(q = ga$plate[i],
marginal = I09.pred$marginals.fitted.values[[i]])
}
# Fig. 5.10
ggplot() +
geom_histogram(aes(ppp), binwidth = 0.1,
colour = "black", fill = "gray88") +
xlab("Posterior predictive p-values") +
ylab("Frequency") +
geom_vline(xintercept = 0.5, linetype = "dotted") +
theme(text = element_text(size=15)) +
theme(panel.background = element_blank()) +
theme(panel.border = element_rect(fill = NA,
colour = "black", size = 1)) +
theme(strip.background = element_rect
(fill = "white", color = "white", size = 1))
# Problem.