-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathptII_quan_Bayes_case_presidential-debates.r
2790 lines (2328 loc) · 82 KB
/
ptII_quan_Bayes_case_presidential-debates.r
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
### (C) 2005-2023 by Leo Guertler
### R-code supplement
### to the book
###
### "Subjektive Ansichten und objektive Betrachtungen"
###
### written by Gürtler & Huber (2023)
###
### All R-code is published under the GPL v3 license:
###
### https://www.gnu.org/licenses/gpl-3.0.en.html
###
### except for 'borrowed' code - see links and references.
### For this R-code the original license of the respective
### authors is valid.
###
### R-code published on
###
### https://osdn.net/projects/mixedmethod-rcode
### https://github.com/abcnorio/mixedmethod-rcode
# file:
# ptII_quan_Bayes_case_presidential-debates.r
# location:
# chap. 6 [6.15.3]
# „I, we, and nation“ — präsidiale Eigenwerbung Teil 2
# note:
# does not run after R 3.4 unless you have the appropriate package "appell" for your working R version
# load necessary libs
library(pwr)
library(BayesianFirstAid)
library(emdbook)
library(ggplot2)
library(coda)
library(HDInterval)
library(BayesFactor)
# load functions
source("ptall_generalfuncs_Bayes_binomial-prop-test.r")
# requires windows
# source("ptall_generalfuncs_appell.r")
source("DiM_Bretthorst_UMS.r")
# start the presidential debates analyses
pres <- t(matrix(c(16,101,91, 32,131,88), nrow=2, byrow=TRUE,dimnames=list(c("Bush","Kerry"),c("nation","I","we"))))
pres
counts.bk <- c(16,101,91, 32,131,88)
president <- gl(2,3, labels=c("Bush","Kerry"))
term <- gl(3,1,6, labels=c("nation","I","we"))
pres.dat <- data.frame(counts.bk,president,term)
pres.dat
# descriptive
# rows
prop.table(pres, 1)
margin.table(pres, 1)
# cols
prop.table(pres, 2)
margin.table(pres, 2)
# all
addmargins(pres)
# frequentist solution
cor(pres[,1], pres[,2])
chisq.test(pres)
set.seed(88772)
chisq.test(pres, sim=TRUE, B=1e5)
prop.test(pres)
# we reduce to 2x2 Chi^2 table
pres
pres.2x2 <- rbind(pres["I",],pres["nation",]+pres["we",])
rownames(pres.2x2) <- c("I","we/nation")
pres.2x2
addmargins(pres.2x2)
cor(pres.2x2[,1], pres.2x2[,2])
chisq.test(pres.2x2)
set.seed(88772)
chisq.test(pres.2x2, sim=TRUE, B=1e5)
prop.test(pres.2x2)
# power
# library(pwr)
# power = ?
pwr.2p2n.test(h=0.2,n1=208,n2=251,power=NULL,sig=0.07)$power
# effect size = ?
pwr.2p2n.test(h=NULL,n1=208,n2=251,power=0.7,sig=0.07)$h
# sample size = ?
pwr.2p2n.test(h=0.2,n1=208,n2=NULL,power=0.7,sig=0.07)$n2
pwr.2p2n.test(h=0.2,n1=NULL,n2=251,power=0.7,sig=0.07)$n1
# necessary samples versus empirical samples (Bush, Kerry)
c(299,397)/colSums(pres.2x2)
####
# JAGS MCMC proportion test
# library(BayesianFirstAid)
# library(emdbook)
# analyze for rows means to t(pres.2x2) so that Bush versus Kerry is analyzed!!!
t(pres.2x2)
pres.2x2 # rows = terms -> analyze for different frequency of usage of the combined terms I vs. we/nation
t(pres.2x2) # rows = terms -> analyze for different frequency of usage between Bush and Kerry
pres.2x2.bprop <- bayes.prop.test(t(pres.2x2), cred.mass=0.95, n.iter=15000, progress.bar="text")
pres.2x2.bprop
# summary
BFA.summary.bayes_prop_test(pres.2x2.bprop)
# graphical diagnostics
BFA.mcmcplot.thetas(pres.2x2.bprop)
# library(ggplot2)
qplot(as.data.frame(pres.2x2.bprop)[,1],as.data.frame(pres.2x2.bprop)[,2],geom=c("hex"), xlab=expression(theta[1]), ylab=expression(theta[2]))
# MCMC diagnostics
par(oma=c(2,1,4,1), "cex.axis"=1, bty="l")
diagnostics(pres.2x2.bprop)
mtext("MCMC diagnostics", outer=TRUE, line=1.7, cex=1.5, side=3)
# model code
model.code(pres.2x2.bprop)
# TODO - tweak the prior!!!!
# plot posterior
plot(pres.2x2.bprop)
# not run
# analyze for original rows!
pres.2x2 # rows = terms I versus we/nation
pres.t2x2.bprop <- bayes.prop.test(pres.2x2, cred.mass=0.95, n.iter=15000, progress.bar="text")
# summary
BFA.summary.bayes_prop_test(pres.t2x2.bprop)
# graphical diagnostics
BFA.mcmcplot.thetas(pres.t2x2.bprop)
# end of not run
# posterior odds ratios -> see BFA.summary.bayes_prop_test()
# compare models relative freqs
# diff crit for ROPE prob. -> ROPE = region of practical equivalence
# see Kruschke 2011 5% = ROPE[-5,+5]
diff.crit <- 3/100
theta.prop.within.ROPE <- as.data.frame(pres.2x2.bprop)
head(theta.prop.within.ROPE)
# whether probability that the group difference is within the ROPE
theta.prob.equal <- mean(abs((theta.prop.within.ROPE$theta1 - theta.prop.within.ROPE$theta2)) < diff.crit)
theta.prob.equal
# relative frequencies are practically different
1 - theta.prob.equal
# odds ratio in favor of equality
theta.prob.equal / (1 - theta.prob.equal)
# odds ratio in favor of a difference
(1 - theta.prob.equal) / theta.prob.equal
# excursion
26+26+10+15
# 77
77^45
# 7.799785e+84
(77^45)/100000/3600/24/365.25
# 2.471603e+72
(26+10)^7
# 78364164096
(36^7)/100000/3600/24/365.25
# 0.02483211
#### Simulation from posterior draws
# brute force MCMC!
# regardless whether prior or posterior
# use a1, b1 as well as a2, b2
# library(coda)
# library(HDInterval)
# MCMC brute force variante 1
# some arbitrary values
res <- bayes.prop.mcmc(a1=4, b1=8, a2=3, b2=6, n.mcmc=1e+4, nchains=4, credMass=0.95)
str(res)
coda:::plot.mcmc(as.mcmc(res$mcmc), col="darkred")
# Jeffrey's prior
#a.prior <- 1/2
#b.prior <- 1/2
# simple gibbs sampler
seed <- 5555
set.seed(seed)
# here comparison of prior and a beta distribution
# for practical purpose one compares two beta distributions
# AND adds a prior to each of them
# uniform prior, shape first beta distribution
a1 <- 1
b1 <- 1
# second beta distribution
a2 <- 0.6
b2 <- 5
n.mcmc <- 1e5
crit.equivalence <- 0.6
reps <- 4
theta.diff <- replicate(reps, rbeta(n.mcmc, shape1=a1, shape2=b1) - rbeta(n.mcmc, shape1=a2, shape2=b2))
str(theta.diff)
prob.diff <- apply(theta.diff,2, function(x) mean(x < crit.equivalence))
prob.diff
# in this case with prior a=1, b=1 result is the same
# as using "only" likelihood function to convert si,Ni to a,b
# analysis
pres.2x2
# default: analysis for rows (here: I vs we/nation)
# we want to analyze for Bush vs. Kerry
pres.2x2.bprop.mcmc <- bprop.mcmc(pres.2x2, analyze="cols")
str(pres.2x2.bprop.mcmc)
bayes.plot.mcmc(bprop.mcmc.res=pres.2x2.bprop.mcmc)
# TODO
# diagnostics
# posterior Odds Ratios
credMass <- 0.99
mean(abs(pres.2x2.bprop.mcmc$mcmc[["theta (diff)"]]) < (1-credMass))
# better ROPE
mean(abs(pres.2x2.bprop.mcmc$mcmc[["theta (diff)"]]) < 0.03)
mean(abs(pres.2x2.bprop.mcmc$mcmc[["theta (diff)"]]) < 0.05)
mean(abs(pres.2x2.bprop.mcmc$mcmc[["theta (diff)"]]) < 0.1)
#etc... further hypotheses possible
# plot sequence of hypotheses
# define credMass area
sek <- seq(0,0.3,0.01)
bprop.vs.sek <- sapply(sek, function(i) mean(abs(pres.2x2.bprop.mcmc$mcmc[["theta (diff)"]]) > i) )
bprop.vs.sek
par(oma=c(2,1,1,1), "cex.axis"=1, bty="l")
plot(sek, bprop.vs.sek, type="l", bty="n", col="darkred", pre.plot=grid(),
xlab="credMass",
ylab=eval(substitute(expression(paste("p(",theta[diff],")",sep="")))),
main="")
mtext(eval(substitute(expression(paste(theta[diff]," > credMass",sep="")))), outer=TRUE, line=-2, cex=1.5, side=3)
# for book
# data
pres.2x2
# analysis for Bush vs. Kerry
pres.2x2.bprop.mcmc <- bprop.mcmc(pres.2x2, analyze="cols")
pres.post.betavalues <- pres.2x2.bprop.mcmc$a1b1a2b2
names(pres.post.betavalues) <- c("a1","b1","a2","b2")
pres.post.betavalues
### MCMC brute force variante 2
# library(HDInterval)
# add chains
nchains <- 3
n.mcmc <- 1e+4
# library(coda)
# library(BEST)
theta.diff.mcmc <- gr1.mcmc <- gr2.mcmc <- vector(mode="list", length=nchains)
# calculate x chains of MCMC for group1 and group2
set.seed(78824)
#a1b1a2b2 <- pres.2x2.bprop.mcmc[["a1b1a2b2"]]
a1b1a2b2 <- pres.post.betavalues
# posteriors
gr1.mcmc <- lapply(gr1.mcmc, function(x) x <- rbeta(n.mcmc, shape1=a1b1a2b2[1], shape2=a1b1a2b2[2]))
gr2.mcmc <- lapply(gr2.mcmc, function(x) x <- rbeta(n.mcmc, shape1=a1b1a2b2[3], shape2=a1b1a2b2[4]))
# calculate theta.diff = theta1 - theta2
for(i in 1:nchains)
{
theta.diff.mcmc[[i]] <- gr1.mcmc[[i]] - gr2.mcmc[[i]]
}
# calculate summary statistics
sums <- function(x) c(summary(x), sd=sd(x), var=var(x))
rnams <- c("Min.","1st Qu.","Median","Mean","3rd Qu.","Max.","sd","var")
megalist <- list(gr1.mcmc, gr2.mcmc, theta.diff.mcmc)
mega.res <- sapply(megalist, function(x) sapply(x, sums))
# calculate hdis
hdis.l <- sapply(megalist, function(x) sapply(x, hdi, credMass=credMass))
res <- rbind(mega.res, hdis.l)
statistic <- c(rep(rnams,nchains),
rep(paste(c("HDI lower ","HDI upper "),"(",round(credMass*100),"%)",sep=""),dim(hdis.l)[1]/2)
)
mcmcchain <- c(rep(c(1:nchains),each=dim(mega.res)[1]/nchains),
rep(c(1:nchains),each=2)
)
res <- data.frame(statistic, res, "MCMC chain"=mcmcchain, check.names=FALSE)
lnam <- c("theta 1","theta 2","theta (diff)")
colnames(res)[2:4] <- lnam
res <- res[order(mcmcchain),]
rownames(res) <- NULL
abc <- lapply(list(1,11,21), function(x) x+0:9)
abcm <- do.call("rbind",abc)
dim(abcm) <- c(30,1)
abcm
res.sorted <- res[abcm,]
res
# sorted after MCMC chains
res.sorted
megalist.mcmc.list <- lapply(megalist, function(x) as.mcmc.list(lapply(x, as.mcmc)))
lnam
# plot
par(oma=c(2,1,4,1), "cex.axis"=1, bty="l", mfrow=c(3,2))
sapply(seq_along(lnam), function(x)
{
coda:::traceplot(megalist.mcmc.list[[x]], smooth=TRUE, main=lnam[x])
coda:::densplot(megalist.mcmc.list[[x]], col="red", main=lnam[x])
rug(jitter(unlist(megalist.mcmc.list[[x]]), amount = 0.05), ticksize=0.04, side=1, col="darkorange")
return(invisible)
}
)
mtext("MCMC diagnostics", outer=TRUE, line=0.5, cex=1.5, side=3)
# test some hypotheses
# Probability theta1 > theta2 and theta1 < theta2
# over all chains
critv <- 0
# remember: diff = theta1 - theta2
# diff > 0 -> theta1 > theta2
diffGREATERzero <- sapply(theta.diff.mcmc, function(x) mean(x > critv))
# diff < 0 -> theta1 < theta2
diffSMALLERzero <- sapply(theta.diff.mcmc, function(x) mean(x < critv))
# output of hypotheses over all MCMC-chains
diffGREATERzero
diffSMALLERzero
# posterior odds
diffGREATERzero / (1-diffGREATERzero)
# posterior odds
diffSMALLERzero / (1-diffSMALLERzero)
# crit 0.1
# over all chains
critv <- 0.1
sapply(theta.diff.mcmc, function(x) mean(x > critv))
# ask about absolute difference without any direction
sapply(theta.diff.mcmc, function(x) mean(abs(x) > critv))
#sapply(theta.diff.mcmc, function(x) mean(abs(x) < critv))
# plot just first mcmc
dens <- density(theta.diff.mcmc[[1]])
par(oma=c(2,1,1,1), "cex.axis"=1, bty="l", mfrow=(c(1,2)))
hist(theta.diff.mcmc[[1]], prob=TRUE, xlab=eval(substitute(expression(paste(theta[diff],sep="")))),
ylab="density", main="", col="steelblue", border="white", breaks="Sturges", cex.lab=1.2, pre.plot=grid())
lines(dens, col="green", lwd=2)
mtext("Bayesian proportion test (brute force)", outer=TRUE, line=-2, cex=1.5, side=3)
# add HDI line
credMass <- 0.87
hdis <- hdi(dens, credMass=credMass)
hdis
xrange <- dens$x[dens$x < hdis["upper"] & dens$x > hdis["lower"]]
#yrange <- dens$y[dens$x < hdis["upper"] & dens$x > hdis["lower"]]
#lines(x=c(xrange[1],xrange[length(xrange)]), y=c(yrange[1],yrange[length(yrange)]), col="orange", lwd=5)
yheight <- attr(hdis,"height")
lines(x=c(xrange[1],xrange[length(xrange)]), y=c(yheight,yheight), col="orange", lwd=6)
legend("left", legend=c(paste("HDI [",credMass*100,"%]",sep="")), lty=1, lwd=2, xpd=TRUE, horiz=FALSE, col="orange", bty="n", cex=.9)
# plot just first mcmc
thetadiff1.abs <- abs(theta.diff.mcmc[[1]])
dens <- density(thetadiff1.abs)
# remove values < 0 BUT y before x (!)
dens$y <- dens$y[dens$x > 0]
dens$x <- dens$x[dens$x > 0]
str(dens)
#par(oma=c(2,1,1,1), "cex.axis"=1, bty="l")
hist(thetadiff1.abs, prob=TRUE, xlab=eval(substitute(expression(paste("abs(",theta[diff],")",sep="")))),
ylab="density", main="", col="steelblue", border="white", breaks="Sturges", cex.lab=1.2, pre.plot=grid())
lines(dens, col="green", lwd=2)
#mtext("Bayesian proportion test (brute force)", outer=TRUE, line=-2, cex=1.5, side=3)
# add HDI line
credMass <- 0.87
hdis <- hdi(dens, credMass=credMass)
hdis
xrange <- dens$x[dens$x < hdis["upper"] & dens$x > hdis["lower"]]
yheight <- attr(hdis,"height")
lines(x=c(0,xrange[length(xrange)]), y=c(yheight,yheight), col="orange", lwd=5)
legend("right", legend=c(paste("HDI [",credMass*100,"%]",sep="")), lty=1, lwd=2, xpd=TRUE, horiz=FALSE, col="orange", bty="n", cex=.9)
### not run
# use first chain
prob.gr1.vs.gr2.diff <- gr1.mcmc[[1]] - gr2.mcmc[[1]]
mean(prob.gr1.vs.gr2.diff > 0)
# Probability, that theta_1 < theta_2
prob.gr1.vs.gr2 <- mean(gr1.mcmc[[1]] > gr2.mcmc[[1]])
prob.gr1.vs.gr2
1 - prob.gr1.vs.gr2
# prob theta_1 - theta_2 > 0.1
mean(prob.gr1.vs.gr2.diff > 0.1)
# Odds ratio in favor of theta_1 > theta_2
prob.gr1.vs.gr2 / (1-prob.gr1.vs.gr2)
# Odds ratio in favor of theta_1 < theta_2
(1-prob.gr1.vs.gr2) / prob.gr1.vs.gr2
# absolute difference (thetas) below diff.crit = 1-credMass
credMass <- 0.87
diff.crit <- 1-credMass
mean(abs(gr1.mcmc[[1]] - gr2.mcmc[[1]]) < diff.crit)
mean((gr1.mcmc[[1]] - gr2.mcmc[[1]]) < diff.crit)
# take only one chain
credMass <- 0.99
diff.crit <- 1-credMass
n.mcmc <- 1e5
# extract posterior a's and b's for B(a,b)
a1b1a2b2 <- pres.2x2.bprop.mcmc[["a1b1a2b2"]]
a1b1a2b2
seed <- 78824
set.seed(seed)
g1 <- rbeta(n.mcmc, shape1=a1b1a2b2[1], shape2=a1b1a2b2[2])
g2 <- rbeta(n.mcmc, shape1=a1b1a2b2[3], shape2=a1b1a2b2[4])
theta.diff <- g1 - g2
# plot
dens <- density(theta.diff)
par(oma=c(2,1,1,1), "cex.axis"=1, bty="l")
hist(theta.diff, prob=TRUE, xlab=eval(substitute(expression(paste(theta[diff],sep="")))),
ylab="density", main="", col="steelblue", border="white", breaks="Sturges", cex.lab=1.2, pre.plot=grid())
lines(dens, col="green", lwd=2)
mtext("Bayesian proportion test (brute force)", outer=TRUE, line=-2, cex=1.5, side=3)
# add HDI line
credMass <- 0.87
hdis <- hdi(dens, credMass=credMass)
hdis
xrange <- dens$x[dens$x < hdis["upper"] & dens$x > hdis["lower"]]
yrange <- dens$y[dens$x < hdis["upper"] & dens$x > hdis["lower"]]
lines(x=c(xrange[1],xrange[length(xrange)]), y=c(yrange[1],yrange[length(yrange)]), col="orange", lwd=5)
legend("right", legend=c(paste("HDI [",credMass*100,"%]",sep="")), lty=1, lwd=2, xpd=TRUE, horiz=FALSE, col="orange", bty="n", cex=.9)
### END OF not run
### Numerical integration OR grid approximation
a1 <- a1b1a2b2[1]
b1 <- a1b1a2b2[2]
a2 <- a1b1a2b2[3]
b2 <- a1b1a2b2[4]
int.width <- 1e-3
start.sek <- 0
end.sek <- 1
nsim <- 1e+5
sek <- seq(start.sek, end.sek, int.width)
if(nsim > 5000) nsamp <- 5000 else nsamp <- nsim
set.seed(33345)
mcmc.1 <- rbeta(nsim, shape1=a1, shape2=b1)
mcmc.2 <- rbeta(nsim, shape1=a2, shape2=b2)
mcmc.diff <- mcmc.1 - mcmc.2
# mean theta difference (posterior)
mean(mcmc.diff)
# posterior probs and odds ratios
mean(abs(mcmc.diff) > 0.1) # how much difference > 10%
mean(mcmc.diff > 0) # how much difference > 0%
# =
mean(mcmc.1 > mcmc.2) # theta1 > theta2
mean(mcmc.diff < 0) # how much difference < 0%
# =
1-mean(mcmc.1 > mcmc.2) # theta1 < theta2
mean(mcmc.diff > 0)/mean(mcmc.diff < 0)
mean(mcmc.diff < 0)/mean(mcmc.diff > 0)
# rough plot
# - densities against each other
# - densities next to each other + diff
# - scatterplot
# - mcmc chains for each other + diff
par(oma=c(2,1,4,1), "cex.axis"=1, bty="l", mfrow=c(2,3))
dbetas1 <- dbeta(sek, shape1=a1, shape2=b1)
dbetas2 <- dbeta(sek, shape1=a2, shape2=b2)
theta1.nam <- eval(substitute(expression(paste(theta[1],sep=""))))
theta2.nam <- eval(substitute(expression(paste(theta[2],sep=""))))
main.nam <- eval(substitute(expression(paste(theta[1]," vs. ",theta[2],sep=""))))
plot(dbetas1, dbetas2, xlab=theta1.nam, ylab=theta2.nam, pre.plot=grid(),
main=main.nam, col="violetred3", type="l", bty="n", lwd=2)
abline(a=0, b=1, col="blue", lty=2, lwd=3)
plot(sek,dbetas1, xlim=c(-0.4, 0.6), main="Histograms", ylab="density", xlab="p",
type="l",col="violetred3", bty="n", pre.plot=grid(),, lwd=2)
points(sek, dbetas2, col="steelblue", type="l", lwd=2)
lines(density(mcmc.diff), col="yellowgreen", type="l", lwd=2)
legend("topleft", bty="n", legend=c(theta1.nam, theta2.nam, main.nam), col=c("violetred3","steelblue","yellowgreen"), lwd=3)
main.nam <- eval(substitute(expression(paste("Scatterplot ", theta[1]," vs. ",theta[2],sep=""))))
plot(mcmc.1, mcmc.2, col="black", pch=21, bg="yellowgreen", cex=0.8, main=main.nam, bty="n",
xlab=theta1.nam, ylab=theta2.nam, pre.plot=grid(),)
abline(a=0, b=1, col="orange", lty=2, lwd=3)
mcmc1.nam <- eval(substitute(expression(paste("MCMC chain ",theta[1],sep=""))))
plot(mcmcsub1 <- sample(mcmc.1,nsamp), main=mcmc1.nam, col="skyblue", type="l", bty="n",
xlab="", ylab=theta1.nam, pre.plot=grid())
lines(lowess(mcmcsub1),col="salmon", lwd=3, lty=2)
mcmc2.nam <- eval(substitute(expression(paste("MCMC chain ",theta[2],sep=""))))
plot(mcmcsub2 <- sample(mcmc.2,nsamp), main=mcmc2.nam, col="violetred3", type="l", bty="n",
xlab="", ylab=theta2.nam, pre.plot=grid())
lines(lowess(mcmcsub2),col="blue", lwd=3, lty=2)
mtext("MCMC diagnostics", outer=TRUE, line=0.5, cex=1.5, side=3)
### Brute force numerical integration / grid approximation
# content of the function
bayes.prop.grid
# outer product
1:10 %o% 1:10
outer(1:10,1:10,"*")
# remember values
pres.2x2
# posterior beta values
a1
b1
a2
b2
# calculate based on grid approximation
prob.a1b1.vs.a2b2 <- bayes.prop.grid(a1=a1, b1=b1, a2=a2, b2=b2, int.width=1e-3)
# prob theta1 > theta2
sum.prob <- sum(prob.a1b1.vs.a2b2)
sum.prob
# prob theta1 < theta2
1 - sum.prob
# odds ratios
sum.prob / (1-sum.prob)
(1-sum.prob) / sum.prob
# analysis of presidents Bush vs. Kerry over "I" vs. "we/nation"
pres.2x2
pres.post.betavalues
prob.a1b1.vs.a2b2 <- bayes.prop.grid(a1=pres.post.betavalues["a1"],
b1=pres.post.betavalues["b1"],
a2=pres.post.betavalues["a2"],
b2=pres.post.betavalues["b2"],
int.width=1e-3)
# test some hypotheses
# prob theta1 > theta2
sum.prob <- sum(prob.a1b1.vs.a2b2)
sum.prob
# prob theta1 < theta2
1 - sum.prob
# odds ratios
sum.prob / (1-sum.prob)
(1-sum.prob) / sum.prob
### Exact tests
a1 <- pres.post.betavalues["a1"]
b1 <- pres.post.betavalues["b1"]
a2 <- pres.post.betavalues["a2"]
b2 <- pres.post.betavalues["b2"]
pres.2x2
a1
b1
a2
b2
c(a1,b1,a2,b2)
# important: if loga=TRUE
# result is a BROB object
# Pr(GR2 > GR1)
h.res <- h(a1=a1, b1=b1, a2=a2, b2=b2)
h.res
# log version
h.res.log <- h(a1=a1, b1=b1, a2=a2, b2=b2, loga=TRUE)
str(h.res.log)
h.res.log
as.numeric(h.res.log)
# Probability(GR2 > GR1)
h.res
# Pr(GR2 < GR1)
1 - h.res
# Ratio in favor of GR2 > GR1
h.res / (1-h.res)
# GR2 < GR1
1/( h.res / (1-h.res) )
# Odds ratio in favor of GR2 > GR1
((h.res)/(1-h.res)) / ((1-h.res)/h.res)
# GR2 < GR1
((1-h.res)/h.res) / ((h.res)/(1-h.res))
# difference between brute force numerical integration and h()
h.res.inv <- 1-h.res
# difference
sum.prob - h.res.inv
# equal
1 - abs(sum.prob - h.res.inv)
# ratio
sum.prob / h.res.inv
# difference between BayesianFirstAid MCMC and h()
diff.crit <- 0
thetas <- as.data.frame(pres.2x2.bprop)
pROPE.equal <- mean(thetas[,"theta1"] - thetas[,"theta2"] > diff.crit)
pROPE.equal
# difference
pROPE.equal - h.res.inv
# equal
1 - abs(pROPE.equal - h.res.inv)
# ratio
pROPE.equal / h.res.inv
###### decision rule Bayesian A/B Testing after Chris Stucchio
#### loss function/ decision rule by Chris Stucchio
pres <- t(matrix(c(16,101,91, 32,131,88), nrow=2, byrow=TRUE,dimnames=list(c("Bush","Kerry"),c("nation","I","we"))))
pres.2x2 <- rbind(pres["I",],pres["nation",]+pres["we",])
rownames(pres.2x2) <- c("I","we/nation")
pres.2x2
pres.1x4 <- as.vector(pres.2x2)
names(pres.1x4) <- c("a1","b1","a2","b2")
pres.1x4
a1 <- pres.1x4["a1"]
b1 <- pres.1x4["b1"]
a2 <- pres.1x4["a2"]
b2 <- pres.1x4["b2"]
a1
b1
a2
b2
# [theta2 - theta1] < crit (Test)
credMass <- 0.99
res <- bayes.prop.loss(a1=a1, b1=b1, a2=a2, b2=b2, crit=1-credMass, loga=FALSE, pr.out=FALSE)
res
#library(Brobdingnag)
bayes.prop.loss(a1=a1, b1=b1, a2=a2, b2=b2, crit=1-credMass, loga=TRUE, pr.out=FALSE)
# change criteria
credMass <- 0.1
res <- bayes.prop.loss(a1=a1, b1=b1, a2=a2, b2=b2, crit=1-credMass, loga=FALSE)
credMass <- 0.22
res <- bayes.prop.loss(a1=a1, b1=b1, a2=a2, b2=b2, crit=1-credMass, loga=FALSE)
# table TRUE vs. FALSE
loss.v <- res[,4]
sek <- seq(0,1,0.001)
tab <- table(loss.v < sek)
tab/sum(tab)
# when does it change from FALSE to TRUE
tf.IDs <- which(( lossvBELOWsek <- loss.v < sek) == TRUE)[1]
data.frame(loss.v,sek, "loss.v < sek"=lossvBELOWsek, check.names=FALSE)[(tf.IDs[1]-1):tf.IDs[1],]
tab.tf <- data.frame(loss.v,sek,loss.v<sek, check.names=FALSE)
tf.IDs <- which(tab.tf[,3] == TRUE, arr.ind=TRUE)
tab.tf[(tf.IDs[1]-1):tf.IDs[1],]
############## NOT RUN
bayes.prop.grid2 <- function(a1=a1, b1=b1, a2=a2, b2=b2, int.width=1e-3, start.sek=0, end.sek=1, CRIT=0)
{
sek <- seq(start.sek, end.sek, int.width)
# important part: (x > y)
grid.res <- outer(sek, sek, function(x, y) (y-x<CRIT) * dbeta(x, a1, b1) * int.width * dbeta(y, a2, b2) * int.width)
# (y - x <0.1)
# grid.res <- outer(sek, sek, function(x, y) (y - x <0.1) * dbeta(x, a1, b1) * int.width * dbeta(y, a2, b2) * int.width)
return(grid.res)
}
p1 <- sum(bayes.prop.grid2(a1,b2,a2,b2, CRIT=mean(bf.diff)))
p2 <- 1-p1
p1
p2
# brute force
set.seed(192934)
bf.N <- 10e7
bf.res1 <- rbeta(n=bf.N, shape1=a1, shape2=b1)
bf.res2 <- rbeta(n=bf.N, shape1=a2, shape2=b2)
bf.diff <- bf.res2 - bf.res1
mean(bf.diff)
############## END OF NOT RUN
### more exact test
### FOLLOWING FUNCTIONS ARE REPROGRAMMED BUT IN PRINCIPLE TAKEN FROM
# original paper by Nadajarah & Kotz (2007)
# corrections by Chen & Luo (2011)
# original R code by Sverdlov, Ryeznik & Wu (2015)
# pdf of theta ratio = theta_2 / theta_1
# see also Pham-Gia (2000)
# not run
# similar functions in R package 'tolerance'
# qdiffprop
#
# and appell function
# comparison
# library(tolerance)
#
# F1(a = 3, b = 4, b.prime = 5, c = 13, x = 0.2, y = 0.4)
# [1] 2.110471
# versus
# appellf1(a = 3, b1 = 4, b2 = 5, c = 13, x = 0.2, y = 0.4)
# [1] 2.110471+0i
#
# hyp2f1(a = 3, b = 4, c = 13, z = 0.5)
# not run - infos
# original paper versions
# CDF = p2beta
# PDF = d2beta
# Quantile = q2beta
# CI = ci2beta
# a1,b1,a2,b2 are a and b values of a posterior beta distribution (see sum symbol below from original paper)
# original function from paper
source("bayesian2beta.r")
# comparison with original paper versions:
d2beta("DIFF", x=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
#[1] 1.402381
pdf.theta.diff(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=FALSE)
#[1] 1.402381
exp( pdf.theta.diff(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE) )
pdfthetadiff.1 <- pdf.theta.diff(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE)
pdfthetadiff.1
exp(pdfthetadiff.1)
pdf.theta.diff(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=FALSE)
#sL=1/10000,sH=1-1/10000)
pdfthetadiff.2 <- pdf.theta.diff(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE)
pdfthetadiff.2
pdf.theta.diff.MULT(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE, sL=1/10000,sH=1-1/10000)
# sL/sH +/- 1/10000
#[1] 0.3515413
exp(pdfthetadiff.2)
#[1] 1.421256
pdf.theta.diff.MULT(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE, sL=0,sH=1-1/9175)
pdfthetadiff.2 <- pdf.theta.diff(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE)
pdfthetadiff.2
# sH- 1/9175
#[1] 0.3381657
exp(pdfthetadiff.2)
#1.402373
1.402373/1.402381
#> 1.402373/1.402381
#[1] 0.9999943
1-1.402373/1.402381
#> 1-1.402373/1.402381
#[1] 5.704584e-06
d2beta("RR", x=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
pdf.theta.ratio(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=FALSE)
d2beta("OR", x=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
pdf.theta.OR(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=FALSE)
exp(pdf.theta.OR(theta=0.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, loga=TRUE))
# prob( p2-p1 < crit )
p2beta ("DIFF", "DIRECT", x = 0, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
cdf.theta.diff(theta=0, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
# prob( p2/p1 < crit )
p2beta(relation='RR', approach='DIRECT', x = 1.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
cdf.theta.ratio(theta=1.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
# prob( (p2/(1-p2)) / (p1/1-p1)) < crit )
p2beta(relation='OR', approach='DIRECT', x = 1.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
cdf.theta.OR(theta=1.5, a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2)
# CI % p2-p1 (Nelder-Mead)
# original paper version:
ci2beta(relation='DIFF', method='neldermead', a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, alpha=.05, left0=-.2, right0=.8)
theta.diff.hdi(a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, alpha=.05, le=-.2, re=.8)
# CI % p2-p1 -> quantile function / inverse CDF
# original paper version:
ci2beta(relation='DIFF', method='inv.cdf', a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, alpha=.05, left0=0, right0=0)
# does work only for p2-p1
CI.DIFF.inv.cdf(a1 = 1/3+0, b1 = 1/3+5-0, a2 = 1/3+2, b2 = 1/3+5-2, alph=0.05, tol=1e-5, methode="diff")
# CORRECT! d2beta = correct for DIFF, RR, and OR
# correct
# p2beta(relation='DIFF', approach='DIRECT', x=0.5, a1,b1,a2,b2)
# cdf.theta.diff(theta=0.5, a1,b1,a2,b2)
# end of not run
### ONLY WINDOWS R v.3
### dynamically load old R function BECAUSE not available in recent R version
dyn.load("appell/libs/i386/appell.dll")
# replace f21_sub by „f21_sub“ (with quotation marks)
results <- .Fortran("f21_sub", a = a, b = b, c = c, z = z, hyp2f1 = algorithm, val = val)
# replace f1 by „f1“ (with quotation marks)
results <- .Fortran("f1", a = a, b1 = b1, b2 = b2, c = c, x = x,
y = y, algoflag = algoflag, userflag = userflag, debug = debug,
val = val, hyp2f1 = hyp2f1)
### END OF dynamically load old R function
################ BOOK
source("ptall_generalfuncs_brob-integral.r")
# values from paper
a1 <- 1/3+7
b1 <- 1/3+12-7
a2 <- 1/3+6
b2 <- 1/3+18-6
theta.res <- prop.theta.sek(a1=a1, b1=b1, a2=a2, b2=b2,
loga=c(T,T,T),
parallel=TRUE,
numer=TRUE,
BROB=c(T,T,T),
xlim.diff=c(-1,1,-1,1), l.diff=100,#xlim.diff=c(-.999,.999, -.999,.999), l.diff=100,
xlim.RR=c(0,10, 0,2), l.RR=100,
xlim.OR=c(0,100, 0,2.5), l.OR=100,
theta.crit=c(0.5,1,1)
)
# brute force
set.seed(192934)
bf.N <- 10e6
bf.res1 <- rbeta(n=bf.N, shape1=a1, shape2=b1)
bf.res2 <- rbeta(n=bf.N, shape1=a2, shape2=b2)
bf.diff <- bf.res2 - bf.res1
BEST:::plotPost(bf.diff, credMass=0.87, ROPE=c(-0.5,0.5), xlab="theta difference", showMode=TRUE, col="skyblue", border="white", compVal=0.5)
# MAP exact
theta.res.exp <- theta.res$post$differ$pdf
theta.res.exp[,2] <- exp(theta.res.exp[,2])
MAP.xct <- theta.res.exp[(theta.res.exp[,2] == max(theta.res.exp[,2])),]
# MAP brute force
MAP.bf <- mean(bf.diff)
# output and comparison
MAP.xct
MAP.bf
(MAP.xct[,1]-MAP.bf)/MAP.xct[,1]
# plot
bf.diff.dens <- density(bf.diff)
par(mfrow=c(1,2))
# non-log
plot(theta.res.exp[,1], theta.res.exp[,2], type="l", col="darkred", bty="n", pre.plot=grid(), xlab="theta diff", ylab="pdf.diff")
abline(v=MAP.xct[,1], col="darkred")
lines(bf.diff.dens$x, bf.diff.dens$y, col="blue")
abline(v=MAP.bf, lty=3, col="blue")
# log
theta.res.log <- theta.res$post$differ$pdf
plot(theta.res.log[,1], theta.res.log[,2], type="l", col="darkred", bty="n", pre.plot=grid(), xlab="theta.diff", ylab="log(pdf.diff)")
abline(v=MAP.xct[,1], col="darkred")
lines(bf.diff.dens$x, log(bf.diff.dens$y), col="blue", lty=3, lwd=2)
abline(v=MAP.bf, lty=3, col="blue")
mtext(expression(paste("Bayesian Analysis of Difference of Proportions ",theta[2]," - ",theta[1]," | Exact vs. Brute Force",sep="")),
3, line=-3, cex=1.6, outer=TRUE)
# presidential data
# values see above
pres.2x2
# Bush vs. Kerry
pres.post.betavalues
a1 <- pres.post.betavalues["a1"]
b1 <- pres.post.betavalues["b1"]
a2 <- pres.post.betavalues["a2"]
b2 <- pres.post.betavalues["b2"]
a1
b1
a2
b2
rm(theta.res)
theta.res <- prop.theta.sek(a1=a1, b1=b1, a2=a2, b2=b2,
loga=c(T,T,T),
parallel=TRUE,
numer=TRUE,
BROB=c(T,T,T),
xlim.diff=c(-1,1,-1,1), l.diff=100,#xlim.diff=c(-.999,.999, -.999,.999), l.diff=100,
xlim.RR=c(0,10, 0,2), l.RR=100,
xlim.OR=c(0,100, 0,2.5), l.OR=100,
theta.crit=c(0.5,1,1)
)
# only plot result
prop.theta.sek.plot(theta.res)
# brute force
set.seed(192934)
bf.N <- 10e6
bf.res1 <- rbeta(n=bf.N, shape1=a1, shape2=b1)
bf.res2 <- rbeta(n=bf.N, shape1=a2, shape2=b2)
bf.diff <- bf.res2 - bf.res1
BEST:::plotPost(bf.diff, credMass=0.87, ROPE=c(-0.25,0.25), xlab="theta difference", showMode=TRUE, col="skyblue", border="white", compVal=0.2)
# MAP exact
theta.res.exp <- theta.res$post$differ$pdf
theta.res.exp[,2] <- exp(theta.res.exp[,2])
MAP.xct <- theta.res.exp[(theta.res.exp[,2] == max(theta.res.exp[,2])),]
# MAP brute force
MAP.bf <- mean(bf.diff)
# output and comparison
MAP.xct
MAP.bf
(MAP.xct[,1]-MAP.bf)/MAP.xct[,1]
# plot
bf.diff.dens <- density(bf.diff)
par(mfrow=c(1,2))
# non-log
plot(theta.res.exp[,1], theta.res.exp[,2], type="l", col="darkred", bty="n", pre.plot=grid(), xlab="theta diff", ylab="pdf.diff")
abline(v=MAP.xct[,1], col="darkred")
lines(bf.diff.dens$x, bf.diff.dens$y, col="blue")
abline(v=MAP.bf, lty=3, col="blue")
# log
theta.res.log <- theta.res$post$differ$pdf
plot(theta.res.log[,1], theta.res.log[,2], type="l", col="darkred", bty="n", pre.plot=grid(), xlab="theta.diff", ylab="log(pdf.diff)")
abline(v=MAP.xct[,1], col="darkred")
lines(bf.diff.dens$x, log(bf.diff.dens$y), col="blue", lty=3, lwd=2)
abline(v=MAP.bf, lty=3, col="blue")
mtext(expression(paste("Bayesian Analysis of Difference of Proportions ",theta[2]," - ",theta[1]," | Exact vs. Brute Force",sep="")),
3, line=-3, cex=1.6, outer=TRUE)