-
Notifications
You must be signed in to change notification settings - Fork 0
/
STAT462_Lab4ANSWER.html
1244 lines (1148 loc) · 42.9 KB
/
STAT462_Lab4ANSWER.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>Lab 4: Code showcase</title>
<script src="site_libs/header-attrs-2.11/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/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<script src="site_libs/kePrint-0.0.1/kePrint.js"></script>
<link href="site_libs/lightable-0.0.1/lightable.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;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<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;
}
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 it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.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 {
content: "";
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: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.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">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<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-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">STAT-462</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="T1_R_Basics.html">Tutorials</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Labs
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="STAT462_22_L1Basics.html">Lab 1:R-Basics</a>
</li>
<li>
<a href="STAT462_Lab2.html">Lab 2: Exploratory Data Analysis (EDA)</a>
</li>
<li>
<a href="STAT462_Lab3.html">Lab 3: Scatterplots</a>
</li>
<li>
<a href="STAT462_Lab4.html">Lab 4: Regression Code showcase</a>
</li>
<li>
<a href="STAT462_Lab5.html">Lab 5: LINE Assumptions</a>
</li>
<li>
<a href="STAT462_Lab6.html">Lab 6: Outliers & Transformations</a>
</li>
<li>
<a href="STAT462_Lab7.html">Lab 7: Multiple Regression</a>
</li>
<li>
<a href="STAT462_Lab8.html">Lab 8: Putting it together</a>
</li>
</ul>
</li>
<li>
<a href="STAT462_LabEXAMPLE.html">LAB EXAMPLE</a>
</li>
<li>
<a href="Worked_questions.html">Worked questions</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Lab 4: Code showcase</h1>
<h3 class="subtitle"><h5 style="font-style:normal">
STAT-462 - Regression Analysis
</h4></h3>
<h4 class="author"><h5 style="font-style:normal">
Dr Helen Greatrex
</h4></h4>
</div>
<style>
p.comment {
background-color: #DBDBDB;
padding: 10px;
border: 1px solid black;
margin-left: 0px;
border-radius: 5px;
font-style: normal;
}
h1.title {
font-weight: bold;
font-family: Arial;
}
h2.title {
font-family: Arial;
}
</style>
<style type="text/css">
#TOC {
font-size: 12px;
font-family: Arial;
}
</style>
<p><br />
</p>
<div id="learning-objectives" class="section level1">
<h1>Learning objectives</h1>
<p><strong>It’s nearly spring break, so this lab is one big code showcase to get comfortable with the commands</strong>.</p>
<p>By the end of this week’s lab, you will be able to:</p>
<ol style="list-style-type: decimal">
<li>Feel comfortable reading in and filtering data</li>
<li>Feel comfortable with the core regression commands.</li>
<li>Look at LINE assumptions</li>
</ol>
<p><br></p>
<p class="comment">
<strong>Assignment 4 is due by midnight before spring break.</strong> <a href="https://psu.instructure.com/courses/2174925/assignments/13762850">See here</a> I PROVIDE HELP UNTIL THE END OF NEXT WEEK’S LAB. After next week’s lab (All of Wed night/Thurs/Fri) is for your own finishing up.
</p>
<p><br></p>
<div id="i-need-help" class="section level2">
<h2>I need help</h2>
<ol style="list-style-type: decimal">
<li><p>There is a TEAMS discussion for lab help <a href="https://teams.microsoft.com/l/team/19%3aWabo92vghie-p1jKkmYOGJIOPMUExkoPb0JQMb_9dgw1%40thread.tacv2/conversations?groupId=bbc92dcc-56df-48e6-8da3-5cd766908eeb&tenantId=7cf48d45-3ddb-4389-a9c1-c115526eb52e">CLICK HERE</a>. Remember to include a screenshot of the issue and a short description of the problem. Also try googling the error first.</p></li>
<li><p>Every time you re-open R studio check you are using your project file (does it say Lab 4 at the top?).</p></li>
<li><p>EVERY TIME YOU RE-OPEN R-STUDIO YOU NEED TO RE-RUN <strong>ALL</strong> YOUR CODE CHUNKS. The easiest way to do this is to press the “Run All” button (see the Run menu at the top of your script)</p></li>
<li><p><strong>If the labs are causing major problems or your computer hardware is struggling (or you have any other software issue), Talk to Dr Greatrex</strong>. We can fix this and there are other free/cheap options for using R online.</p></li>
</ol>
<p><br></p>
</div>
</div>
<div id="step1-lab-set-up.-do-not-skip" class="section level1">
<h1>STEP1: Lab set-up. DO NOT SKIP!</h1>
<ol style="list-style-type: decimal">
<li>Create a new project for Lab 4. If you are stuck, see previous labs or <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#21_Projects">Tutorial 2.1</a>.</li>
</ol>
<p><br></p>
<ol start="2" style="list-style-type: decimal">
<li>Copy your lab template to your lab 4 folder, <strong>rename as STAT-462_Lab4_EMAILID.Rmd</strong> (e.g.STAT-462_Lab4_hlg5155.Rmd) and open. THIS LAB IS ONE BIG CODE SHOWCASE. Delete all the headings/subheadings after Code Show case.</li>
</ol>
<p><br></p>
<ol start="3" style="list-style-type: decimal">
<li>In the library section, add a new code chunk and use this code to load the following libraries. <br><br>If some don’t exist on your computer or on the cloud, use <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#23_Adding_a_new_package">Tutorial 2.3</a> to install/download them first.<br><br> To make sure they loaded OK, run the code chunk TWICE. The second time any welcome text will disappear unless there are errors.</li>
</ol>
<pre class="r"><code>library(tidyverse)
library(dplyr)
library(ggpubr)
library(GGally)
library(skimr)
library(ggplot2)
library(plotly)
library(equatiomatic)
library(olsrr)
library(Stat2Data)
library(readxl)
library(yarrr)</code></pre>
<p><br></p>
<ol start="4" style="list-style-type: decimal">
<li>Finally, press knit to check the html works and it looks like this (with your theme)</li>
</ol>
<p><img src="Figures/Lab4_fig1.png" width="1671" style="display: block; margin: auto;" /></p>
<p><br> <br></p>
</div>
<div id="step-2-code-showcase" class="section level1">
<h1>STEP 2: Code showcase</h1>
<p>This lab is a series of mini challenges. For each challenge, please add a new sub-heading to make it easy to grade.</p>
<p><em>You might want to make a second .Rmd file to practice the tutorials, so you can save your practice but only write up what is needed in your report</em></p>
<p>You will need the code from these NEW TUTORIALS:</p>
<ul>
<li><a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#10_Reading_in_and_loading_data">TUTORIAL 10: Reading in data</a></li>
<li><a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#11_Filtering_and_selecting_data">TUTORIAL 11: Filtering/choosing/sub-setting data</a></li>
</ul>
<div id="challenge-1-leaf-analysis" class="section level2">
<h2>Challenge 1: Leaf Analysis</h2>
<p>The aim of this question is to support you with some of the learning objectives of question 4 in the exam.</p>
<ol style="list-style-type: decimal">
<li>Use the data command to load the <code>LeafWidth</code> dataset(make sure you have run the library code chunk first). Look at the help file for the dataset to understand what you are looking at and what the column names mean. In the text, identify the <em>specific</em> unit of analysis.</li>
</ol>
<pre class="r"><code>boxplot(LeafWidth$Year)</code></pre>
<p><img src="STAT462_Lab4ANSWER_files/figure-html/unnamed-chunk-4-1.png" width="672" /></p>
<pre class="r"><code>boxplot(LeafWidth$Length)</code></pre>
<p><img src="STAT462_Lab4ANSWER_files/figure-html/unnamed-chunk-4-2.png" width="672" /></p>
<pre class="r"><code>shapiro.test(LeafWidth$Year)</code></pre>
<pre><code>##
## Shapiro-Wilk normality test
##
## data: LeafWidth$Year
## W = 0.85624, p-value = 1.412e-14</code></pre>
<pre class="r"><code>shapiro.test(LeafWidth$Length)</code></pre>
<pre><code>##
## Shapiro-Wilk normality test
##
## data: LeafWidth$Length
## W = 0.98691, p-value = 0.02123</code></pre>
<pre class="r"><code># one sided test
# </code></pre>
<p>You are looking at two variables: a. Year the leaves were collected b. Average length of each leaf (in mm)</p>
<ol start="2" style="list-style-type: decimal">
<li><p>For <strong>EACH of the two variables above</strong></p>
<ol style="list-style-type: lower-alpha">
<li>Create a professional looking boxplot <br>
<ul>
<li>with either title or axis title</li>
</ul></li>
<li>Below the boxplot, write whether you believe the variable is likely to be Normally distributed and why. <br></li>
<li>Add a guess of a p-value in a Wilk-Shapiro test. (you are not being graded on whether your answer is ‘correct’) <br></li>
<li>Formally assess the normality of the variable using a Wilk-Shapiro test at a critical value of 5%. Include your H0, H1 and your conclusions. Write a comment on whether the result matches your guess. (you could also have a look at a histogram). <br>
<ul>
<li>H0, H1, to either refer or use the numbers in the output and conclusions</li>
</ul></li>
</ol></li>
<li><p>Is the Wilk-Shapiro test one-sided or two-sided? (google it!)<br />
</p></li>
</ol>
<ul>
<li>one sided</li>
</ul>
<ol start="4" style="list-style-type: decimal">
<li>Someone adds a new leaf to the dataset. Calculate the range of lengths are you 99% sure the new leaf will have.</li>
</ol>
<pre class="r"><code># prediction interval
ybar <- mean(LeafWidth$Length)
sy <- sd(LeafWidth$Length)
n <- nrow(LeafWidth)
lowerPI <- ybar - qt(0.995,n-1)*(sy*(sqrt( (1+ (1/n)))))
upperPI <- ybar + qt(0.995,n-1)*(sy*(sqrt( (1+ (1/n)))))
lowerPI</code></pre>
<pre><code>## [1] 27.10081</code></pre>
<pre class="r"><code>upperPI</code></pre>
<pre><code>## [1] 92.57546</code></pre>
<ol start="5" style="list-style-type: decimal">
<li>Someone collects a whole new sample from your population. Given your data, what is your estimate of their average leaf length, with a 95% level of certainty.</li>
</ol>
<pre class="r"><code># confidence interval
ybar <- mean(LeafWidth$Length)
sy <- sd(LeafWidth$Length)
n <- nrow(LeafWidth)
lowerCI <- ybar - qt(0.975,n-1)*(sy/(sqrt(n)))
upperCI <- ybar + qt(0.975,n-1)*(sy/(sqrt(n)))
lowerCI</code></pre>
<pre><code>## [1] 58.27643</code></pre>
<pre class="r"><code>upperCI</code></pre>
<pre><code>## [1] 61.39984</code></pre>
<pre class="r"><code>t.test(LeafWidth$Length)</code></pre>
<pre><code>##
## One Sample t-test
##
## data: LeafWidth$Length
## t = 75.462, df = 251, p-value < 2.2e-16
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
## 58.27643 61.39984
## sample estimates:
## mean of x
## 59.83814</code></pre>
<ol start="6" style="list-style-type: decimal">
<li>Given the Wilk-Shapiro test results above, would it have been appropriate to calculate the ranges from [4] and [5] for a variable as skewed as ‘the year the leaves were collected?’ Explain your answer. (Hint Lecture 9)</li>
</ol>
<p><em>You can use a confidence interval cos clt, but vastly inappropriate to use your model for prediction or prediction intervals.)</em></p>
</div>
<div id="challenge-2-filtering-data" class="section level2">
<h2>Challenge 2: Filtering Data</h2>
<p>You might find <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#11_Filtering_and_selecting_data">TUTORIAL 11: Filtering/choosing/sub-setting data</a> useful (the code is in there!).</p>
<pre class="r"><code>data("pirates", package = "yarrr")
piratenew <- dplyr::filter(pirates,parrots > 3)
mean(piratenew$tattoos)</code></pre>
<pre><code>## [1] 9.033962</code></pre>
<ol style="list-style-type: decimal">
<li><p>Load the <code>pirates</code> dataset from the <code>yarrr</code> package. Take a look at it and the help file.</p></li>
<li><p>Select the value of the pirates dataset for the 15th row and 4th column (I need to see the R code!)</p></li>
<li><p>Filter the full pirates data so that it just includes pirates with more than 3 parrots and save to a new variable (see the tutorial..).</p>
<ol style="list-style-type: lower-alpha">
<li>What is the average number of tattoos of pirates with more than 3 parrots</li>
<li>How many 3+ parrot owning, <em>male</em> pirates <em>also</em> have more than 3 tattoos.</li>
</ol></li>
<li><p>Remove the 17th row and overwrite</p></li>
<li><p>Remove the row containing the tallest pirate (let’s say the data was entered incorrectly)</p></li>
</ol>
</div>
<div id="challenge-3-public-safety-spending" class="section level2">
<h2>Challenge 3: Public safety spending</h2>
<p><em>Suburban towns often spend a large fraction of their municipal budgets on public safety services (police, fire, and ambulance). A taxpayers’ group felt that tiny towns were likely to spend large amounts per person because they have such small financial bases. The group obtained data on the per-capita (per-person) spending on public safety for 29 suburban towns in a metropolitan area, as well as the population of each town in units of 1000 people. If you used 10000 thats fine </em></p>
<p>They sent you the data in the file <code>expenditure.xslx</code>, which you can get from Canvas.</p>
<pre class="r"><code>exp <- read_excel("expenditure copy.xlsx")
exp</code></pre>
<pre><code>## # A tibble: 29 × 2
## Population Expend
## <dbl> <dbl>
## 1 14 140
## 2 20 142
## 3 22 165
## 4 22 175
## 5 24 143
## 6 24 141
## 7 26 142
## 8 28 144
## 9 29 144.
## 10 30 138
## # … with 19 more rows</code></pre>
<ol style="list-style-type: decimal">
<li>Download this from canvas and put it into your lab 4 folder. If you are on the cloud, just download it for now (see step 2)</li>
</ol>
<p>BEFORE you read a file into R, it is good to look at column names. It’s very frustrating in R when column names have spaces, special characters or anything else that is difficult to type. It makes it especially hard to refer to a column/variable by name, e.g. table$columnname. You <em>can</em> change this in R using the <code>names()</code> command. But <em>much easier</em> is to fix the issue BEFORE reading it into R. So:</p>
<ol start="2" style="list-style-type: decimal">
<li><p>Open <code>expenditure.xlsx</code> in Excel and take a look! Rename the column titles so that no column names contains spaces/special characters & check you are happy with the data. Save and close. If you are on the cloud, upload to your Lab 4 project.</p></li>
<li><p>Use <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#10_Reading_in_and_loading_data">TUTORIAL 10: Reading in data</a> to read it into R.</p></li>
<li><p>Use inline code to write a sentence in your report telling me the number of towns in the sample and the average population of the sampled towns. (See Lab 3 / <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#48_Inline_code">Tutorial 4.8, Inline code</a>). Summarize what the aim of the study is (see above), the unit of analysis, the response and predictor variables and what the taxpayer’s group expects the results to be.</p></li>
</ol>
<pre class="r"><code>skimr::skim(exp)</code></pre>
<table style="width: auto;" class="table table-condensed">
<caption>
Data summary
</caption>
<thead>
<tr>
<th style="text-align:left;">
</th>
<th style="text-align:left;">
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;">
Name
</td>
<td style="text-align:left;">
exp
</td>
</tr>
<tr>
<td style="text-align:left;">
Number of rows
</td>
<td style="text-align:left;">
29
</td>
</tr>
<tr>
<td style="text-align:left;">
Number of columns
</td>
<td style="text-align:left;">
2
</td>
</tr>
<tr>
<td style="text-align:left;">
_______________________
</td>
<td style="text-align:left;">
</td>
</tr>
<tr>
<td style="text-align:left;">
Column type frequency:
</td>
<td style="text-align:left;">
</td>
</tr>
<tr>
<td style="text-align:left;">
numeric
</td>
<td style="text-align:left;">
2
</td>
</tr>
<tr>
<td style="text-align:left;">
________________________
</td>
<td style="text-align:left;">
</td>
</tr>
<tr>
<td style="text-align:left;">
Group variables
</td>
<td style="text-align:left;">
None
</td>
</tr>
</tbody>
</table>
<p><strong>Variable type: numeric</strong></p>
<table>
<thead>
<tr>
<th style="text-align:left;">
skim_variable
</th>
<th style="text-align:right;">
n_missing
</th>
<th style="text-align:right;">
complete_rate
</th>
<th style="text-align:right;">
mean
</th>
<th style="text-align:right;">
sd
</th>
<th style="text-align:right;">
p0
</th>
<th style="text-align:right;">
p25
</th>
<th style="text-align:right;">
p50
</th>
<th style="text-align:right;">
p75
</th>
<th style="text-align:right;">
p100
</th>
<th style="text-align:left;">
hist
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;">
Population
</td>
<td style="text-align:right;">
0
</td>
<td style="text-align:right;">
1
</td>
<td style="text-align:right;">
35.19
</td>
<td style="text-align:right;">
12.98
</td>
<td style="text-align:right;">
14
</td>
<td style="text-align:right;">
28
</td>
<td style="text-align:right;">
32
</td>
<td style="text-align:right;">
40
</td>
<td style="text-align:right;">
76
</td>
<td style="text-align:left;">
▃▇▃▁▁
</td>
</tr>
<tr>
<td style="text-align:left;">
Expend
</td>
<td style="text-align:right;">
0
</td>
<td style="text-align:right;">
1
</td>
<td style="text-align:right;">
140.78
</td>
<td style="text-align:right;">
37.59
</td>
<td style="text-align:right;">
70
</td>
<td style="text-align:right;">
135
</td>
<td style="text-align:right;">
138
</td>
<td style="text-align:right;">
142
</td>
<td style="text-align:right;">
310
</td>
<td style="text-align:left;">
▁▇▁▁▁
</td>
</tr>
</tbody>
</table>
<ol start="5" style="list-style-type: decimal">
<li><em>If the taxpayer’s group is correct</em>, write (in a full sentence) whether you think the slope of Simple Linear regression model between your response and predictor should be negative or positive?</li>
</ol>
<p>“A taxpayers’ group felt that tiny towns were likely to spend large amounts per person because they have such small financial bases.” <em>should be negative</em></p>
<ol start="6" style="list-style-type: decimal">
<li>Make a professional looking scatter-plot of your response and predictor (good enough to give to the taxpayers group). Describe it fully using this to help (<a href="https://www.khanacademy.org/math/ap-statistics/bivariate-data-ap/scatterplots-correlation/a/describing-scatterplots-form-direction-strength-outliers?modal=1">KHAN SCATTER DESCRIPTIONS:</a>)</li>
</ol>
<pre class="r"><code>plot(exp,col="red",pch=16)</code></pre>
<p><img src="STAT462_Lab4ANSWER_files/figure-html/unnamed-chunk-10-1.png" width="672" /></p>
<ol start="7" style="list-style-type: decimal">
<li>Use <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#9_Regression_models">Tutorial 9</a> to fit a regression model to the data and save it as a variable called <code>model1</code>. Examine the coefficients and the summary of the model fit using OLSRR (in the tutorial).</li>
</ol>
<pre class="r"><code>model1 <- lm(Expend ~Population,data=exp)</code></pre>
<pre class="r"><code>ols_regress(Expend ~Population,data=exp)</code></pre>
<pre><code>## Model Summary
## -----------------------------------------------------------------
## R 0.227 RMSE 37.279
## R-Squared 0.052 Coef. Var 26.480
## Adj. R-Squared 0.017 MSE 1389.758
## Pred R-Squared -0.905 MAE 19.972
## -----------------------------------------------------------------
## RMSE: Root Mean Square Error
## MSE: Mean Square Error
## MAE: Mean Absolute Error
##
## ANOVA
## --------------------------------------------------------------------
## Sum of
## Squares DF Mean Square F Sig.
## --------------------------------------------------------------------
## Regression 2044.358 1 2044.358 1.471 0.2357
## Residual 37523.464 27 1389.758
## Total 39567.821 28
## --------------------------------------------------------------------
##
## Parameter Estimates
## -----------------------------------------------------------------------------------------
## model Beta Std. Error Std. Beta t Sig lower upper
## -----------------------------------------------------------------------------------------
## (Intercept) 117.614 20.318 5.789 0.000 75.925 159.304
## Population 0.658 0.543 0.227 1.213 0.236 -0.455 1.772
## -----------------------------------------------------------------------------------------</code></pre>
<ol start="8" style="list-style-type: decimal">
<li>In the text of your report, write formally write the model equation either using the equation knowledge from labs 2/3 or equatiomatic to extract the equation for the model as described in <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#9_Regression_models">Tutorial 9</a>.</li>
</ol>
</div>
</div>
<div id="use-greek-letter-or-equation-format-units.." class="section level1">
<h1>use greek letter or equation format, units..</h1>
<pre class="r"><code>extract_eq(model1,use_coefs = T)</code></pre>
<p><span class="math display">\[
\operatorname{\widehat{Expend}} = 117.61 + 0.66(\operatorname{Population})
\]</span></p>
<ol start="8" style="list-style-type: decimal">
<li><p>Explain the slope and intercept within the context of the data. Explain if the slope in the output confirms the opinion of the community group?</p></li>
<li><p>Add the line of best fit to a new version of the scatter-plot. Explain why this initial regression might be misleading.</p></li>
</ol>
<pre class="r"><code>plot(exp,col="red",pch=16)
abline(model1)</code></pre>
<p><img src="STAT462_Lab4ANSWER_files/figure-html/unnamed-chunk-14-1.png" width="672" /></p>
<ol start="10" style="list-style-type: decimal">
<li>Use Tutorial 11 to remove the outlier. Repeat the linear regression and scatter-plot with the new data and save it as a variable called <code>model2</code>. Explain how this has changed your assessment of the relationship between the variables.</li>
</ol>
<pre class="r"><code>exp2 <- filter(exp, Expend < 250)
model2 <- lm(Expend ~Population,data=exp2)
ols_regress(Expend ~Population,data=exp2)</code></pre>
<pre><code>## Model Summary
## ---------------------------------------------------------------
## R 0.743 RMSE 13.060
## R-Squared 0.553 Coef. Var 9.692
## Adj. R-Squared 0.535 MSE 170.551
## Pred R-Squared 0.429 MAE 8.473
## ---------------------------------------------------------------
## RMSE: Root Mean Square Error
## MSE: Mean Square Error
## MAE: Mean Absolute Error
##
## ANOVA
## --------------------------------------------------------------------
## Sum of
## Squares DF Mean Square F Sig.
## --------------------------------------------------------------------
## Regression 5476.351 1 5476.351 32.11 0.0000
## Residual 4434.336 26 170.551
## Total 9910.687 27
## --------------------------------------------------------------------
##
## Parameter Estimates
## -------------------------------------------------------------------------------------------
## model Beta Std. Error Std. Beta t Sig lower upper
## -------------------------------------------------------------------------------------------
## (Intercept) 180.381 8.424 21.412 0.000 163.065 197.698
## Population -1.353 0.239 -0.743 -5.667 0.000 -1.844 -0.862
## -------------------------------------------------------------------------------------------</code></pre>
<pre class="r"><code>plot(exp2,col="red",pch=16)
abline(model2)</code></pre>
<p><img src="STAT462_Lab4ANSWER_files/figure-html/unnamed-chunk-15-1.png" width="672" /></p>
<ol start="11" style="list-style-type: decimal">
<li>Normally, to calculate the correlation coefficient between two variables, we use the <code>cor()</code> command or we could look at the output from <code>ols_regress()</code>. Let’s imagine that these have mysteriously broken. From only the information provided in the command <code>summary(model2)</code>, explain how you can quickly calculate the correlation coefficient and state what it is.</li>
</ol>
<pre class="r"><code>summary(model2)</code></pre>
<pre><code>##
## Call:
## lm(formula = Expend ~ Population, data = exp2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -40.022 -3.450 2.020 4.682 24.386
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 180.3812 8.4243 21.412 < 2e-16 ***
## Population -1.3531 0.2388 -5.667 5.84e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 13.06 on 26 degrees of freedom
## Multiple R-squared: 0.5526, Adjusted R-squared: 0.5354
## F-statistic: 32.11 on 1 and 26 DF, p-value: 5.844e-06</code></pre>
<pre class="r"><code>sqrt(0.5526)</code></pre>
<pre><code>## [1] 0.7433707</code></pre>
<ol start="12" style="list-style-type: decimal">
<li>Look at the ANOVA table (middle part of <code>ols_regress(model2)</code> or <code>anova(model2)</code>). Using the information provided there, calculate the R<sup>2</sup> value.</li>
</ol>
<pre class="r"><code>ols_regress(model2)</code></pre>
<pre><code>## Model Summary
## ---------------------------------------------------------------
## R 0.743 RMSE 13.060
## R-Squared 0.553 Coef. Var 9.692
## Adj. R-Squared 0.535 MSE 170.551
## Pred R-Squared 0.429 MAE 8.473
## ---------------------------------------------------------------
## RMSE: Root Mean Square Error
## MSE: Mean Square Error
## MAE: Mean Absolute Error
##
## ANOVA
## --------------------------------------------------------------------
## Sum of
## Squares DF Mean Square F Sig.
## --------------------------------------------------------------------
## Regression 5476.351 1 5476.351 32.11 0.0000
## Residual 4434.336 26 170.551
## Total 9910.687 27
## --------------------------------------------------------------------
##
## Parameter Estimates
## -------------------------------------------------------------------------------------------
## model Beta Std. Error Std. Beta t Sig lower upper
## -------------------------------------------------------------------------------------------
## (Intercept) 180.381 8.424 21.412 0.000 163.065 197.698
## Population -1.353 0.239 -0.743 -5.667 0.000 -1.844 -0.862
## -------------------------------------------------------------------------------------------</code></pre>
<pre class="r"><code>#Multiple R-squared: 0.5526,</code></pre>
<ol start="13" style="list-style-type: decimal">
<li>Test if the slope is significantly different to 1 (Monday-28 lecture). Show all your workings and professionally format any equations. Note, I mean is it different to 1! For half marks, you can test if it is different to zero.</li>
</ol>
<pre class="r"><code>-1.3531 - 1 / (0.2388)</code></pre>
<pre><code>## [1] -5.540705</code></pre>
<p><br></p>
<div id="challenge-4-mystery-data" class="section level2">
<h2>Challenge 4: Mystery data</h2>
<ol style="list-style-type: decimal">
<li><p>Download the mystery dataset from canvas into your lab 4 folder.</p></li>
<li><p>Read it into R using <a href="https://psu-spatial.github.io/stat462-2022/T1_R_Basics.html#10_Reading_in_and_loading_data">TUTORIAL 10: Reading in data</a> and calculate the correlation coefficient.</p></li>
<li><p>Explain why this correlation coefficient is vastly inappropriate!</p></li>
</ol>
<pre class="r"><code>mystery <- read.csv("MysteryData.csv")
cor(mystery)</code></pre>
<pre><code>## x y
## x 1.0000000 -0.5560607
## y -0.5560607 1.0000000</code></pre>
<pre class="r"><code>plot(mystery,asp=1)</code></pre>
<p><img src="STAT462_Lab4ANSWER_files/figure-html/unnamed-chunk-19-1.png" width="672" /></p>
<p>There is no show me something new this lab.</p>
</div>
</div>
<div id="submitting-your-lab" class="section level1">
<h1>Submitting your Lab</h1>
<p>Remember to save your work throughout and to spell check your writing (next to the save button).</p>
<p>Now, press the knit button for the final time.</p>
<p>If you have not made any mistakes in the code then R should create a html file in your lab 4 folder which includes your answers. If you look at your lab 4 folder, you should see this there - complete with a very recent time-stamp.</p>