-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGLM_2_Binomial_exercise.html
953 lines (851 loc) · 34.8 KB
/
GLM_2_Binomial_exercise.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Day 2: Binomial GLMs</title>
<script src="site_libs/header-attrs-2.29/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/flatly.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<script src="site_libs/navigation-1.1/codefolding.js"></script>
<link href="site_libs/font-awesome-6.5.2/css/all.min.css" rel="stylesheet" />
<link href="site_libs/font-awesome-6.5.2/css/v4-shims.min.css" rel="stylesheet" />
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
details > summary > p:only-child {
display: inline;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark the anchor link active (and if it's in a dropdown, also mark that active)
var dropdown = menuAnchor.closest('li.dropdown');
if (window.bootstrap) { // Bootstrap 4+
menuAnchor.addClass('active');
dropdown.find('> .dropdown-toggle').addClass('active');
} else { // Bootstrap 3
menuAnchor.parent().addClass('active');
dropdown.addClass('active');
}
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before, .tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "\e259";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "\e258";
font-family: 'Glyphicons Halflings';
border: none;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
</style>
</head>
<body>
<div class="container-fluid main-container">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-bs-toggle="collapse" data-target="#navbar" data-bs-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">PGR-GLM</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">
<span class="fa fa-home"></span>
Home
</a>
</li>
<li>
<a href="setup.html">
<span class="fa fa-cog"></span>
Setup
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fa fa-book"></span>
R Book
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="https://intro2r.com">
<span class="fa fa-firefox"></span>
Web book
</a>
</li>
<li class="divider"></li>
<li>
<a href="https://github.com/alexd106/Rbook/raw/master/docs/Rbook.pdf">
<span class="fa fa-file-pdf"></span>
PDF book
</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fa fa-book"></span>
Exercises
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="exercises.html">
<span class="fa fa-book"></span>
Exercises
</a>
</li>
<li class="divider"></li>
<li>
<a href="exercise_solutions.html">
<span class="fa fa-book"></span>
Exercise Solutions
</a>
</li>
</ul>
</li>
<li>
<a href="data.html">
<span class="fa fa-download"></span>
Data
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<span class="fa fa-question-circle"></span>
Info
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="syllabus.html">
<span class="fa fa-graduation-cap"></span>
Syllabus
</a>
</li>
<li>
<a href="People.html">
<span class="fa fa-user-friends"></span>
People
</a>
</li>
<li class="divider"></li>
<li>
<a href="resources.html">
<span class="fa fa-book"></span>
Resources
</a>
</li>
<li class="dropdown-header">Feedback</li>
<li>
<a href="People.html">
<span class="fa fa-envelope fa-lg"></span>
Contact
</a>
</li>
<li class="divider"></li>
<li>
<a href="https://github.com/alexd106/PGR-GLM">
<span class="fa fa-github fa-lg"></span>
Source code
</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<div class="btn-group pull-right float-right">
<button type="button" class="btn btn-default btn-xs btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span>Code</span> <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right" style="min-width: 50px;">
<li><a id="rmd-show-all-code" href="#">Show All Code</a></li>
<li><a id="rmd-hide-all-code" href="#">Hide All Code</a></li>
</ul>
</div>
<h1 class="title toc-ignore">Day 2: Binomial GLMs</h1>
</div>
<p> </p>
<div
id="binomial-glm---understanding-multi-drug-resistance-staphylococcus-epidermidis"
class="section level1">
<h1>Binomial GLM - understanding Multi-drug Resistance
<em>Staphylococcus epidermidis</em></h1>
<p> </p>
<p>For the GLM exercises, we’ll use the workflow we suggested in the
first GLM overview lecture as a template, specifically:</p>
<ol style="list-style-type: decimal">
<li><p>Know your research question!</p></li>
<li><p>Think about your response variable (stochastic).</p></li>
<li><p>Think about the process behind the data (deterministic).</p></li>
<li><p>Understand the data that you’ve collected (plot it!)</p></li>
<li><p>Combine into a model that can answer your question.</p></li>
<li><p>Fit the model.</p></li>
<li><p>Check your assumption(s).</p></li>
<li><p>Answer your question.</p></li>
</ol>
<p><br />
</p>
<div id="know-your-research-question" class="section level3">
<h3>1. Know your research question!</h3>
<p><br />
</p>
<p>The researchers who collected this data wanted to understand how a
policy decision, as well as other covariates, were associated with the
prevalence of Multi-drug Resistant <em>Staphylococcus epidermidis</em>
(MRSE, a relative of MRSA) amongst patients in different Intensive Care
Unit (ICU) wards. Data was collected from all 210 ICU wards in the UK
and included the total number of patients in each ICU ward
(<code>total_patients</code>) as well as how many of them were MRSE
positive (<code>mrse</code>).</p>
<p>Specifically, the researchers wanted to understand how three
explanatory variables were associated with the prevalence of MRSE: 1)
the number of staff working in an ICU (<code>staff</code>); 2) current
capacity of the ward (<code>capacity</code>, expressed as a proportion
of beds currently occupied); and 3) whether or not the respective
hospital board had implemented a policy concerning the reduced use of
Chlorhexidine bathing (<code>policy</code>). Chlorhexidine usage was of
primary interest, as the researchers believed this bathing was, in part,
responsible for increasing prevalence of MRSE due to overuse leading to
anti-microbial resistance (since chlorhexidine is an anti-microbial
agent). Additionally, the researchers felt it was likely that the
effectiveness of the policy depended on the number of ICU staff to
implement it (so would require an interaction between <code>staff</code>
and <code>policy</code>). In total, data was collected from 210 ICU
wards (<span class="math inline">\(n = 210\)</span>), where each
observation is from a single ICU ward in a hospital.</p>
<p>As concisely as possible, write down the research question that can
be answered with our analysis.</p>
<p><br />
</p>
</div>
<div id="think-about-your-response-variable-the-stochastic-element."
class="section level3">
<h3>2. Think about your response variable (the stochastic element).</h3>
<p><br />
</p>
<p>From the information provided in the brief above, we are already able
to determine a suitable distribution to use when fitting the model (as
before, ignore that today’s class is called <span
class="math inline">\(Binomial\)</span> GLMs). Here, we’ve been told two
pieces of information that help us determine that a <span
class="math inline">\(Binomial\)</span> is a sensible distribution:</p>
<ol style="list-style-type: decimal">
<li><p>We have a count of “successes” (here, “success” is paradoxically
a patient who is infected with MRSE)</p></li>
<li><p>We have the total number of patients present on the
ward.</p></li>
</ol>
<p>So, we know the minimum count of “successes” (i.e. infected patients)
will be zero but we also know we have an upper bound; We can’t have more
patients infected with MRSE than we have patients on the ward. This is
the type of data that a <span class="math inline">\(Binomial\)</span>
distribution excels in accounting for. Our stochastic element of the
model would therefore be:</p>
<p><span class="math inline">\(y_i \sim Binomial(p_i, k_i)\)</span></p>
<p>Where <span class="math inline">\(y\)</span> is the number of MRSE
positive patients in ICU ward <span class="math inline">\(i\)</span>,
generated according to a <span class="math inline">\(Binomial\)</span>
distribution, with probability <span class="math inline">\(p\)</span>
and number of trials <span class="math inline">\(k\)</span>.</p>
<p><br />
</p>
</div>
<div
id="think-about-the-process-behind-the-data-the-deterministic-element."
class="section level3">
<h3>3. Think about the process behind the data (the deterministic
element).</h3>
<p><br />
</p>
<p>As with yesterday’s practical, spending a couple of minutes thinking
about the process that goes into why some wards may have higher
prevalence of MRSE compared to others is mind boggling. We could spend
years trying to map out that complexity, and indeed that’s what lots of
researchers try to do. Here, the researchers have presented us with a
suitably focused set of covariates and a razor sharp research question,
meaning we can skip the “existential crises” phase and jump straight
into the modelling. While skipping this is useful for teaching purposes,
it really is worth emphasising, again, that this is where the majority
of statistical analysis happens. Thinking very carefully about the
process behind how the data is “generated” (called the <em>Data
Generating Process</em>), and how we want to represent this in our
models is really at the core of modelling.</p>
<p>For our purposes, the deterministic part we’re interested in is the
effect of number of staff, current capacity, policy implementation, and
an interaction between number of staff and policy implementation. With
this in mind, the deterministic element of our model will be something
like the equation shown below. Try to fill in the gaps:</p>
<p><span class="math inline">\(logit(p_i) = \beta_0 + \text{___} \times
Capacity_i + \beta_2 \times \text{___}_i + \beta_3 \times Staff_i +
\text{___} \times Staff_i \times Nopolicy_i\)</span></p>
<p> </p>
</div>
<div id="understand-the-data-that-youve-collected-plot-it"
class="section level3">
<h3>4. Understand the data that you’ve collected (plot it!)</h3>
<p><br />
</p>
<p>Import the data file ‘mrse.txt’ into R and take a look at the
structure of this dataframe. Given you have never seen this data before,
it’s really important that you familiarise yourself with any
nuances.</p>
<p>Keep the tips and tricks you used in yesterday’s practical and feel
free to use them again here; load in the data, check for any covariates
you need to adjust, plot out the data, etc.</p>
<p>A bit of advice for visualising <span
class="math inline">\(Binomial\)</span> data; it can be easier to
visualise if you create a new column in your dataset which is the
proportion of success. You can calculate proportion as the number of
successes divided by the number of trials (using the terminology of the
<span class="math inline">\(Binomial\)</span> distribution). If in
doubt, ask for help.</p>
<p>Keep in mind that to run Binomial GLMs in R, we need both the number
of successes (here, the number of patients with MRSE) but also the
number of failures. We have the number with MRSE in the data already
(<code>mrse</code>) but we don’t have number of failures. Instead we
have the total number of patients (<code>total_patients</code>). It’s a
good idea to create a column that contains failures (within context of
MRSE, think of failure as those patients for whom the detection of MRSE
“failed”).</p>
<p>For the figures below, I am using a very commonly used <code>R</code>
package, called <code>ggplot2</code>. This is entirely personal
preference. It is entirely acceptable to use <code>base R</code> to do
your plotting, so do not feel as though you must use
<code>ggplot2</code>. If, however, you would like to, check out the
Intro2R book, which contains a chapter on using <code>ggplot2</code>.
Further, there are multiple ways to visualise data and also what
questions you might want those figures to answer. The examples I include
are just that. Examples.</p>
<p><img src="GLM_2_Binomial_exercise_files/figure-html/Q4-1.png" width="672" /><img src="GLM_2_Binomial_exercise_files/figure-html/Q4-2.png" width="672" /><img src="GLM_2_Binomial_exercise_files/figure-html/Q4-3.png" width="672" /><img src="GLM_2_Binomial_exercise_files/figure-html/Q4-4.png" width="672" /><img src="GLM_2_Binomial_exercise_files/figure-html/Q4-5.png" width="672" /></p>
<p><br />
</p>
</div>
<div id="combine-into-a-model-that-can-answer-your-question."
class="section level3">
<h3>5. Combine into a model that can answer your question.</h3>
<p><br />
</p>
<p>Having gone through the previous steps, it’s now time to run our
first model. Given we had some practice yesterday, we can start with the
model we want to actually run:</p>
<p>Run the model now, using <code>glm()</code>.</p>
<ul>
<li>Hints:
<ul>
<li>We use <code>family =</code> to specify the distribution in a
<code>glm()</code>
<ul>
<li>“Family” is just an alternative way to refer to a distribution.</li>
</ul></li>
<li>Remember that for Binomial GLMs we must specify both success and
failure
<ul>
<li>To do so, we use <code>cbind(success, fail)</code> replacing success
and failure with your respective variables</li>
</ul></li>
<li>What is the default link function used by Binomial GLMs?
<ul>
<li>How do we specify it?</li>
<li>Do we need to specify it?</li>
</ul></li>
<li>Use <code>?glm</code> if you’re stuck, or ask for help.</li>
</ul></li>
</ul>
<p><br />
</p>
</div>
<div id="check-your-assumptions." class="section level3">
<h3>6. Check your assumption(s).</h3>
<p><br />
</p>
<p>Having run the model, we now need to check how well this model meets
the assumptions.</p>
<p>To do so, we can check the model diagnostic plots, as well as check
for dispersion. Do so now.</p>
<p>For the diagnostic plots:</p>
<ul>
<li>Residuals vs Fitted
<ul>
<li>What kind of pattern would we expect?</li>
</ul></li>
<li>Q-Q Residuals
<ul>
<li>Are we expecting Normally distributed error with a Binomial
distribution?</li>
</ul></li>
<li>Scale-Location
<ul>
<li>What kind of pattern would we expect?</li>
</ul></li>
<li>Residuals vs Leverage
<ul>
<li>Are any observations having a strong influence on the model
fit?</li>
</ul></li>
</ul>
<p><img src="GLM_2_Binomial_exercise_files/figure-html/Q6-1.png" width="672" /></p>
<p><br />
</p>
</div>
<div id="interpret-your-model." class="section level3">
<h3>7. Interpret your model.</h3>
<p><br />
</p>
<p>Using <code>summary()</code>, go through each <code>Estimate</code>
and provide an interpretation of what it means scientifically. E.g. what
does the <code>n_staff</code> <code>Estimate</code> mean?</p>
<p><br />
</p>
</div>
<div id="create-figures-to-show-predicted-relationships."
class="section level3">
<h3>8. Create figures to show predicted relationships.</h3>
<p><br />
</p>
<p>In the <span class="math inline">\(Poisson\)</span> exercise, we
relied on <code>packages</code> to make our figures for us. In today’s
exercise, we’ll do these ourselves so that we get the freedom to make
any aesthetic changes we might want, or to make show predictions
according to specific circumstances. Doing so, inevitably, will require
more work on our side though.</p>
<p>For started, we need a “new” dataset that contains an even spread of
covariate values that we want to use to make predictions. In the
lecture, I showed a trick we can use to do so; by using the
<code>expand.grid()</code> function. Using this we’ll start off by
making a dataset to show the relationship for <code>capacity</code>, and
then afterwards, do this again to show the relationship for the
interaction between <code>policy</code> and <code>n_staff</code>.
Regardless of which prediction we are doing, we must provide values for
all covariates in the model, even those we don’t necessarily want to
show. The choice for what values to set covariates to is not necessarily
trivial, but the convention is to set them to the median. For example,
for <code>n_staff</code>, we might set all values of this covariate to
<code>median(icu$n_staff)</code>, but there’s nothing to stop us from
setting these to values we are particularly interested in. For instance,
maybe we want to show the predicted relationship of capacity with the
maximum number of staff if we wanted to show the best case scenario for
the capacity relationship. Now that we’re creating these predictions by
hand, rather than relying on <code>R</code> packages, we have the
freedom to do so.</p>
<p>For <code>capacity</code>, we can create our fake dataset using the
following code:</p>
<pre><code># Create a fake dataset to feed into our model equation
synth_data <- expand.grid(
# Set n_staff to median (22 staff) or any value you think is interesting
n_staff = median(icu$n_staff),
# We have to set policy to either Not implemented or Implemented
policy = "Implemented",
capacity = seq(
# We create a sequence from the minimum capacity observered
from = min(icu$capacity),
# To the maximum capacity observed
to = max(icu$capacity),
# And request 20 values across that range
length.out = 20)) </code></pre>
<p>We can then use this new <em>synthetic</em> dataset to create
predictions of proportion of MRSE positive patients using the
<code>predict()</code> function. The <code>predict()</code> function
takes our model equation (with the estimated parameter values) and
combines this with either the original data (if we did not supply a
synthetic dataset) or with a synthetic data (if you do supply a
synthetic dataset) to calculate the expected MRSE proportions, given the
respective covariate values.</p>
<pre><code>synth_data$pred <- predict(mod1, newdata = synth_data)</code></pre>
<p>A hint: we can tell the <code>predict()</code> function to use the
inverse link function automatically when making the predictions, so we
don’t need to by setting <code>type = "response"</code> or else we could
always do this manually by using the inverse link function (here <span
class="math inline">\(\frac{e^x}{(1+e^x)}\)</span>, or
<code>plogis()</code> in <code>R</code>) such that our predicted values
are on the response scale.</p>
<pre><code>synth_data$pred <- predict(mod1, newdata = synth_data, type = "response")
# Or
synth_data$pred <- plogis(predict(mod1, newdata = synth_data))</code></pre>
<p>Once done, we can use our new synthetic data and predicted MRSE
prevalence to create a figure that shows the relationships for
capacity.</p>
<pre><code># Plot the raw data
plot(icu$capacity, icu$proportion, xlab= "Ward capacity", ylab= "Proportion of patients with MRSE")
# And add a line to show our predicted model fit
lines(synth_data$pred ~ synth_data$capacity, lty = 1, col = 1)</code></pre>
<p>Your figure should look like:</p>
<p><img src="GLM_2_Binomial_exercise_files/figure-html/Q8.1-1.png" width="672" /></p>
<p>Now for the harder part of the model. We’ll need to go through the
same steps as above, but this time making tweaks to show the interaction
between <code>policy</code> and <code>n_staff</code>.</p>
<p>Hint: the biggest “part” here is creating the synthetic data such
that we can show the <code>n_staff</code> relationship for <em>both</em>
levels of <code>policy</code>, but doing so, requires only two small
changes to the <code>expand.grid()</code> code.</p>
<p>Give it a go, but if you’re struggling, ask for help. This is a tough
one.</p>
<p><br />
</p>
</div>
<div id="uncertainty" class="section level3">
<h3>9. Uncertainty</h3>
<p><br />
</p>
<p>It’s always important to show uncertainty when visualising (or
reporting) what our model has estimated. Without uncertainty, we
essentially tell our reader that we know <em>exactly</em> how the world
works. Clearly we don’t, we have a crude understanding build upon many
assumptions. Showing uncertainty, often through confidence intervals, is
a way to, at the very least, acknowledge that we <em>don’t</em> know the
exact Truth.</p>
<p>Including confidence intervals requires that we calculate them. Doing
so by hand is an absolute pain, but thankfully, <code>R</code> makes
this relatively easier. All we need to do is tell the
<code>predict()</code> function to also report standard error for each
predicted observation, and then convert these to upper and lower 95%
CI.</p>
<p>Here’s how we do that for capacity:</p>
<pre><code># We remake our synthetic data for visualising *capacity*
synth_data <- expand.grid(
n_staff = median(icu$n_staff),
policy = "Implemented",
capacity = seq(
from = min(icu$capacity),
to = max(icu$capacity),
length.out = 20))
# Now instead of just getting a single column of mean prediction, we ask predict()
# for two columns - one for mean prediction and another for standard error.
# This means we cannot simply add the predictions, as is, to our synth_data
# Instead we store the output to then calculate 95% CI
# Note that we now include the argument se.fit = TRUE, to get our standard error
# We also cannot use type = response anymore, instead we use plogis but later on
pred <- predict(mod1, newdata = synth_data, se.fit = TRUE)
# Extract the mean Estimate on response scale
synth_data$pred <- plogis(pred$fit)
# Subtract SE * 1.96 to get 95% and backtransform for lower 95% CI
synth_data$low <- plogis(pred$fit - pred$se.fit * 1.96)
# Add SE * 1.96 to get 95% and backtransform for upper 95% CI
synth_data$upp <- plogis(pred$fit + pred$se.fit * 1.96)
# Plot the raw data
plot(icu$capacity, icu$proportion,
xlab = "Ward capacity",
ylab = "Proportion of patients with MRSE")
# As before, add a line to show our predicted model fit
lines(synth_data$pred ~ synth_data$capacity, lty = 1, col = "black")
# Now we add two new dashed lines (lty = 2 for dashed) to show 95% CI
lines(synth_data$low ~ synth_data$capacity, lty = 2, col = "grey")
lines(synth_data$upp ~ synth_data$capacity, lty = 2, col = "grey")</code></pre>
<p>Your figure should look like:</p>
<p><img src="GLM_2_Binomial_exercise_files/figure-html/Q9.1-1.png" width="672" /></p>
<p>Getting the <code>synth_data</code>, mean estimates and 95% CI is the
hard part. Once we have these sorted out, we can create a figure however
we like. The example above looks fairly bland and boring, but we can
always change this.</p>
<p>Using your code from the above figure showing capacity, adapt it now
to visualise the interaction between <code>policy</code> and
<code>n_staff</code> which includes 95% CI. Below I give an example of
how I’d visualise the predictions, but you’re free to do this however
you’d like.</p>
<p><img src="GLM_2_Binomial_exercise_files/figure-html/Q9.2-1.png" width="672" /></p>
<p>In my above example figure, notice how predicted relationship for Not
Implemented is generally below our data? If you’re interesting in why
that’s the case, try remaking this figure and set capacity (bed
occupancy) to 100% to see if that changes anything.</p>
<p><br />
</p>
</div>
<div id="the-monkeys-paw" class="section level3">
<h3>10. The Monkey’s Paw</h3>
<p><br />
</p>
<p>Think back to the very first lecture where we spoke about the four
broad assumptions. The first was the assumption of <em>Validity</em>.
For the data that we’ve been modelling here, we’ve constantly spoken
about how many patients were MRSE positive. But is that accurate? In
truth, we actually don’t know how many patients were actually MRSE
positive. All we know is how many <em>tested</em> positive. In order for
a patient to be declared MRSE positive, there are quite a few tests that
have to be done, and at minimum number must come back positive before
declaring MRSE - meaning lots of tests where we can get
false-negatives.</p>
<p>So. What we’re actually asking with our models here is not “What
proportion of patients are MRSE positive?”. Instead, we’re asking “What
proportion of patients are MRSE positive <em>and also</em> tested
positive?”. This might seem like a trivial difference, but just as in
the coffee example in the first lecture, the deterministic process
underlying why a sample tests positive or not is more complex than
simply the true MRSE state. How reliable are the tests? Was the lab
technician tired? Had they just broken up with their partner, and so
were very distracted when running the test? Was the result correctly
recorded? Plus no shortage of other variables that influenced the
probability of whether or not a sample tested positive.</p>
<p>Mathematically, we would say there are two probabilities at play here
which combine to give a single probability (and outcome). The
probability that a patient is actually MRSE positive is multiplied by
the probability MRSE was detected, given they were MRSE positive. With
the data we have, it’s impossible to disentangle these two probabilities
(though there are sampling and corresponding statistical methods to do
just that), so we’re left explaining the combined probabilities rather
than the one we’re actually interested in - whether or not a patient is
MRSE positive.</p>
<p>This example of violating the assumption of <em>Validity</em> is
possibly one of the most common ways I see it being broken, and it can
be really hard to identify. It can be even harder to convince people
they have broken it. Certainly, there are no statistical tests we can
perform to test for it, and not much we can do having already collected
the data. The only way to catch it, is to 1) know about it, and 2) think
<em>very, very</em> carefully about what the data actually is.</p>
<p>This is why the first part of your analysis <em>must</em> be sitting
back and thinking about your data and research question. Without that
step… The Monkey’s Paw awaits.</p>
<p><br />
</p>
</div>
<div id="optional-exploring-model-diagnostics" class="section level3">
<h3>11. (Optional) Exploring model diagnostics</h3>
<p>As in the <span class="math inline">\(Poisson\)</span> exercise,
below I include code to simulate a <span
class="math inline">\(Binomial\)</span> dataset to allow you to explore
the impact of sample size, model misspecification, and effect size, on
model diagnostic plots. The <em>Data Generating Process</em> (DGP) for
the dataset is:</p>
<p><span class="math inline">\(y_i \sim Binomial(p_i, k_i)\)</span></p>
<p><span class="math inline">\(logit(p_i) = \beta_0 + \beta_1 \times
x_{1,i} + \beta_2 \times x_{2,i} + \beta_3\times x_{3,i} + \beta_4
\times x_{1, i} \times x_{2,i}\)</span></p>
<p>where you are free to decide what the values for the parameters
(<span class="math inline">\(\beta_{0,...,4}\)</span>) are. Note that
given you’ve now run a model that included an interaction, the DGP also
includes an interaction between <span class="math inline">\(x_1\)</span>
and <span class="math inline">\(x_2\)</span></p>
<p>Rerun the simulation and analysis varying the sample size
(e.g. <code>N <- 1000</code>), the effect sizes
(e.g. <code>beta_0 <- 10</code>) or the formula of the
<code>glm()</code> (e.g. remove the interaction). Check what effect this
has on dispersion and the model diagnostic plots.</p>
<pre><code># Set your seed to have the randomness be cosnsitent each time you run the code
# You can change this, or comment it out, if you want to embrase the randomness
set.seed(1234)
# Set your sample size
N <- 500
# Set the number of trials
k <- 10
# Create three continuous covariates
x1 <- runif(N, 0, 10)
x2 <- runif(N, 0, 10)
x3 <- runif(N, 0, 10)
# Set your parameter values
beta_0 <- 2.5 # This is the intercept (on link scale)
beta_1 <- 0.2 # This is the slope for the x1 variable (on link scale)
beta_2 <- -1.3 # This is the slope for the x2 variable (on link scale)
beta_3 <- 0.4 # This is the slope for the x3 variable (on link scale)
beta_4 <- 0.05 # The combined effect of x1 and x2 (on link scale)
# Generate your linear predictor on the link scale (i.e. log)
# We don't actually need to use log() here (it's already on the link scale)
linear_predictor_link <- beta_0 + beta_1 * x1 + beta_2 * x2 + beta_3 * x3 + beta_4 * x1 * x2
# Backtransform your linear predictor to the response scale (i.e. exponentiate)
linear_predictor_response <- plogis(linear_predictor_link)
# Generate your response variable using a Binomial random number generator (rbinom)
y <- rbinom(N, size = k, prob = linear_predictor_response)
# Note that the above three lines of code are the equivalent to the equations:
# y ~ Binomial(p, k)
# logit(p) = beta_0 + beta_1 * x1 + beta_2 * x2 + beta_3 * x3 + beta_4 * x1 * x2
# Store your data in a dataframe
dat <- data.frame(y, x1, x2, x3)
# Create the "fails" column
dat$fail <- k - dat$y
# Run a Binomial GLM
fit <- glm(cbind(y, fail) ~ x1 + x2 + x3 + x1 : x2,
data = dat,
family = binomial)
# See if the model was able to estimate your parameter values
# and what the dispersion is
summary(fit)
# See how well the model diagnostics perform
par(mfrow = c(2,2))
plot(fit)</code></pre>
<p><strong>End of the Binomial GLM - understanding Multi-drug Resistance
<em>Staphylococcus epidermidis</em></strong></p>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.odd').parent('tbody').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open');
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
window.initializeCodeFolding("hide" === "show");
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>