forked from PeterKDunn/SRM-Textbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
37-Regression.Rmd
1620 lines (1249 loc) · 62.7 KB
/
37-Regression.Rmd
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
# Regression {#Regression}
<!-- Introductions; easier to separate by format -->
```{r, child = if (knitr::is_html_output()) {'./introductions/37-Regression-HTML.Rmd'} else {'./introductions/37-Regression-LaTeX.Rmd'}}
```
```{r}
data(RedDeer)
```
## Introduction {#Chap35-Intro}
The last chapter introduced *correlation*, which measures the *strength* of the *linear* relationship between two quantitative variables $x$ (an explanatory variable) and $y$ (a response variable).
We now study *regression*, which describes *what* the linear relationship is between $x$ and $y$.
The relationship is described using an *equation*, which allows us to:
1. *Predict* values of $y$ from given values of $x$ (Sect. \@ref(RegressionForPrediction)); and
2. *Understand* the relationship between $x$ and $y$ (Sect. \@ref(RegressionForUnderstanding)).
An example of a linear regression equation, describing the relationship between an explanatory variable $x$ and a response variable $y$, is
\[
\hat{y} = -4 + (2\times x), \qquad\text{usually written}\qquad \hat{y} = -4 + 2x.
\]
The notation $\hat{y}$ refers to the *mean predicted* value of the response variable given a value of $x$.
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
$y$ refers to the observed data, whose values are known.
$\hat{y}$ refers to *mean predicted* (not observed) values of $y$ for some given value of $x$.
:::
:::: {.pronounceBox .pronounce data-latex="{iconmonstr-microphone-7-240.png}"}
$\hat{y}$ is pronounced as 'why-hat'; the 'caret' above the $y$ is called a 'hat', and designates a *predicted* value (of $y$).
:::
More generally, the equation of a straight line is
\[
\hat{y} = b_0 + (b_1 \times x), \qquad\text{usually written}\qquad \hat{y} = b_0 + b_1 x
\]
where $b_0$ and $b_1$ are (unknown) numbers estimated from sample data.
Notice that $b_1$ is the number multiplied by $x$.
In the example above, $b_0 = -4$ and $b_1 = 2$.
::: {.example #RegressionEquations name="Regression equations"}
If $\hat{y} = 15 - 102x$, then $b_0 = 15$ and $b_1 = -102$.
:::
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
Consider the regression equation $\hat{y} = -0.0047x + 2.1$.\label{thinkBox:RegressionCoefs}
What are the values of $b_0$ and $b_1$?
(Be careful!)
`r if (knitr::is_latex_output()) '<!--'`
`r webexercises::hide()`
$b_0 = 2.1$ and $b_1 = -0.0047$.
Remember: $b_1$ is the number multiplied by the $x$, and that $b_0$ is the number by itself.
Some software and some journal papers write regression equations with the value of $b_0$ first, and some with the value of $b_1$ first.
The *order* is not important.
`r webexercises::unhide()`
`r if (knitr::is_latex_output()) '-->'`
:::
## Linear equations: review {#RegressionEquationsReview}
To introduce, or revise, the idea of a linear equation, consider the (artificial) data in
`r if (knitr::is_latex_output()) {
'Fig. \\@ref(fig:ExampleScatterLATEX) (left panel),'
} else {
'Fig. \\@ref(fig:ExampleScatterHTML),'
}`
with an explanatory variable $x$ and a response variable $y$.
In the regression equation $\hat{y} = b_0 + b_1 x$, the numbers $b_0$ and $b_1$ are called *regression coefficients*, where
* $b_0$ is called the *intercept*.
Its value corresponds to the *predicted* mean value of $y$ when $x = 0$.
* $b_1$ is the *slope*.
It measures how much the value of $y$ changes, on average, when the value of $x$ *increases* by 1.
We will use software to find the values of $b_0$ and $b_1$ (the formulas are tedious to use).
A rough approximation of the value of the *intercept* can be made by drawing a sensible-looking straight line through the scatterplot of the data, and determining what that line predicts for the value of $y$ when $x = 0$.
Also, a rough approximation of the *slope* can be made by computing
\[
\text{approximate slope}
= \frac{\text{Change in $y$}}{\text{Corresponding change in $x$}}
= \frac{\text{rise}}{\text{run}}.
\]
This approximation of the slope is the *change* in the value of $y$ (the 'rise') divided by the corresponding *change* in the value of $x$ (the 'run').
In
`r if (knitr::is_latex_output()) {
'Fig. \\@ref(fig:ExampleScatterLATEX) (left panel),'
} else {
'Fig. \\@ref(fig:ExampleScatterHTML),'
}`
I have drawn a sensible line on the graph to capture the relationship (your line may look a little different).
When $x = 0$, the regression line predicts the value of $y$ to be about $2$, so $b_0$ is approximately $2$.
To approximate the slope, use the 'rise over run'
`r if (knitr::is_latex_output()) {
'idea (Fig. \\@ref(fig:ExampleScatterLATEX), right panel; the online version has an animation).'
} else {
'idea; the animation below may help explain.'
}`
When the value of $x$ increases from $1$ to $5$ (a change of $5 - 1 = 4$), the corresponding value of $y$ changes from 5 to 17 (a change of $17 - 5 = 12$).
So:
\[
\frac{\text{rise}}{\text{run}}
= \frac{17 - 5}{5 - 1}
= \frac{12}{4}
= 3.
\]
The value of $b_1$ is about $3$.
The regression line is approximately $\hat{y} = 2 + (3\times x)$, usually written
\[
\hat{y} = 2 + 3x.
\]
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
The regression equation has $\hat{y}$ (not $y$) on the left-hand side.
That is, the equation *predicts* the mean values of $y$, which may not be equal to the observed values (which are denoted by $y$).
A 'good' regression equation would produce predicted values $\hat{y}$ close to the observed values $y$; that is, the lines passes close to each point on the scatterplot.
:::
The *intercept* has the same measurement units as the response variable.
The measurement unit for the *slope* is the 'measurement units of the response variable', per 'measurement units of the explanatory variable'.
:::{.example name="Measurement units for intercept and slope"}
For the red-deer data, explanatory variable is age (in years), and the response variable is molar weight (in g).
Hence, the intercept $b_0$ is measured in grams, and the slope $b_1$ is measured in grams per year.
:::
<!-- FOR LaTeX: Put this example data plot and the static rise/run in the same plot -->
<!-- FOT HTML, separate plots -->
```{r ExampleScatterHTML, fig.cap="An example scatterplot", fig.align="center", fig.width=5, fig.height=4}
if (knitr::is_html_output()){
set.seed(5000)
x <- seq(0.5, 5,
length = 10)
mu <- 2 + 3 * x
y <- mu + rnorm(length(x), 0, 0.5)
m1 <- lm(y ~ x)
plot(y ~ x,
xlim = c(0, 5),
ylim = c(0, 20),
las = 1,
xlab = expression(paste("Explanatory, ", italic(x)) ),
ylab = expression(paste("Response, ", italic(y)) ),
pch = 19)
grid()
abline( coef(m1),
col = "grey",
lwd = 2)
}
```
```{r AnimateRiseRun, animation.hook="gifski", interval=0.85, dev=if (is_latex_output()){"pdf"}else{"png"}}
if (knitr::is_html_output()){
NumPlots <- 9
set.seed(5000)
x <- seq(0.5, 5,
length = 10)
b0 <- 2
b1 <- 3
mu <- b0 + b1 * x
y <- mu + rnorm(length(x), 0, 0.5)
x1 <- 1
x2 <- 5
y1 <- b0 + (b1 * x1)
y2 <- b0 + (b1 * x2)
for (i in (1:NumPlots)){
par( mar = c(5, 4, 4, 2) + 0.1)
# DATA
plot(y ~ x,
xlim = c(0, 5),
ylim = c(0, 20),
type = "n",
las = 1,
xlab = expression(paste("Explanatory, ", italic(x)) ),
ylab = expression(paste("Response, ", italic(y)) ),
pch = 19)
rug(1:20,
side = 2,
ticksize = -0.02)
grid()
points(y ~ x,
pch = 19)
if ( i >=2 ){ # DATA + LINE
abline(b0, b1,
col = "red",
lwd = 2)
}
if (i >= 3) { # DATA + LINE + x1
lines( c(x1, x1),
c(0, y1),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if ( i >= 4){ # DATA + LINE + x1 + y1
lines( c(0, x1),
c(y1, y1),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if ( i >= 5 ){ # DATA + LINE + x1 + y1 + x2
lines( c(x2, x2),
c(0, y2),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if ( i >= 6) { # DATA + LINE + x1 + y1 + x2 + y2
lines( c(0, x2),
c(y2, y2),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if (i >= 7 ) { # DATA + LINE + x1 + y1 + x2 + y2 + RUN
run <- x2 - x1
arrows(x1, 2,
x2, 2,
lwd = 2,
length = 0.15,
col = "darkgrey",
code = 2)
text( mean( c(x1, x2)), 2.5,
labels = bquote("Run: "~ .(x2)-.(x1) == .(run)),
pos = 2 )
}
if (i >= 8 ){ # DATA + LINE + x1 + y1 + x2 + y2 + RUN + RISE
rise <- y2 - y1
arrows(0.5, y1,
0.5, y2,
lwd = 2,
length = 0.15,
col = "darkgrey",
code = 2)
text( 0.5,
mean( c(y1, y2)),
labels = bquote("Rise: "~ .(y2)-.(y1) == .(rise)),
pos = 4 )
}
if (i >= 9 ) { # DATA + LINE + x1 + y1 + x2 + y2 + RUN + RISE + SLOPE
slope <- rise / run
polygon( c(2.15, 2.15, 4.85, 4.85),
c(6, 8, 8, 6),
border = NA, # No border
col = "antiquewhite1")
text(3.5,
7,
labels = bquote("Slope: "~ .(rise) %/% .(run) == .(slope)) )
}
}
}
```
<!-- FOR LaTeX: Put this example data plot and the static rise/run in the same plot -->
```{r ExampleScatterLATEX, fig.cap="An example scatterplot. Left: Approximating $b_0$; right: approximating $b_1$ using rise-over-run", fig.align="center", fig.width=9, fig.height=4, out.width='100%'}
set.seed(5000)
x <- seq(0.5, 5,
length = 10)
mu <- 2 + 3 * x
y <- mu + rnorm(length(x), 0, 0.5)
m1 <- lm(y ~ x)
if (knitr::is_latex_output()){
par(mfrow = c(1, 2))
plot(y ~ x,
xlim = c(0, 5),
ylim = c(0, 20),
las = 1,
main = expression(Approximating~italic(b)[0]),
xlab = expression(Explanatory~italic(x) ),
ylab = expression(Response~italic(y) ),
pch = 19,
col = "grey")
grid()
rug(1:20,
side = 2,
ticksize = -0.02)
abline( coef(m1),
col = "black",
lwd = 2)
# Beta 0
abline(v = 0,
lwd = 2,
col = "grey")
lines( x = c(0, 0),
y = c(0, coef(m1)[1]),
lty = 1,
lwd = 2,
col = "grey")
lines( x = c(-1, 0.45),
y = c(coef(m1)[1], coef(m1)[1]),
lty = 1,
lwd = 2,
col = "grey")
arrows(x0 = 2,
x1 = 0.5,
y0 = 2,
y1 = coef(m1)[1],
angle = 15,
length = 0.25,
lwd = 2)
text(x = 2,
y = 2,
pos = 4,
labels = expression(Approximately~italic(b)[0]))
######
b0 <- 2
b1 <- 3
x1 <- 1
x2 <- 5
y1 <- b0 + (b1 * x1)
y2 <- b0 + (b1 * x2)
NumPlots <- i <- 9
# for (i in (NumPlots:NumPlots)){
# DATA
plot(y ~ x,
xlim = c(0, 5),
ylim = c(0, 20),
type = "n",
las = 1,
main = expression(Approximating~italic(b)[1]),
xlab = expression(Explanatory~italic(x) ),
ylab = expression(Response~italic(y) ),
pch = 19)
rug(1:20,
side = 2,
ticksize = -0.02)
grid()
points(y ~ x,
pch = 19)
if ( i >=2 ){ # DATA + LINE
abline(b0, b1,
col = "red",
lwd = 2)
}
if (i >= 3) { # DATA + LINE + x1
lines( c(x1, x1),
c(0, y1),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if ( i >= 4){ # DATA + LINE + x1 + y1
lines( c(0, x1),
c(y1, y1),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if ( i >= 5 ){ # DATA + LINE + x1 + y1 + x2
lines( c(x2, x2),
c(0, y2),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if ( i >= 6) { # DATA + LINE + x1 + y1 + x2 + y2
lines( c(0, x2),
c(y2, y2),
lwd = 2,
col = "darkgrey",
lty = 2)
}
if (i >= 7 ) { # DATA + LINE + x1 + y1 + x2 + y2 + RUN
run <- x2 - x1
arrows(x1, 2,
x2, 2,
lwd = 2,
length = 0.15,
col = "darkgrey",
code = 2)
text( mean( c(x1, x2)),
2,
labels = bquote("Run: "~ .(x2)-.(x1) == .(run)),
pos = 3 )
}
if (i >= 8 ){ # DATA + LINE + x1 + y1 + x2 + y2 + RUN + RISE
arrows(0.5, y1,
0.5, y2,
lwd = 2,
length = 0.15,
col = "darkgrey",
code = 2)
rise <- y2 - y1
text( 0.5,
mean( c(y1, y2)) + 0.5,
labels = bquote("Rise: "~ .(y2)-.(y1) == .(rise)),
pos = 4 )
}
# }
}
```
`r if (knitr::is_html_output()){
'You may like the following interactive activity, which explores slopes and intercepts.'}`
<iframe src="https://phet.colorado.edu/sims/html/graphing-slope-intercept/latest/graphing-slope-intercept_en.html" width="600" height="450" scrolling="no" allowfullscreen="allowfullscreen"></iframe>
::: {.example #CycloneRegressionGuesses name="Estimating regression parameters"}
The relationship [@mypapers:dunnsmyth:glms] between the number of cyclones $y$ in the Australian region each year from 1969 to 2005, and a climatological index called the *Ocean `r readr::parse_character( c("Niño"), locale=locale(encoding="UTF-8"))` Index* (ONI, $x$), is shown in Fig. \@ref(fig:ONIcyclones).
When the value of $x$ is zero, the predicted value of $y$ is about $12$; $b_0$ is about $12$.
(You may get something slightly different.)
Notice that the intercept is the *predicted* value of $y$ when $x = 0$, which is *not* at the left of the graph.
To approximate the value of $b_1$, use the 'rise over run' idea.
When $x$ is about $-2$, the predicted value of $y$ is about $17$; when $x$ is about $2$, the predicted value of $y$ is about $8$.
The value of $x$ increases by $2 - (-2) = 4$, while the value of $y$ changes by $8 - 17 = -9$ (a *decrease* of about $9$).
Hence, $b_1$ is approximately $-9/4 = -2.25$.
(You may get something slightly different.)
The relationship has a *negative* direction, so the slope must be *negative*.
The regression line is approximately $\hat{y} = 12 - 2.25x$.
:::
```{r ONIcyclones, fig.width=4, fig.align="center", fig.cap="The number of cyclones in the Australian region each year from 1969 to 2005, and the ONI for October, November, December", fig.width=5, fig.height=4}
data(Cyclones)
plot(Total ~ OND,
data = Cyclones,
xlim = c(-2, 3),
ylim = c(0, 20),
pch = 19,
ylab = "Total number of cyclones",
xlab = "ONI averaged over Oct., Nov., Dec.",
las = 1)
clm <- lm( Total ~ OND,
data = Cyclones)
abline( coef(clm),
lwd = 2,
col = "grey")
grid(lty = 2)
```
The above method gives a crude approximation to the values of the intercept $b_0$ and the slope $b_1$.
In practice, *many* reasonable lines could be drawn through a scatterplot of data.
However, one of those lines is the 'best' line in some sense^[For those interested: The 'line of best fit' is the line for which the sum of the *squared* vertical distances between the observations $y$ and the predicted values $\hat{y}$ (i.e, the regression line) is as small as possible.].
Software calculates this 'line of best fit' for us.
<iframe src="https://learningapps.org/watch?v=p84zyy2ot22" style="border:0px;width:100%;height:800px" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>
## Regression using software {#Regression-Software}
The regression line, explained above, is computed from the observed sample data.
This assumes that a regression equation exists in the population that is being estimated using the sample information.
In the population, the intercept is denoted by $\beta_0$ and the slope by $\beta_1$.
These population values are unknown, and are estimated by the statistics $b_0$ and $b_1$ respectively.
:::: {.pronounceBox .pronounce data-latex="{iconmonstr-microphone-7-240.png}"}
::: {style="display: flex;"}
The symbol $\beta$ is the Greek letter 'beta', pronounced 'beater' (as in 'egg beater').
So $\beta_0$ is said as 'beater-zero', and $\beta_1$ as 'beater-one'.
:::
::: {}
```{r}
htmltools::tags$video(src = "./Movies/beta.mp4",
width = "121",
loop = "FALSE",
controls = "controls",
loop = "loop",
style = "padding:5px; border: 2px solid gray;")
```
:::
::::
Every sample is likely to produce a slightly different value for both $b_0$ and $b_1$ (*sampling variation*), so both $b_0$ and $b_1$ have a standard error.
The formulas for computing the values of $b_0$ and $b_1$ are intimidating, so we will allow software to do the calculations.
```{r}
RD.lm <- lm(Weight ~ Age,
data = RedDeer)
RD.b0 <- round( coef(RD.lm)[1], 3)
RD.b1 <- round( coef(RD.lm)[2], 3)
```
<div style="float:right; width: 222x; border: 1px; padding:10px">
<img src="Illustrations/diana-parkhouse-Qf4eZXC3t2Y-unsplash.jpg" width="200px"/>
</div>
For the red-deer data again
`r if( knitr::is_latex_output() ) {
'(Fig. \\@ref(fig:RedDeerScatter)),'
} else {
'(Fig. \\@ref(fig:RedDeerScatterHTML)),'
}
`
part of the relevant output is shown in Fig. \@ref(fig:RedDeerRegressionjamoviSPSSraw).
From the output, the sample *slope* is $b_1 = `r RD.b1`$, and the sample $y$-intercept is $b_0 = `r RD.b0`$: the values of $b_0$ and $b_1$ are in the column labelled `Estimate` in jamovi, and the column labelled `B` in SPSS.
These are the values of the two *regression coefficients*; so
\[
\hat{y} = `r RD.b0` + (`r RD.b1`\times x),
\qquad\text{usually written as}\qquad
\hat{y} = `r RD.b0` - `r abs(RD.b1)` x.
\]
::: {.tipBox .tip data-latex="{iconmonstr-info-6-240.png}"}
The *sign* of the slope $b_1$ and the sign of correlation coefficient $r$ are always the same.
For example, if the slope is negative, the correlation coefficient will also be negative.
:::
```{r RedDeerRegressionjamoviSPSSraw, fig.cap="Output for the red-deer data,Left: jamovi; right: SPSS", fig.align="center", out.width=c("45%", "54%"), fig.show="hold"}
knitr::include_graphics( "jamovi/RedDeer/RedDeer-Regression.png")
knitr::include_graphics( "SPSS/RedDeer/RedDeer-Regression.png")
```
```{r}
cyclone.lm <- lm(Total ~ OND,
data = Cyclones)
```
::: {.example #RegressionCoefficients name="Regression coefficients"}
The regression equation for the cyclone data (Fig. \@ref(fig:ONIcyclones)) is found from the jamovi output (Fig. \@ref(fig:CyclonesRegressionjamoviSPSS)):
\[
\hat{y} = 12.14 - 2.23x,
\]
where $x$ is the ONI (averaged over October, November, December) and $y$ is the number of cyclones.
These values are close the approximations made in Example \@ref(exm:CycloneRegressionGuesses) ($12$ and $-2.25$ respectively).
:::
```{r CyclonesRegressionjamoviSPSS, fig.cap="Output for the cyclone data. Left: jamovi; right: SPSS", fig.align="center", out.width=c("43%", "55%"), fig.show="hold"}
knitr::include_graphics( "jamovi/Cyclones/Cyclones-Regression.png")
knitr::include_graphics( "SPSS/Cyclones/SPSS-Cycones-Regression.png")
```
`r if (knitr::is_html_output()){
'You may like the following interactive activity, which explores regression equations.'}`
<div style="text-align:center;">
<iframe src="https://phet.colorado.edu/sims/html/least-squares-regression/latest/least-squares-regression_en.html" width="600" height="450" scrolling="no" allowfullscreen="true"></iframe>
</div>
## Regression for predictions {#RegressionForPrediction}
<div style="float:right; width: 222x; border: 1px; padding:10px">
<img src="Illustrations/diana-parkhouse-Qf4eZXC3t2Y-unsplash.jpg" width="200px"/>
</div>
The regression equation for the red-deer data, estimated from one of the many possible samples, is $\hat{y} = `r RD.b0` - `r abs(RD.b1)` x$, and can be used to make *predictions* of the mean value of $y$ for a given value of $x$; for example, predicting the *average* molar weight for deer $10$ years old.
Since $x$ represents the age, use $x = 10$ in the regression equation:
\begin{eqnarray*}
\hat{y}
&=& `r RD.b0` - (`r abs(RD.b1)`\times 10)\\
&=& `r RD.b0` - `r abs(RD.b1 * 10)` = `r RD.b0 + RD.b1*10`.
\end{eqnarray*}
Male red deer aged $10$ years are predicted to have a *mean* molar weight of $`r RD.b0 + RD.b1*10`$ grams.
Some individual deer aged $10$ will have molars weighing *more* than this, and some weighing *less* than this; the model predicts that the *mean* molar weight for male red deer aged 10 will be about $`r RD.b0 + RD.b1*10`$ grams.
(Note: The value of $\hat{y}$ is computed using the estimates $b_0$ and $b_1$, which are in turn computed from sample data.
Hence, the value of $\hat{y}$ is also based on the sample informatiom, so also has a standard error.)
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
What is the predicted mean molar weight for for male red deer $12$ years of age?\label{thinkBox:Predictions}
`r if (knitr::is_latex_output()) '<!--'`
`r webexercises::hide()`
Prediction: $4.398 - (0.181 \times 12) = 2.226$, or about 2.23 grams.
`r webexercises::unhide()`
`r if (knitr::is_latex_output()) '-->'`
:::
Suppose we were interested in male red deer $20$ years of age; the mean predicted weight of the molars would be $4.398 - (0.181 \times 20) = 0.778$, or about $0.78$ grams.
However, while this prediction *may* be a useful prediction... it may be rubbish.
In the data, the oldest deer is aged 14.4 years, so the regression line may not even apply for deer aged over 14.4 years of age.
For example, the relationship may be non-linear after 14 years of age, or red deer may not even live to 20 years of age.
The prediction *may* be sensible... but it *may not* be either.
We don't know whether the prediction is sensible or not, because we have no data for deer aged over 14.4 years to inform us.
Making predictions outside the range of the available data is called *extrapolation*, and *extrapolation* beyond the data may lead to nonsense predictions.
::: {.definition #Extrapolation name="Extrapolation"}
*Extrapolation* refers to making predictions outside the range of the available data.
Extrapolation beyond the data may lead to nonsense predictions.
:::
## Regression for understanding {#RegressionForUnderstanding}
The regression equation can be used to *understand* the relationship between the two variables.
Consider again the red-deer regression equation:
\begin{equation}
\hat{y}
=
`r RD.b0`
-
`r abs(RD.b1)` x.
(\#eq:RedDeerEquation)
\end{equation}
What does this equation reveal about the relationship between $x$ and $y$?
### The meaning of $b_0$
$b_0$ is the *predicted* value of $y$ when $x = 0$.
Using $x = 0$ in Eq. \@ref(eq:RedDeerEquation) predicts a mean molar weight of
\[
\hat{y} = 4.398 - (0.181\times 0) = 4.398
\]
for deer zero years of age (i.e., newborn male red deer).
This prediction is the predicted *mean* molar weight; some individual deer will have molars weights greater than this, and some less than this.
But in any case, this predicted mean may be nonsense: it is *extrapolating* beyond the data (the youngest deer in the sample is aged $4.4$ years).
::: {.tipBox .tip data-latex="{iconmonstr-info-6-240.png}"}
The value of the intercept $b_0$ is sometimes (but not always) meaningless.
The value of the slope $b_1$ is usually of greater interest, as it explains the *relationship* between the two variables.
:::
### The meaning of $b_1$ {#SlopeMeaning}
$b_1$ tells us how much the value of $y$ changes (on average) when the value of $x$ *increases* by one.
For the red-deer data, $b_1$ tells us how much the molar weight changes (on average) when age increases by one year.
Each extra year older is associated with an average change of $`r RD.b1`$ grams in molar weight; that is, a *decrease* in molar weight by a mean of $`r abs(RD.b1)`$g.
The molars of some individual deer will lose more weight than this in some years, and some will lose less... the value is a *mean* weight loss per year.
To demonstrate: When $x = 10$, $y$ is predicted to be $\hat{y}= `r RD.b0 + 10 * RD.b1`$g.
For deer one year older than this (i.e.\ $x = 11$) we predict $y$ to increase by $b_1 = `r RD.b1`$g higher (or, equivalently, $0.181$ *lower*).
That is, we would predict $\hat{y}= `r RD.b0 + 10*RD.b1` - `r abs(RD.b1)` = `r RD.b0 + 11*RD.b1`$g.
This is the same prediction made by using $x = 11$ in Eq. \@ref(eq:RedDeerEquation).
::: {.tipBox .tip data-latex="{iconmonstr-info-6-240.png}"}
If the value of $b_1$ is *positive*, then the predicted values of $y$ *increase* as the values of $x$ *increase*.
If the value of $b_1$ is *negative*, then the predicted values of $y$ *decrease* as the values of $x$ *increase*.
:::
This interpretation of $b_1$ explains the relationship: Each extra year of age reduces the weight of the molars by 0.181 grams, on average, in male red deer.
Recall that the units of measurement of the slope here are 'grams per year'.
Observe what happens if the slope is *zero*.
Since $b_1$ is the change in $y$ (on average) when $x$ increase by one, $b_1 = 0$ means that the predicted mean value of $y$ changes by *zero* if the value of $x$ changes by one.
In other words, if the value of $x$ changes, the predicted mean value of $y$ doesn't change.
This is equivalent to saying that there is *no relationship* between the variables.
(We would also find $r = 0$.)
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
If the value of the slope is zero, there is *no linear relationship* between $x$ and $y$.
In this case, the correlation coefficient is also zero.
:::
## Confidence intervals for the regression parameters {#RegressionCI}
### Introduction {#RegressionTests-Intro}
The regression line is computed from the *sample* data, assuming a linear relationship actually exists in the *population*.
The values of $b_0$ and $b_1$ are estimates of the population parameters $\beta_0$ and $\beta_1$.
The *sample* estimates can be used to ask questions about the unknown *population* regression coefficients.
As usual, the sample estimates can vary across all possible samples (and so have a *sampling distribution*).
Usually the slope of more interest than the intercept, because the slope explains the *relationship* between the two variables (Sect. \@ref(RegressionForUnderstanding)); however the same ideas apply for the intercept.
The CIs can be obtained from software or computed manually.
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
Using the output (Fig. \@ref(fig:RedDeerRegressionjamoviSPSSraw)) for the red-deer data, can you determine the *approximate* 95% CI for $\beta_1$?\label{thinkBoxCI}
:::
### Describing the sampling distribution {#SamplingDistributionSlopeCI}
The observed value of the slope will vary across all possible samples; *sampling variation* is present.
However, under certain conditions (Sect. \@ref(RegressionStatValidity)), the sampling distribution can be described as:
* an approximate normal distribution,
* with a mean of $\beta_1 = 0$, and
* a standard deviation, called the *standard error of the slope* and denoted $\text{s.e.}(b_1)$.
(A formula exists for finding $\text{s.e.}(b_1)$, but it is tedious to use and we will not give it.)
This distribution describes the possible values of the sample slope, through *sampling variation*.
For the red-deer data then, the values of the sample slope across all possible samples is described (Fig. \@ref(fig:RedDeerSlopeSampDistCI)) as:
* an approximate normal distribution,
* with a sampling mean whose values is $\beta_1 = 0$, and
* with a standard deviation, called the *standard error of the slope* $\text{s.e.}(b_1) = 0.029$ (from software; Fig. \@ref(fig:RedDeerRegressionjamoviSPSSraw)).
```{r RedDeerSlopeSampDistCI, fig.cap="The distribution of sample slopes for the red-deer data, around the true slope $\\beta_1$", fig.align="center", fig.height=3.5, fig.width=8.25, out.width='85%'}
mn <- 0
se <- 0.0289
out <- plotNormal(mu = mn,
sd = se,
round.dec = 4,
cex.axis = 0.95,
ylim = c(0, 27),
showXlabels = c( expression(beta[1] - 0.087),
expression(beta[1] - 0.058),
expression(beta[1] - 0.029),
expression(beta[1]),
expression(beta[1] + 0.029),
expression(beta[1] + 0.058),
expression(beta[1] + 0.087)),
main = "", # Main title
xlab = "Sample regression slopes", # horizontal axis labels
showZ = TRUE) # Whether to show z = -3:3 or not
arrows( x0 = 0,
x1 = 0,
y0 = 22,
y1 = 14,
angle = 15,
length = 0.15)
text(x = 0,
y = 22,
pos = 3,
labels = "Sampling mean")
arrows(x0 = 0,
x1 = 0.029,
y0 = 3,
y1 = 3,
angle = 15,
length = 0.15)
text(x = 0.029/2,
y = 3,
pos = 3,
labels = "Std. error")
```
Most CIs have the form
\[
\text{statistic} \pm ( \text{multiplier} \times \text{standard error}),
\]
where the multiplier is two for an approximate 95% CI (from the 68--95--99.7 rule),.
Using the standard error reported by the software, an approximate 95% CI is $-0.181 \pm (2\times 0.029)$, or $-0.181 \pm 0.058$, or from $-0.239$ to $-0.123$.
Software can be used to produce *exact* CIs too (Fig. \@ref(fig:RedDeerRegressionjamoviSPSSCI)).
The *approximate* and *exact* 95% CIs are very similar.
We could write:
> The approximate 95% confidence, for the slope in the regression line explaining molar weight of male red deer from age, is between $-0.239$ to $-0.123$ grams per year.
```{r RedDeerRegressionjamoviSPSSCI, fig.cap="Output for the red-deer data, including the CIs for the regression parameters. Top: jamovi; bottom: SPSS", fig.align="center", out.width=c("75%", "90%"), fig.show="hold"}
knitr::include_graphics( "jamovi/RedDeer/RedDeer-Regression-CI.png")
knitr::include_graphics( "SPSS/RedDeer/RedDeer-Regression-CI.png")
```
::: {.example #EDpatientsCI name="Emergency department patients"}
A study examined the relationship between the number of emergency department (ED) patients and the number of days following the distribution of monthly welfare monies [@brunette1991correlation] from 1986 to 1988 in Minneapolis, USA.
The data (extracted from Fig. 2 of @brunette1991correlation) are displayed in Fig. \@ref(fig:EDScatterjamovi) (left panel), and the jamovi output in Fig. \@ref(fig:EDScatterjamovi) (right panel)).
From the jamovi output (Fig. \@ref(fig:EDScatterjamovi)), the regression line is estimated as
\[
\hat{y} = 150.19 - 0.348x,
\]
where $y$ represents the mean number of ED patients, and $x$ the number of days since welfare distribution.
A 95% CI for the slope is not shown in the output (though it could have been requested).
However, since most CIs have the form
\[
\text{statistic} \pm ( \text{multiplier} \times \text{standard error}),
\]
an approximate 95% CI is easily computed:
\[
-0.34790 \pm (2\times 0.046672),
\]
or $-0.34790 \pm 0.093344$, equivalent to $-0.441$ to $-0.255$ patients per day.
:::
```{r EDScatterjamovi, fig.align = "center", fig.cap = "The number of emergency department patients, and the number of days since distribution of welfare. Left: scatterplot; right: jamovi output.", fig.width=5, fig.height=3.5, out.width=c("45%", "54%"), fig.show="hold"}
data(EDpatients)
plot( ED ~ Days,
data = EDpatients,
xlab = "Days after distribution",
ylab = "Mean number of ED patients",
main = "Mean number of ED patients vs \ndays after distribution of welfare",
pch = 19,
las = 1,
xlim = c(0, 30),
ylim = c(135, 155) )
knitr::include_graphics( "jamovi/ED/EDRegression-crop.png")
```
## Hypothesis testing for the regression parameters {#RegressionHT}
### Statistical hypotheses {#RegressionHypotheses}
The null hypothesis is the usual 'no relationship' hypothesis.
In this context, 'no relationship' means that the slope is zero (Sect. \@ref(SlopeMeaning)), so the null hypotheses (about the *population*) is $H_0$: $\beta_1 = 0$.
This hypothesis proposes that $\beta_1$ is zero, but $b_1$ is not zero due to sampling variation.
As part of the [decision-making process](#DecisionMaking), the null hypothesis is initially *assumed* to be true.
For the red-deer data (Sect. \@ref(RedDeerData)), testing if a relationship exists between the age of the deer and the weight of their molars implies these hypotheses:
\[
\text{$H_0$: } \beta_1 = 0;\quad\text{and}\quad\text{$H_1$: } \beta_1 \ne 0.
\]
The parameter is $\beta_1$, the population slope for the regression equation predicting molar weight from age.
The alternative hypothesis is two-tailed, based on the RQ.
```{r}
RD.fitinfo <- summary(RD.lm)$coefficients
RD.t <- RD.fitinfo[, "t value"]
RD.P <- RD.fitinfo[, "Pr(>|t|)"]
```
### Describing the sampling distribution {#SamplingDistributionSlopeHT}
*Assuming* the null hypothesis is true (that $\beta_1 = 0$), the possible values of the sample slope $b_1$ can be described, due to *sampling variation*.
The variation in the sample slope across all possible samples is described (Fig. \@ref(fig:RedDeerSlopeSampDist)) using:
* an approximate normal distribution,
* with a sampling mean whose value is $\beta_1 = 0$ (from $H_0$), and
* a standard deviation, called the *standard error of the slope* and denoted $\text{s.e.}(b_1)$, with a value of $0.0289$ (from software; Fig. \@ref(fig:RedDeerRegressionjamoviSPSSCI)).
```{r RedDeerSlopeSampDist, fig.cap="The distribution of sample slopes for the red-deer data, if the population slope is 0", fig.align="center", fig.height=3.5, fig.width=8.25, out.width='85%'}
par( mar = c(5, 2, 1, 2))
mn <- 0
se <- 0.0289
out <- plotNormal(mu = mn,
sd = se,
ylim = c(0, 27),
round.dec = 4,
main = "", # Main title
xlab = "Sample regression slopes", # horizontal axis labels
showZ = TRUE) # Whether to show z = -3:3 or not
arrows( x0 = 0,
x1 = 0,
y0 = 22,
y1 = 14,
angle = 15,
length = 0.15)
text(x = 0,
y = 22,
pos = 3,
labels = "Sampling mean")
arrows(x0 = 0,
x1 = 0.029,
y0 = 3,
y1 = 3,
angle = 15,
length = 0.15)
text(x = 0.029/2,
y = 3,
pos = 3,
labels = "Std. error")
```
### Computing the test statistic
The *observed* sample slope is $b_1 = -0.181$.
Locating this on Fig. \@ref(fig:RedDeerSlopeSampDist) (way to the left) shows that it is very unlikely that one of the many possible samples would produce such a slope, just through sampling variation (if the population slope really was $\beta_1 = 0$).
The *test statistic* is found using the usual approach when the sampling distribution has an approximate normal distribution:
\begin{align*}
t
&= \frac{\text{observed sample slope} - \text{slope sampling mean}}{\text{standard error of the slope}}\\
&= \frac{ b_1 - \beta_1}{\text{s.e.}(b_1)} \\
&= \frac{-0.181 - 0}{0.0289} = -6.27,
\end{align*}
where the values of $b_1$ and $\text{s.e.}(b_1)$ are taken from the software output (Fig. \@ref(fig:RedDeerRegressionjamoviSPSSCI)).
This $t$-score is also reported by the software.
### Determining the $P$-value
To determine if the statistic is *consistent* with the null hypothesis, the $P$-value can be approximated using the [68--95--99.7 rule](#def:EmpiricalRule), approximated using tables, or taken from software output (Fig. \@ref(fig:RedDeerRegressionjamoviSPSSCI)).
Using software, the two-tailed $P$-value is $P < 0.001$.
### Writing conclusions
We write:
> The sample presents very strong evidence ($t = -6.27$; two-tailed $P < 0.001$) that the slope in the population between age of the deer and molar weight is not zero (slope: $-0.181$; 95% CI from $-0.239$ to $-0.124$).
Notice the three features of writing conclusions again:
An *answer to the RQ*; evidence to support the conclusion ('$t = -6.27$; two-tailed $P < 0.001$); and some *sample summary information* ('slope: $-0.181$; 95% CI from $-0.239$ to $-0.124$').
<!-- ```{r RedDeerRegressionjamoviSPSS, fig.cap="Output for the red-deer data. Top: jamovi; bottom: SPSS", fig.align="center", out.width=c("60%", "80%"), fig.show="hold"} -->
<!-- knitr::include_graphics( "jamovi/RedDeer/RedDeer-Regression.png") -->
<!-- knitr::include_graphics( "SPSS/RedDeer/RedDeer-Regression.png") -->
<!-- ``` -->
::: {.example #EDpatientsRegression name="Emergency department patients"}
For the emergency department data used in Example \@ref(exm:EDpatientsCI), the scatterplot of the data and the jamovi output are shown in Fig. \@ref(fig:EDScatterjamovi).
The regression line is estimated as
\[
\hat{y} = 150.19 - 0.348x,
\]
where $y$ represents the mean number of ED patients, and $x$ the number of days since welfare distribution.
This regression equation suggests that each extra day after welfare distribution is associated with a *decrease* in the mean number of ED patients of about 0.35.
It may be easier to understand this way:
> Each 10 extra days after welfare distribution is associated with a *decrease* in the number of ED patients of about $10\times 0.35 = 3.5$.
The scatterplot and the regression equation suggests a negative relationship between the number of ED patients and the days after distribution.
However, every sample is likely to be different, so the relationship may not actually be present in the population (the slope may be non-zero due to sampling variation).
We can test this hypothesis:
\[
\text{$H_0$: } \beta_1 = 0\quad\text{and}\quad\text{$H_1$: } \beta_1 \ne 0,
\]
where $\beta_1$ is the *population* slope.
The test is two-tailed, based on the authors' aim.
From the output, the test statistic is $t = -7.45$, which is very large; unsurprisingly, the two-tailed $P$-value is very small: $P < 0.001$.