-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGLM_1_Poisson_exercise_solutions.html
1327 lines (1229 loc) · 73.9 KB
/
GLM_1_Poisson_exercise_solutions.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
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Day 1: Poisson 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">
code {
white-space: pre;
}
.sourceCode {
overflow: visible;
}
</style>
<style type="text/css" data-origin="pandoc">
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
color: #aaaaaa;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; }
div.sourceCode
{ background-color: #f8f8f8; }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span.al { color: #ef2929; } /* Alert */
code span.an { color: #8f5902; font-weight: bold; font-style: italic; } /* Annotation */
code span.at { color: #204a87; } /* Attribute */
code span.bn { color: #0000cf; } /* BaseN */
code span.cf { color: #204a87; font-weight: bold; } /* ControlFlow */
code span.ch { color: #4e9a06; } /* Char */
code span.cn { color: #8f5902; } /* Constant */
code span.co { color: #8f5902; font-style: italic; } /* Comment */
code span.cv { color: #8f5902; font-weight: bold; font-style: italic; } /* CommentVar */
code span.do { color: #8f5902; font-weight: bold; font-style: italic; } /* Documentation */
code span.dt { color: #204a87; } /* DataType */
code span.dv { color: #0000cf; } /* DecVal */
code span.er { color: #a40000; font-weight: bold; } /* Error */
code span.ex { } /* Extension */
code span.fl { color: #0000cf; } /* Float */
code span.fu { color: #204a87; font-weight: bold; } /* Function */
code span.im { } /* Import */
code span.in { color: #8f5902; font-weight: bold; font-style: italic; } /* Information */
code span.kw { color: #204a87; font-weight: bold; } /* Keyword */
code span.op { color: #ce5c00; font-weight: bold; } /* Operator */
code span.ot { color: #8f5902; } /* Other */
code span.pp { color: #8f5902; font-style: italic; } /* Preprocessor */
code span.sc { color: #ce5c00; font-weight: bold; } /* SpecialChar */
code span.ss { color: #4e9a06; } /* SpecialString */
code span.st { color: #4e9a06; } /* String */
code span.va { color: #000000; } /* Variable */
code span.vs { color: #4e9a06; } /* VerbatimString */
code span.wa { color: #8f5902; font-weight: bold; font-style: italic; } /* Warning */
.sourceCode .row {
width: 100%;
}
.sourceCode {
overflow-x: auto;
}
.code-folding-btn {
margin-right: -30px;
}
</style>
<script>
// apply pandoc div.sourceCode style to pre.sourceCode instead
(function() {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].ownerNode.dataset["origin"] !== "pandoc") continue;
try { var rules = sheets[i].cssRules; } catch (e) { continue; }
var j = 0;
while (j < rules.length) {
var rule = rules[j];
// check if there is a div.sourceCode rule
if (rule.type !== rule.STYLE_RULE || rule.selectorText !== "div.sourceCode") {
j++;
continue;
}
var style = rule.style.cssText;
// check if color or background-color is set
if (rule.style.color === '' && rule.style.backgroundColor === '') {
j++;
continue;
}
// replace div.sourceCode by a pre.sourceCode rule
sheets[i].deleteRule(j);
sheets[i].insertRule('pre.sourceCode{' + style + '}', j);
}
}
})();
</script>
<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 1: Poisson GLMs</h1>
</div>
<p> </p>
<div id="exercise-poisson-glm---predicting-species-richness"
class="section level1">
<h1>Exercise: Poisson GLM - predicting species richness</h1>
<p> </p>
<p>For the GLM exercises, we’ll use the workflow we suggested in the LM
lectures, and expanded upon in the GLM introduction 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 element).</p></li>
<li><p>Think about the process behind the data (deterministic
element).</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>Repeat steps 6 and 7 as required.</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> </p>
<p>The researchers who collected this data wanted to describe the
relationships between the number of species (<code>Species</code>)
present in a plot of land, and how this number was associated with the
overall plant biomass (<code>Biomass</code>, i.e. what was the overall
weight of plants in the plot of land), and the pH of the soil
(<code>pH</code>, categorised into “High”, “Medium” and “Low”). The
researchers were interested in describing the associations between
species and the two explanatory variables. In total, the researchers
collected data from 90 plots of land (<span class="math inline">\(n =
90\)</span>), where each observation is from a single plot.</p>
<p> </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> </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 (the
fact that this practical is called Poisson GLM may also offer a rather
cryptic hint…). The relevant information comes from the description of
<code>Species</code> indicating that this variable is a count, which
implies 1) the minimum value is 0 [we cannot have -1 species], and 2)
the response variable will be measured in integers [we cannot count 3.14
plants]. With this information alone, we can already deduce the
<em>stochastic</em> element of our model (i.e. the error) should be
adequately described by specifying a <span
class="math inline">\(Poisson\)</span> distribution.</p>
<p>Therefore, the stochastic element of our model will be:</p>
<p><span class="math inline">\(y_i \sim Poisson(\lambda_i)\)</span></p>
<p>Where <span class="math inline">\(y\)</span> is the count of species
in a plot <span class="math inline">\(i\)</span>, generated according to
a <span class="math inline">\(Poisson\)</span> distribution with rate
<span class="math inline">\(\lambda\)</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> </p>
<p>Spare a moment’s thought to how complex the process behind the number
of plant species present in a plot of land will be. How much sunlight
does each plot get? How much rainfall? What seeds were already present
in the soil before data collection started? Why were <em>those</em>
seeds present and not others? Why did some of them germinate in time for
us to count them?</p>
<p>We don’t have any data to try and explain this variation, yet it will
still be there (this is what we are tasking the stochastic part of the
model to deal with).</p>
<p>For our purposes, the deterministic part we’re interested in is what
role plant biomass and soil pH plays in determining species richness.
With this in mind, the deterministic element of our model will be:</p>
<p><span class="math inline">\(log(\lambda_i) = \beta_0 + \beta_1 \times
Biomass_i + \beta_2 \times midpH_i + \beta_3 \times
highpH_i\)</span></p>
<p>Where <span class="math inline">\(\lambda\)</span> is our linear
predictor regressed on the <span class="math inline">\(log\)</span> link
scale, where <span class="math inline">\(\beta_0\)</span> is the
intercept (which defaults to low pH), <span
class="math inline">\(\beta_1\)</span> is the slope for biomass, <span
class="math inline">\(\beta_2\)</span> is the difference from low pH
(<span class="math inline">\(\beta_0\)</span>) to mid pH, and <span
class="math inline">\(\beta_3\)</span> is the difference from low pH to
high pH.</p>
<p>Remember that for categorical variables, <code>R</code> will convert
these into a series of columns with 1 indicating an observation belongs
to a group and 0 indicating the converse. One of the groups will not
have a column (the group that has the lowest alphanumerical value,
e.g. for a categorical variable with groups <code>A</code> and
<code>B</code>, <code>A</code> would be first), and it is this group
that becomes the intercept (<span
class="math inline">\(\beta_0\)</span>). We are able to specify which
group becomes our reference and we’ll do this later on, such that
<code>low</code> is our reference point.</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> </p>
<p>We now get to the part where we’ll actually start using
<code>R</code>. A plea though - do not underestimate the value in taking
the time to think carefully about the previous steps. Spending the time
thinking about those questions makes your life that much easier. I’d
estimate that for my own work, I spend at least 60% of my time thinking
before doing anything with data or <code>R</code>. It really is that
important.</p>
<p>4.1. Get R ready to go</p>
<p>As in previous exercises, either create a new R script (perhaps call
it GLM_Poisson) or continue with your previous R script in your RStudio
Project. Again, make sure you include any metadata you feel is
appropriate (title, description of task, date of creation etc) and don’t
forget to comment out your metadata with a <code>#</code> at the
beginning of the line.</p>
<p>4.2. Data exploration</p>
<p>Import the data file ‘species.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. To
help with this, carry out an initial data exploration (using any methods
you think will help you get a sense of the data,
e.g. <code>plot()</code>, <code>pairs()</code>, <code>coplot()</code>,
amongst many other options).</p>
<p>While doing this, ask yourself:</p>
<ul>
<li>Do any of the variables need to be adjusted? (e.g. are factors
recognised as such?)</li>
<li>Do any factors need to be “re-levelled”, such that it is read “Low”,
“Medium”High” (or any order we may prefer)?
<ul>
<li>Hint: check <code>?factor</code> and look at the <code>levels</code>
argument</li>
<li>Hint: it might make sense for <code>low</code> pH to be our
reference level</li>
</ul></li>
<li>Are there any relationships you can already see by eye alone?</li>
<li>Are there any imbalances in any of the explanatory variables?</li>
<li>Are there any observations that seem like they may be a data entry
mistake?</li>
</ul>
<p>If using <code>pairs()</code> to create a plot of the variables of
interest, rather than creating a plot with every single variable in our
dataset, we may prefer to restrict the plot to the variables we are
actually interested in (this is redundant for this dataset but it’s
worth keeping this trick in mind for larger datasets). An effective way
of doing this is to store the names of the variables of interest in a
vector <code>VOI<- c("Var1", "Var2", ...)</code> and then use the
list of variable names to subset the variables that get plotted
(e.g. <code>pairs(Mydata[, VOI])</code>)</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" tabindex="-1"></a>sp <span class="ot"><-</span> <span class="fu">read.table</span>(<span class="at">file=</span> <span class="st">"./data/species.txt"</span>, <span class="at">header=</span> <span class="cn">TRUE</span>)</span>
<span id="cb1-2"><a href="#cb1-2" tabindex="-1"></a></span>
<span id="cb1-3"><a href="#cb1-3" tabindex="-1"></a><span class="co"># Check the structure of the data to see if we need to correct anything</span></span>
<span id="cb1-4"><a href="#cb1-4" tabindex="-1"></a><span class="fu">str</span>(sp)</span>
<span id="cb1-5"><a href="#cb1-5" tabindex="-1"></a><span class="do">## 'data.frame': 90 obs. of 3 variables:</span></span>
<span id="cb1-6"><a href="#cb1-6" tabindex="-1"></a><span class="do">## $ Species: int 9 10 15 9 7 8 7 6 13 14 ...</span></span>
<span id="cb1-7"><a href="#cb1-7" tabindex="-1"></a><span class="do">## $ Biomass: num 2.2 1.6 1 1.4 4.9 3.9 3.9 6.5 0.3 1.9 ...</span></span>
<span id="cb1-8"><a href="#cb1-8" tabindex="-1"></a><span class="do">## $ pH : chr "low" "low" "low" "low" ...</span></span>
<span id="cb1-9"><a href="#cb1-9" tabindex="-1"></a></span>
<span id="cb1-10"><a href="#cb1-10" tabindex="-1"></a><span class="co"># Correct pH so it is read as a factor, reordered such that "low" is the reference level</span></span>
<span id="cb1-11"><a href="#cb1-11" tabindex="-1"></a>sp<span class="sc">$</span>pH<span class="ot"><-</span> <span class="fu">factor</span>(sp<span class="sc">$</span>pH, <span class="at">levels =</span> <span class="fu">c</span>(<span class="st">"low"</span>, <span class="st">"mid"</span>, <span class="st">"high"</span>))</span>
<span id="cb1-12"><a href="#cb1-12" tabindex="-1"></a></span>
<span id="cb1-13"><a href="#cb1-13" tabindex="-1"></a><span class="co"># Get simple descriptives of the data (e.g. what is the range for each variable?)</span></span>
<span id="cb1-14"><a href="#cb1-14" tabindex="-1"></a><span class="fu">summary</span>(sp)</span>
<span id="cb1-15"><a href="#cb1-15" tabindex="-1"></a><span class="do">## Species Biomass pH </span></span>
<span id="cb1-16"><a href="#cb1-16" tabindex="-1"></a><span class="do">## Min. : 2.00 Min. : 0.300 low :30 </span></span>
<span id="cb1-17"><a href="#cb1-17" tabindex="-1"></a><span class="do">## 1st Qu.:12.00 1st Qu.: 1.300 mid :30 </span></span>
<span id="cb1-18"><a href="#cb1-18" tabindex="-1"></a><span class="do">## Median :18.50 Median : 2.000 high:30 </span></span>
<span id="cb1-19"><a href="#cb1-19" tabindex="-1"></a><span class="do">## Mean :22.34 Mean : 2.684 </span></span>
<span id="cb1-20"><a href="#cb1-20" tabindex="-1"></a><span class="do">## 3rd Qu.:33.00 3rd Qu.: 3.275 </span></span>
<span id="cb1-21"><a href="#cb1-21" tabindex="-1"></a><span class="do">## Max. :52.00 Max. :13.600</span></span>
<span id="cb1-22"><a href="#cb1-22" tabindex="-1"></a></span>
<span id="cb1-23"><a href="#cb1-23" tabindex="-1"></a><span class="co"># make a list of the variables of interest, for convenience:</span></span>
<span id="cb1-24"><a href="#cb1-24" tabindex="-1"></a>VOI<span class="ot"><-</span> <span class="fu">c</span>(<span class="st">"Species"</span>, <span class="st">"Biomass"</span>, <span class="st">"pH"</span>)</span>
<span id="cb1-25"><a href="#cb1-25" tabindex="-1"></a><span class="fu">pairs</span>(sp[, VOI])</span></code></pre></div>
<p><img src="GLM_1_Poisson_exercise_solutions_files/figure-html/Q4-1.png" width="672" /></p>
<div class="sourceCode" id="cb2"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb2-1"><a href="#cb2-1" tabindex="-1"></a><span class="co"># Negative relationship between Species and Biomass?</span></span>
<span id="cb2-2"><a href="#cb2-2" tabindex="-1"></a><span class="co"># Positive relationship between Species and pH? </span></span>
<span id="cb2-3"><a href="#cb2-3" tabindex="-1"></a><span class="co"># Biomass tends to increase with pH, which could generate</span></span>
<span id="cb2-4"><a href="#cb2-4" tabindex="-1"></a><span class="co"># some collinearity between these explanatory variables in a model.</span></span>
<span id="cb2-5"><a href="#cb2-5" tabindex="-1"></a><span class="co"># but still plenty of variation in Biomass within each pH, </span></span>
<span id="cb2-6"><a href="#cb2-6" tabindex="-1"></a><span class="co"># so hopefully this won't be an issue.</span></span>
<span id="cb2-7"><a href="#cb2-7" tabindex="-1"></a></span>
<span id="cb2-8"><a href="#cb2-8" tabindex="-1"></a><span class="fu">coplot</span>(Species <span class="sc">~</span> Biomass <span class="sc">|</span> pH, <span class="at">data =</span> sp)</span></code></pre></div>
<p><img src="GLM_1_Poisson_exercise_solutions_files/figure-html/Q4-2.png" width="672" /></p>
<div class="sourceCode" id="cb3"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb3-1"><a href="#cb3-1" tabindex="-1"></a><span class="co"># the relationships looks consistently negative with biomass across the pH levels</span></span></code></pre></div>
<p> </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> </p>
<p>Having gone through the previous steps, it’s now time to run our
first model. Given this is the first practical session, we’ll start with
a simple model for the sake of pedagogy, where we explore how species
richness is related with biomass.</p>
<p>Write the equation (not the <code>R</code> code) for this simplified
model.</p>
<p>Hint: You can always use the more complex model, written in steps 2
and 3, and simplify it to match the first model we’ll run.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb4-1"><a href="#cb4-1" tabindex="-1"></a><span class="co"># y_i ~ Poisson(lambda_i)</span></span>
<span id="cb4-2"><a href="#cb4-2" tabindex="-1"></a><span class="co"># log(lambda_i) = beta_0 + beta_1 * Biomass</span></span></code></pre></div>
<p> </p>
</div>
<div id="fit-the-model." class="section level3">
<h3>6. Fit the model.</h3>
<p> </p>
<p>To warm up, let’s start by using this simpler model, where we assume
that the number <code>Species</code> counted in a plot is a function of
how much <code>Biomass</code> there was. We’ll leave <code>pH</code> out
of the model for the time being.</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>What is the default link function used by Poisson 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>
<div class="sourceCode" id="cb5"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb5-1"><a href="#cb5-1" tabindex="-1"></a>sp.glm1 <span class="ot"><-</span> <span class="fu">glm</span>(Species <span class="sc">~</span> Biomass, </span>
<span id="cb5-2"><a href="#cb5-2" tabindex="-1"></a> <span class="at">family =</span> <span class="fu">poisson</span>(<span class="at">link =</span> <span class="st">"log"</span>), </span>
<span id="cb5-3"><a href="#cb5-3" tabindex="-1"></a> <span class="at">data =</span> sp)</span></code></pre></div>
<p> </p>
</div>
<div id="check-your-assumptions." class="section level3">
<h3>7. Check your assumption(s).</h3>
<p> </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 distribted error with a Poisson
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>
<div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb6-1"><a href="#cb6-1" tabindex="-1"></a><span class="co"># Model diagnostic plots:</span></span>
<span id="cb6-2"><a href="#cb6-2" tabindex="-1"></a><span class="co"># Residuals vs Fitted</span></span>
<span id="cb6-3"><a href="#cb6-3" tabindex="-1"></a> <span class="co"># We see a fairly clear "funnel" pattern. We go from having relatively "little" variation</span></span>
<span id="cb6-4"><a href="#cb6-4" tabindex="-1"></a> <span class="co"># when our predicted values (on the link scale) are small, to "lots" of variation</span></span>
<span id="cb6-5"><a href="#cb6-5" tabindex="-1"></a> <span class="co"># when our predicted values are large, and most of this is happening between predicted</span></span>
<span id="cb6-6"><a href="#cb6-6" tabindex="-1"></a> <span class="co"># values of 2.5 to 3.5 (so over a fairly small range of predicted values)</span></span>
<span id="cb6-7"><a href="#cb6-7" tabindex="-1"></a> <span class="co"># This would suggest we're not meeting the assumptions particularly well and</span></span>
<span id="cb6-8"><a href="#cb6-8" tabindex="-1"></a> <span class="co"># is a good indication that we have overdispersion.</span></span>
<span id="cb6-9"><a href="#cb6-9" tabindex="-1"></a><span class="co"># Q-Q Residuals</span></span>
<span id="cb6-10"><a href="#cb6-10" tabindex="-1"></a> <span class="co"># We completely ignore this figure for GLMs.</span></span>
<span id="cb6-11"><a href="#cb6-11" tabindex="-1"></a><span class="co"># Scale-Location</span></span>
<span id="cb6-12"><a href="#cb6-12" tabindex="-1"></a> <span class="co"># We also don't want to see any patterns (as for Resids vs Fitted) but we see the</span></span>
<span id="cb6-13"><a href="#cb6-13" tabindex="-1"></a> <span class="co"># same rapid increase in variation once predicted values are above 2.5</span></span>
<span id="cb6-14"><a href="#cb6-14" tabindex="-1"></a><span class="co"># Residuals vs Leverage</span></span>
<span id="cb6-15"><a href="#cb6-15" tabindex="-1"></a> <span class="co"># We're really only using this to check for values close to a Cook's distance of 1</span></span>
<span id="cb6-16"><a href="#cb6-16" tabindex="-1"></a> <span class="co"># While we don't have any observations that are greater than 1, we have a handful</span></span>
<span id="cb6-17"><a href="#cb6-17" tabindex="-1"></a> <span class="co"># that are getting uncomfortably close. While these values are fine, we're</span></span>
<span id="cb6-18"><a href="#cb6-18" tabindex="-1"></a> <span class="co"># not exactly jumping for joy with these Cook's distances.</span></span>
<span id="cb6-19"><a href="#cb6-19" tabindex="-1"></a><span class="co"># Overall, the diagnostic plots don't look great. Not the worst, but we'd want something</span></span>
<span id="cb6-20"><a href="#cb6-20" tabindex="-1"></a><span class="co"># better.</span></span>
<span id="cb6-21"><a href="#cb6-21" tabindex="-1"></a></span>
<span id="cb6-22"><a href="#cb6-22" tabindex="-1"></a><span class="co"># To do a quick and crude check for dispersion, we can use the information from summary()</span></span>
<span id="cb6-23"><a href="#cb6-23" tabindex="-1"></a> <span class="co"># We take residual deviance and divide by the degrees of freedom, so for this model:</span></span>
<span id="cb6-24"><a href="#cb6-24" tabindex="-1"></a> <span class="co"># 432.63/88 = 4.9!</span></span>
<span id="cb6-25"><a href="#cb6-25" tabindex="-1"></a> <span class="co"># We have a whopping 4.9 overdispersion! My general rule of thumb is that I start getting</span></span>
<span id="cb6-26"><a href="#cb6-26" tabindex="-1"></a> <span class="co"># concerned when dispersion is somewhere in the 1.5-1.8 region. 4.9 is doomsday!</span></span>
<span id="cb6-27"><a href="#cb6-27" tabindex="-1"></a> <span class="co"># As a result, our standard error for our parameter estimates is going to be artificially</span></span>
<span id="cb6-28"><a href="#cb6-28" tabindex="-1"></a> <span class="co"># small. This in turn leads to both 1) risks of our p value being smaller than it should be</span></span>
<span id="cb6-29"><a href="#cb6-29" tabindex="-1"></a> <span class="co"># for Biomass, and 2) any predictions that include uncertainty being too confident.</span></span>
<span id="cb6-30"><a href="#cb6-30" tabindex="-1"></a></span>
<span id="cb6-31"><a href="#cb6-31" tabindex="-1"></a><span class="fu">par</span>(<span class="at">mfrow =</span> <span class="fu">c</span>(<span class="dv">2</span>,<span class="dv">2</span>)) <span class="co"># Show figures in 2 rows and 2 columns</span></span>
<span id="cb6-32"><a href="#cb6-32" tabindex="-1"></a><span class="fu">plot</span>(sp.glm1) <span class="co"># Plot the model diagnostics</span></span></code></pre></div>
<p><img src="GLM_1_Poisson_exercise_solutions_files/figure-html/Q7-1.png" width="672" /></p>
<div class="sourceCode" id="cb7"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb7-1"><a href="#cb7-1" tabindex="-1"></a><span class="fu">par</span>(<span class="at">mfrow =</span> <span class="fu">c</span>(<span class="dv">1</span>,<span class="dv">1</span>)) <span class="co"># Reset so only 1 figure is shown</span></span>
<span id="cb7-2"><a href="#cb7-2" tabindex="-1"></a><span class="fu">summary</span>(sp.glm1) <span class="co"># Get the summary of the model (to check dispersion)</span></span>
<span id="cb7-3"><a href="#cb7-3" tabindex="-1"></a><span class="do">## </span></span>
<span id="cb7-4"><a href="#cb7-4" tabindex="-1"></a><span class="do">## Call:</span></span>
<span id="cb7-5"><a href="#cb7-5" tabindex="-1"></a><span class="do">## glm(formula = Species ~ Biomass, family = poisson(link = "log"), </span></span>
<span id="cb7-6"><a href="#cb7-6" tabindex="-1"></a><span class="do">## data = sp)</span></span>
<span id="cb7-7"><a href="#cb7-7" tabindex="-1"></a><span class="do">## </span></span>
<span id="cb7-8"><a href="#cb7-8" tabindex="-1"></a><span class="do">## Coefficients:</span></span>
<span id="cb7-9"><a href="#cb7-9" tabindex="-1"></a><span class="do">## Estimate Std. Error z value Pr(>|z|) </span></span>
<span id="cb7-10"><a href="#cb7-10" tabindex="-1"></a><span class="do">## (Intercept) 3.55455 0.03939 90.25 <2e-16 ***</span></span>
<span id="cb7-11"><a href="#cb7-11" tabindex="-1"></a><span class="do">## Biomass -0.19534 0.01604 -12.18 <2e-16 ***</span></span>
<span id="cb7-12"><a href="#cb7-12" tabindex="-1"></a><span class="do">## ---</span></span>
<span id="cb7-13"><a href="#cb7-13" tabindex="-1"></a><span class="do">## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</span></span>
<span id="cb7-14"><a href="#cb7-14" tabindex="-1"></a><span class="do">## </span></span>
<span id="cb7-15"><a href="#cb7-15" tabindex="-1"></a><span class="do">## (Dispersion parameter for poisson family taken to be 1)</span></span>
<span id="cb7-16"><a href="#cb7-16" tabindex="-1"></a><span class="do">## </span></span>
<span id="cb7-17"><a href="#cb7-17" tabindex="-1"></a><span class="do">## Null deviance: 645.45 on 89 degrees of freedom</span></span>
<span id="cb7-18"><a href="#cb7-18" tabindex="-1"></a><span class="do">## Residual deviance: 433.62 on 88 degrees of freedom</span></span>
<span id="cb7-19"><a href="#cb7-19" tabindex="-1"></a><span class="do">## AIC: 866.48</span></span>
<span id="cb7-20"><a href="#cb7-20" tabindex="-1"></a><span class="do">## </span></span>
<span id="cb7-21"><a href="#cb7-21" tabindex="-1"></a><span class="do">## Number of Fisher Scoring iterations: 4</span></span></code></pre></div>
<p> </p>
</div>
<div id="answer-your-question" class="section level3">
<h3>8. Answer your question</h3>
<p> </p>
<p>Hopefully you identified issues that mean we should be very cautious
with interpreting this model. For now, we’ll put these concerns to rest
(we will come back to them), and use this model as an opportunity to
practice making predictions (and therefore answering our research
question).</p>
<p>8.1. Go back to your equation that you wrote for question 5. We’re
going to combine the information from <code>summary()</code> with the
equation we wrote in section 5 to allow us to make predictions. As a
reminder, the statistical notation for the deterministic element of the
model with just Biomass is:</p>
<p><span class="math inline">\(log(\lambda_i) = \beta_0 + \beta_1 \times
Biomass_i\)</span></p>
<p>where <span class="math inline">\(\beta_0\)</span> was the intercept
and <span class="math inline">\(\beta_1\)</span> was the slope for
biomass.</p>
<p>Replace <span class="math inline">\(\beta_0\)</span> and <span
class="math inline">\(\beta_1\)</span> now, using your parameter
estimates from <code>summary()</code>, and use this updated equation to
make the following predictions:</p>
<ul>
<li><p>On the link scale, how many plants would you predict if a plot
had 0 kg of biomass?</p></li>
<li><p>On the link scale, how many plants would you predict if a plot
had 2.5 kg of biomass?</p></li>
<li><p>On the link scale, how many plants would you predict if a plot
had 5 kg of biomass?</p></li>
</ul>
<div class="sourceCode" id="cb8"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb8-1"><a href="#cb8-1" tabindex="-1"></a><span class="co"># On the link scale, how many plants would you predict if a plot had 0 kg of biomass?</span></span>
<span id="cb8-2"><a href="#cb8-2" tabindex="-1"></a><span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> <span class="dv">0</span> <span class="co"># = 3.554549</span></span>
<span id="cb8-3"><a href="#cb8-3" tabindex="-1"></a><span class="do">## [1] 3.554549</span></span>
<span id="cb8-4"><a href="#cb8-4" tabindex="-1"></a><span class="co"># On the link scale, how many plants would you predict if a plot had 2.5 kg of biomass?</span></span>
<span id="cb8-5"><a href="#cb8-5" tabindex="-1"></a><span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> <span class="fl">2.5</span> <span class="co"># = 3.066211</span></span>
<span id="cb8-6"><a href="#cb8-6" tabindex="-1"></a><span class="do">## [1] 3.066211</span></span>
<span id="cb8-7"><a href="#cb8-7" tabindex="-1"></a><span class="co"># On the link scale, how many plants would you predict if a plot had 5 kg of biomass?</span></span>
<span id="cb8-8"><a href="#cb8-8" tabindex="-1"></a><span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> <span class="dv">5</span> <span class="co"># = 2.577873</span></span>
<span id="cb8-9"><a href="#cb8-9" tabindex="-1"></a><span class="do">## [1] 2.577873</span></span></code></pre></div>
<p>8.2. To make interpreting these predictions easier and more
intuitive, let’s make the predictions on the response scale. To go from
the <span class="math inline">\(log\)</span> link scale, to the response
scale, we take our predictions and apply the inverse link function to
them. The inverse link function of <span
class="math inline">\(log\)</span> is <span
class="math inline">\(e\)</span> (or exponential, or
<code>exp()</code>). Predict, on the response scale, how many plant
species we would expect if:</p>
<ul>
<li><p>On the response scale, how many plants would you predict if a
plot had 0 kg of biomass?</p></li>
<li><p>On the response scale, how many plants would you predict if a
plot had 5 kg of biomass?</p></li>
<li><p>On the response scale, how many plants would you predict if a
plot had 10 kg of biomass?</p></li>
</ul>
<div class="sourceCode" id="cb9"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb9-1"><a href="#cb9-1" tabindex="-1"></a><span class="co"># On the response scale, how many plants would you predict if a plot had 0 kg of biomass?</span></span>
<span id="cb9-2"><a href="#cb9-2" tabindex="-1"></a><span class="fu">exp</span>(<span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> <span class="dv">0</span>) <span class="co"># = 35.0</span></span>
<span id="cb9-3"><a href="#cb9-3" tabindex="-1"></a><span class="do">## [1] 34.97206</span></span>
<span id="cb9-4"><a href="#cb9-4" tabindex="-1"></a><span class="co"># On the response scale, how many plants would you predict if a plot had 5 kg of biomass?</span></span>
<span id="cb9-5"><a href="#cb9-5" tabindex="-1"></a><span class="fu">exp</span>(<span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> <span class="dv">5</span>) <span class="co"># = 13.2</span></span>
<span id="cb9-6"><a href="#cb9-6" tabindex="-1"></a><span class="do">## [1] 13.1691</span></span>
<span id="cb9-7"><a href="#cb9-7" tabindex="-1"></a><span class="co"># On the response scale, how many plants would you predict if a plot had 10 kg of biomass?</span></span>
<span id="cb9-8"><a href="#cb9-8" tabindex="-1"></a><span class="fu">exp</span>(<span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> <span class="dv">10</span>) <span class="co"># = 5.0</span></span>
<span id="cb9-9"><a href="#cb9-9" tabindex="-1"></a><span class="do">## [1] 4.958967</span></span></code></pre></div>
<p>8.3. Using this approach, we get a series of snapshot predictions
over different values of Biomass. That’s useful in and of itself, but we
can make this a bit easier for readers to interpret by showing this in a
figure.</p>
<p>To do so, rather copy-and-pasting our equation and substituting in
different value of biomass, why not use <code>R</code> to make this a
bit easier for us?</p>
<p>Let’s start by creating an entirely new dataset that contains a
column called <code>Biomass</code>. If we wanted to, we could just plug
our previous biomass values in but an alternative that gives us more
flexibility would be to use the <code>seq()</code> function to create
any number of <code>Biomass</code> values we desired. All we need to
supply is the minimum and maximum values that we want to consider, and
how many values we want returned to us.</p>
<p>The other thing we need to do is to put this into a dataframe. The
function <code>data.frame()</code> makes this trivially easy. All we
need to do is say what the column is going to be called (here
<code>Biomass</code>) and what the values for the column are. The
<code>seq()</code> function can handle what the values are, so
specifying the column name is all we need to do - and it’s dead easy.
The example below shows all of this done in a single line of
<code>R</code> code.</p>
<pre><code>new_richness <- data.frame(Biomass = seq(from = min(sp$Biomass),
to = max(sp$Biomass),
length.out = 5))</code></pre>
<p>Use this now to create your own “synthetic” data set to do
predictions with.</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb11-1"><a href="#cb11-1" tabindex="-1"></a>new_richness <span class="ot"><-</span> <span class="fu">data.frame</span>(<span class="at">Biomass =</span> <span class="fu">seq</span>(<span class="at">from =</span> <span class="fu">min</span>(sp<span class="sc">$</span>Biomass), </span>
<span id="cb11-2"><a href="#cb11-2" tabindex="-1"></a> <span class="at">to =</span> <span class="fu">max</span>(sp<span class="sc">$</span>Biomass), </span>
<span id="cb11-3"><a href="#cb11-3" tabindex="-1"></a> <span class="at">length.out =</span> <span class="dv">5</span>))</span>
<span id="cb11-4"><a href="#cb11-4" tabindex="-1"></a>new_richness</span>
<span id="cb11-5"><a href="#cb11-5" tabindex="-1"></a><span class="do">## Biomass</span></span>
<span id="cb11-6"><a href="#cb11-6" tabindex="-1"></a><span class="do">## 1 0.300</span></span>
<span id="cb11-7"><a href="#cb11-7" tabindex="-1"></a><span class="do">## 2 3.625</span></span>
<span id="cb11-8"><a href="#cb11-8" tabindex="-1"></a><span class="do">## 3 6.950</span></span>
<span id="cb11-9"><a href="#cb11-9" tabindex="-1"></a><span class="do">## 4 10.275</span></span>
<span id="cb11-10"><a href="#cb11-10" tabindex="-1"></a><span class="do">## 5 13.600</span></span></code></pre></div>
<p>8.4. Once you have this data frame, use it to make 5 simultaneous
predictions of how many plant species we would expect to find, on the
response scale. Store the output in a new column of the
<code>new_richness</code> dataset.</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb12-1"><a href="#cb12-1" tabindex="-1"></a>new_richness<span class="sc">$</span>pred <span class="ot"><-</span> <span class="fu">exp</span>(<span class="fl">3.5545494</span> <span class="sc">+</span> <span class="sc">-</span><span class="fl">0.1953352</span> <span class="sc">*</span> new_richness<span class="sc">$</span>Biomass)</span>
<span id="cb12-2"><a href="#cb12-2" tabindex="-1"></a>new_richness</span>
<span id="cb12-3"><a href="#cb12-3" tabindex="-1"></a><span class="do">## Biomass pred</span></span>
<span id="cb12-4"><a href="#cb12-4" tabindex="-1"></a><span class="do">## 1 0.300 32.981567</span></span>
<span id="cb12-5"><a href="#cb12-5" tabindex="-1"></a><span class="do">## 2 3.625 17.226679</span></span>
<span id="cb12-6"><a href="#cb12-6" tabindex="-1"></a><span class="do">## 3 6.950 8.997707</span></span>
<span id="cb12-7"><a href="#cb12-7" tabindex="-1"></a><span class="do">## 4 10.275 4.699613</span></span>
<span id="cb12-8"><a href="#cb12-8" tabindex="-1"></a><span class="do">## 5 13.600 2.454666</span></span></code></pre></div>
<p>An option available to use is, rather than doing this predictions by
“hand”, we can use a function called <code>predict()</code>. This
function becomes especially useful when we have more complicated models,
where we really don’t want to have to write out the equation by hand,
but also for when we want to make more customised figures. We’ll use
<code>predict()</code> more tomorrow, but for now, let’s use it in this
relatively simple example.</p>
<p>We just need to supply <code>predict()</code> with our new
“synthetic” dataset (i.e. <code>new_richness</code> from above) along
with our model object (e.g. <code>sp.glm1</code>). The code to do so is
then:</p>
<pre><code>pred_plants <- exp(predict(sp.glm1, new_biomass))</code></pre>
<p>8.5. With both this new dataset, create a plot to show our
prediction.</p>
<p>For this, you can either use your “hand made” predictions, or the
predictions using <code>predict()</code>.</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb14-1"><a href="#cb14-1" tabindex="-1"></a><span class="fu">plot</span>(new_richness<span class="sc">$</span>pred <span class="sc">~</span> new_richness<span class="sc">$</span>Biomass)</span>
<span id="cb14-2"><a href="#cb14-2" tabindex="-1"></a><span class="fu">lines</span>(new_richness<span class="sc">$</span>pred <span class="sc">~</span> new_richness<span class="sc">$</span>Biomass)</span></code></pre></div>
<p><img src="GLM_1_Poisson_exercise_solutions_files/figure-html/Q8.5-1.png" width="672" /></p>
<p>And with that, we have a prediction (from our model which we know has
issues). If we stopped here, we’d conclude that biomass has a negative
association with the number of plant species, while also reporting that
this model has a variety of issues.</p>
<p> </p>
<p>8.6. (Optional): The figure we have produced looks pretty jagged. If
we wanted a smoother line to be drawn, how would we do so?</p>
<p> </p>
<div class="sourceCode" id="cb15"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb15-1"><a href="#cb15-1" tabindex="-1"></a><span class="co"># We would simply increase the number of biomass values that our seq() code created. Try it out if you're interested.</span></span></code></pre></div>
<p> </p>
</div>
<div id="including-ph-in-the-model" class="section level3">
<h3>9. Including <code>pH</code> in the model</h3>
<p> </p>
<p>We’ve run a Poisson GLM where <code>Species</code> is explained by
<code>Biomass</code>, but there are two problems. The first is that our
model diagnostics suggested we are not meating our assumptions well. The
second is that our initial research question sought to describe the
relationships between <code>Species</code> with both
<code>Biomass</code> <em>and</em> <code>pH</code>. We might be able to
address both issues with the appropriate model.</p>
<p>Run a <span class="math inline">\(Poisson\)</span> GLM where
<code>Species</code> is a function of <code>Biomass</code> and
<code>pH</code>.</p>
<div class="sourceCode" id="cb16"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb16-1"><a href="#cb16-1" tabindex="-1"></a>sp.glm2 <span class="ot"><-</span> <span class="fu">glm</span>(Species <span class="sc">~</span> Biomass <span class="sc">+</span> pH, </span>
<span id="cb16-2"><a href="#cb16-2" tabindex="-1"></a> <span class="at">family =</span> <span class="fu">poisson</span>(<span class="at">link =</span> <span class="st">"log"</span>), </span>
<span id="cb16-3"><a href="#cb16-3" tabindex="-1"></a> <span class="at">data =</span> sp)</span></code></pre></div>
<p> </p>
</div>
<div id="re-diagnose" class="section level3">
<h3>10. Re-diagnose</h3>
<p> </p>
<p>With every new model we run, we need to diagnose that model. We’ve
already done that once, so let’s quickly do it again.</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 Poisson
distribution?</li>
</ul></li>
<li>Scale-Location
<ul>
<li>What kind of pattern would we expect?</li>
<li>What is the maximum <span class="math inline">\(\sqrt{|Std.
PearsonResid|}\)</span> we would be comfortable with?</li>