forked from PeterKDunn/SRM-Textbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
35-Relationships-Two-Quant.Rmd
517 lines (395 loc) · 16.4 KB
/
35-Relationships-Two-Quant.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
# (PART) Connection RQs: regression and correlation {-}
# Relationships between two quantitative variables {#TwoQuant}
<!-- Introductions; easier to separate by format -->
```{r, child = if (knitr::is_html_output()) {'./introductions/35-Relationships-Two-Quant-HTML.Rmd'} else {'./introductions/35-Relationships-Two-Quant-LaTeX.Rmd'}}
```
## Introduction: red deer {#Chap33-Intro}
So far, RQs about single variables and RQs for comparing two groups have been studied.
Comparing the mean value of a quantitative variable in two groups was studied in Sects. \@ref(CITwoMeans) and \@ref(TestTwoMeans).
Comparing the percentage of times an outcome of interest appears in two groups was studied in Sects. \@ref(OddsRatiosCI) and \@ref(TestsOddsRatio).
In this Chapter (and the next two), the relationship between two quantitative variables is studied.
Our main example in the next three chapters is a study [@data:Holgate1965:StraightLine] that examined the relationship between the age of $n = 78$ male red deer and the weight of their
`r if( knitr::is_latex_output() ) {
'molars (Table \\@ref(tab:deerData)).'
} else {
'molars; the data are shown below.'
}
`
The data comprises two quantitative variables.
```{r deerDataDT, fig.cap="The male red deer data", fig.align="center"}
data(RedDeer)
if( knitr::is_html_output() ) {
DT::datatable(RedDeer,
list(scrollX = TRUE,
scrollY = TRUE,
ordering = FALSE),
caption = "The male red deer data")
}
```
\begin{figure}
\begin{minipage}{0.32\textwidth}
\captionof{table}{The first five and last five observations of the male red deer data ($n = 78$)\label{tab:deerData}}
\fontsize{10}{12}\selectfont
```{r deerData}
RDhead <- array( dim = c(11, 2) )
RDhead[1:5, ] <- as.matrix( head(RedDeer, 5) )
RDhead[7:11, ] <- as.matrix( tail(RedDeer, 5) )
RDhead[, 1] <- format( RDhead[, 1],
nsmall = 1)
RDhead[, 2] <- format( RDhead[, 2],
digits = 2,
nsmall = 2)
RDhead[6, ] <- c("$\\vdots$", "$\\vdots$")
knitr::kable( RDhead,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
table.env = "@empty",
escape = FALSE,
digits = c(1, 2),
align = "c",
linesep = "", # With the \vdots, spacing doesn't seem necessary
col.names = c( "Age (in years)",
"Molar weight (in g)")) %>%
row_spec(0, bold = TRUE) %>%
#kable_styling(font_size = 10) %>% # CANNOT USE THIS IN THE MINIPAGE
column_spec(1, width = "13mm") %>%
column_spec(2, width = "22mm")
```
\end{minipage}
\hspace{0.05\textwidth}
\begin{minipage}{0.60\textwidth}%
\centering
```{r RedDeerScatter, fig.width=5.5, out.width='95%'}
plot(Weight ~ Age,
data = RedDeer,
las = 1,
pch = 19,
ylim = c(0, 5.5),
xlim = c(4, 15),
cex = 0.8,
main = "Molar weight and age\nof male red deer",
xlab = "Age (in years)",
ylab = "Molar weight (in g)")
```
\caption{Molar weight verses age for the red deer data}\label{fig:RedDeerScatter}
\end{minipage}
\end{figure}
## Two quantitative variables: graphical summaries {#RedDeerData}
<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, both variables are *quantitative*, so the appropriate graphical summary (Sect. \@ref(Scatterplots)) is a *scatterplot*
`r if( knitr::is_latex_output() ) {
'(Fig. \\@ref(fig:RedDeerScatter)).'
} else {
'(Fig. \\@ref(fig:RedDeerScatterHTML)).'
}
`
The *response* variable is graphed on the *vertical* axis, and denoted $y$; the *explanatory* variable is graphed on the *horizontal* axis,
and denoted $x$.
In some cases, when only a relationship is being explored, which variable is $x$ and which is $y$ is not important (for example, see Example \@ref(exm:CorTestDogs).)
Since the *explanatory* variable (potentially) *influences* the response variable, in this example:
* The *explanatory variable* ($x$) is the age of the deer (in years), and
* The *response variable* ($y$) is the weight of molars (in grams).
In other words, the age of the deer may influence the weight of the molars.
(Supposing that the weight of the molars may influence the age of the deer is silly.)
Each row in the dataset (and each point on the scatterplot) corresponds to a single deer (the units of analysis); two quantitative variables (age; molar weight) are measured on each deer.
<!-- The figure for LaTeX is in the minipage (combined with data table), so only need show it for the HTML -->
`r if (knitr::is_latex_output()) '<!--'`
```{r RedDeerScatterHTML, fig.cap="Molar weight verses age for the red deer data", fig.align="center", fig.width=4.5, fig.height=3.5}
plot(Weight ~ Age,
data = RedDeer,
las = 1,
pch = 19,
ylim = c(0, 5.5),
xlim = c(4, 15),
cex = 1,
main = "Molar weight in male red deer\nplotted against the age of the deer",
xlab = "Age (in years)",
ylab = "Molar weight (in g)")
```
`r if (knitr::is_latex_output()) '-->'`
## Understanding scatterplots {#UnderstandingScatterplots}
The purpose of a graph is to help *understand* the data (Sect. \@ref(GraphsIntro)).
For a scatterplot, the *form*, *direction*, and *variation in the relationship* (or the *strength of the relationship*) are described:
1. *Form*: The overall *form* or structure of the relationship (e.g., linear; curved upwards; etc.).
2. *Direction*: The *direction* of the relationship (sometimes not relevant if the relationship is non-linear):
- The variables are *positively* associated if *high* values of one variable accompany *high* values of the other variable, in general.
- The variables are *negatively* associated if *high* values of one variable accompany *low* values of the other variable, in general.
3. *Variation*: The amount of *variation* in the relationship.
A small amount of variation in the response variable for given values of the explanatory variable means the relationship is strong; a lot of variation in the response variable for given values of the explanatory variable means the relationship is less strong.
Anything unusual or noteworthy should also be discussed.
These three features explain the *type* of relationship (*form*; *direction*), and the *strength* of that relationship (*variation*).
Examples are shown in
`r if (knitr::is_html_output()) {
'the carousel below (click to move through the scatterplots).'
} else {
'Fig. \\@ref(fig:ScatterplotDescriptionExamples). (The online version has extra examples.)'
}`
```{r, child = if (knitr::is_html_output()) './children/ScatterExampleCarousel.Rmd'}
```
```{r, child = if (knitr::is_latex_output()) './children/ScatterExampleImages.Rmd'}
```
::: {.example #DescribeScatterplots name="Describing scatterplots"}
A study [@data:Tager:FEV; @BIB:data:FEV] measured the lung capacity of children in Boston (using the forced expiratory volume, FEV).
The scatterplot (Fig. \@ref(fig:FEVscatter)) is curved (*form*), where older children have larger FEVs, in general (*direction*).
The *variation* gets larger for taller youth.
:::
```{r FEVscatter, fig.cap="FEV plotted against height for children in Boston", fig.align="center", fig.width=8, fig.height=3.25, out.width='90%'}
data(LungCap)
par(mfrow = c(1, 2))
plot(FEV ~ Ht,
data = LungCap,
las = 1,
ylim = c(0, 6),
cex = 0.7,
main = "FEV and height",
xlab = "Height (inches)",
ylab = "FEV (litres)",
pch = 19)
scatter.smooth( LungCap$Ht, LungCap$FEV,
las = 1,
ylim = c(0, 6),
cex = 0.7,
col = "grey",
lwd = 2,
main = "FEV and height",
xlab = "Height (inches)",
ylab = "FEV (litres)",
pch = 19)
arrows(x0 = 50,
x1 = 50,
y0 = 0.8,
y1 = 2.2,
angle = 15,
length = 0.11,
lwd = 2,
code = 3)
text(x = 50,
y = 2.2,
pos = 3,
cex = 0.85,
labels = "Smaller\nvariation")
arrows(x0 = 70,
x1 = 70,
y0 = 2,
y1 = 5.8,
angle = 15,
length = 0.11,
lwd = 2,
code = 3)
text(x = 70,
y = 1.8,
pos = 1,
cex = 0.85,
labels = "Larger\nvariation")
```
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
Describe the scatterplot of the diameter against the age of $385$ small-leaved lime trees (@data:ForestBiomass2017), shown in Fig. \@ref(fig:LimeTreesScatter)).\label{thinkBox:DescribeLimeTreesScatter}
`r if (knitr::is_latex_output()) '<!--'`
`r webexercises::hide()`
* **Form**: may start off straight-ish, but then seems hard to assess.
* **Direction**: biomass increases as age increases (on average).
* **Variation**: small-ish for small ages; large-ish for older trees (after about 60 years old).
`r webexercises::unhide()`
`r if (knitr::is_latex_output()) '-->'`
:::
```{r LimeTreesScatter, fig.cap="The age and foliage biomass of small-leaved lime trees grown in Russia ($n = 385$)", fig.align="center", fig.show="hold", fig.width=8, fig.height=3.25, out.width='90%'}
data(Lime)
par( mfrow = c(1, 2))
plot(Foliage ~ Age,
las = 1,
main = "Foliage biomass of small-leaved\nlime trees against age",
xlab = "Age (in years)",
ylab = "Foliage biomass (in kg)",
cex = 0.8,
pch = 19,
xlim = c(0, 140),
ylim = c(0, 14),
data = Lime)
###
plot(Foliage ~ Age,
las = 1,
main = "Foliage biomass of small-leaved\nlime trees against age",
xlab = "Age (in years)",
ylab = "Foliage biomass (in kg)",
cex = 0.8,
pch = 19,
col = "grey",
xlim = c(0, 140),
ylim = c(0, 14),
data = Lime)
abline( coef(lm(Foliage ~ Age,
data = Lime)),
lwd = 2)
#m2 <- lm(log(DBH) ~ log(Age),
# data = lime)
#
#newAge <- seq( min(lime$Age),
# max(lime$Age),
# length = 100)
#newDBH <- predict(m2,
# newdata = data.frame(Age = newAge))
#lines( newDBH ~ newAge)
```
::: {.example #DescribeScatterplotsDeer name="Scatterplots"}
For the red deer data
`r if (knitr::is_latex_output()) {
'(Fig. \\@ref(fig:RedDeerScatter)),'
} else {
'(Fig. \\@ref(fig:RedDeerScatterHTML)),'
}`
the relationship is approximately linear (form) with a negative direction (*older* deer generally have *lighter* teeth); the *variation* is... perhaps moderate.
:::
<iframe src="https://learningapps.org/watch?v=pdxmdaf1522" style="border:0px;width:100%;height:500px" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>
## Summary {#Chap33-Summary}
A *scatterplot* displays the relationship between two quantitative variables (the response denoted $y$; the explanatory denoted $x$).
The relationship is described by the *form* (linear, or otherwise), the *direction* of the relationship (sometimes not relevant if the graph is not linear), and the *variation* in the relationship (or the *strength* of the relationship).
## Quick review questions {#Chap33-QuickReview}
::: {.webex-check .webex-box}
A study of onion growth [@meadplant] produced the scatterplot shown in Fig. \@ref(fig:MeanScatter).
```{r MeanScatter, fig.cap="Onion yield plotted against planting density", fig.align="center", fig.width=5, fig.height=3.5}
data(YieldDen)
plot(Yield ~ Dens,
las = 1,
main = "Planting density and yield per plant\nfor onions",
xlab = "Planting density (plants/sq. ft)",
ylab = "Yield/plant (g/plant)",
pch = 19,
ylim = c(0, 140),
data = YieldDen)
```
1. The $x$-variable is \tightlist
`r if( knitr::is_html_output() ) {longmcq( c(
answer = "Planting density",
"Yield per plant",
"It doesn't matter"
) )} else {"________________."}`
1. The *form* is best described as
`r if( knitr::is_html_output() ) {longmcq( c(
"Linear",
answer = "Curved"
) )} else {"________________."}`
1. The *direction* is best described as
`r if( knitr::is_html_output() ) {longmcq( c(
answer = "Negative",
"Positive"
) )} else {"________________."}`
1. The *variation* is best described as
`r if( knitr::is_html_output() ) {longmcq( c(
answer = "Small",
"Large",
"Strong"
) )} else {"________________."}`
:::
## Exercises {#TwoQuantExercises}
Selected answers are available in Sect. \@ref(TwoQuantAnswer).
<!-- ::: {.exercise #TwoQuantExercisesSheepFood} -->
<!-- A study evaluated various food mixtures for sheep [@data:Moir1961:RuminantDiet]. -->
<!-- Describe the scatterplot (Fig. \@ref(fig:SheepScatter)) in terms of the *form*, *direction* and *variation* in the relationship. -->
<!-- ::: -->
<!-- ```{r SheepScatter, fig.cap="Scatterplots for the sheep-food data", fig.align="center", fig.width=5, fig.height=3.5} -->
<!-- data(ruminant) -->
<!-- plot(Energy ~ DryMatterDigest, -->
<!-- data = ruminant, -->
<!-- las = 1, -->
<!-- xlim = c(30, 80), -->
<!-- ylim = c(1, 3.5), -->
<!-- main = "Sheep feed data", -->
<!-- xlab = "Dry matter digestibility (%)", -->
<!-- ylab = "Digestible energy (in Cal/gram)", -->
<!-- pch = 19) -->
<!-- abline( lm( Energy ~ DryMatterDigest, -->
<!-- data = ruminant), -->
<!-- lwd = 2, -->
<!-- col = "grey") -->
<!-- ``` -->
::: {.exercise #TwoQuantExercisesSoftdrink}
A study examined the time taken to deliver soft drinks to vending machines [@others:Montgomery:regressionanalysis].
Describe the relationship (Fig. \@ref(fig:MandibleGestationPlot), left panel).
:::
::: {.exercise #TwoQuantExercisesMandible}
A study examined the mandible length and gestational age for 167 foetuses from the 12th week of gestation onward [@data:royston:mandible].
Describe the relationship (Fig. \@ref(fig:MandibleGestationPlot), right panel).
:::
```{r MandibleGestationPlot, fig.cap="Two scatterplots. Left: The time taken to deliver soft drinks to vending machines. Right: The relationship between gestational age and mandible length.", fig.align="center", fig.width=9, fig.height=3.5, out.width='100%'}
par(mfrow = c(1, 2),
mar = c(5.1, 5.1, 4.1, 2.1))
data(SDrink)
plot(Time ~ Cases,
data = SDrink,
main = "Time to service vending machine\nand number of products stocked",
xlab = "Number of cases of product stocked",
ylab = "Time to service\nmachine (mins)",
xlim = c(0, 30),
ylim = c(0, 80),
las = 1,
pch = 19)
abline(coef(lm(Time ~ Cases,
data = SDrink)),
col = "grey")
###
data(Mandible)
plot(Length ~ Age,
data = Mandible,
main = "Gestational age and\nmandible length",
xlab = "Gestational age (in weeks)",
ylab = "Mandible length (in mm)",
xlim = c(10, 40),
ylim = c(0, 50),
las = 1,
pch = 19)
abline(coef(lm(Length ~ Age,
data = Mandible)),
col = "grey")
###
```
::: {.exercise #TwoQuantExercisesGorillas}
A study [@wright2021chest] 25 gorillas are recorded information about their chest beating and their size (measured by the breadth of the gorillas' backs).
Describe the relationship (Fig. \@ref(fig:GorillaWindmillPlot), left panel).
:::
```{r GorillaWindmillPlot, fig.cap="Two scatterplots. Left: Chest beating in gorillas; right: The relationship between DC output and wind speed.", fig.align="center", fig.width=9, fig.height=3.5, out.width='100%'}
par(mfrow = c(1, 2),
mar = c(5.1, 4.1, 4.1, 2.1))
data(Gorillas)
plot(NoChestBeats ~ BackBreadth,
data = Gorillas,
main = "Chest beating in gorillas",
xlab = "Back breadth (in cm)",
ylab = "Number chest beats per minute",
xlim = c(54, 66),
ylim = c(0, 51),
las = 1,
pch = 19)
###
data(Windmill)
plot(DC ~ Wind,
data = Windmill,
main = "DC output and wind speed",
xlab = "Wind speed (in miles per hour)",
ylab = "DC output",
las = 1,
xlim = c(2, 10),
ylim = c(0, 2.5),
pch = 19)
```
::: {.exercise #TwoQuantExercisesWindmill}
A study examined the relationship between direct current generated by a windmill and wind speed [@data:hand:handbook; @data:joglekar:lackoffit].
Describe the relationship (Fig. \@ref(fig:GorillaWindmillPlot), right panel).
:::
<!-- QUICK REVIEW ANSWERS -->
`r if (knitr::is_html_output()) '<!--'`
::: {.EOCanswerBox .EOCanswer data-latex="{iconmonstr-check-mark-14-240.png}"}
**Answers to in-chapter questions:**
- Sect. \ref{thinkBox:DescribeLimeTreesScatter}:
**Form**: may start off straight-ish, but then seems hard to assess.
**Direction**: biomass increases as age increases (on average).
**Variation**: small-ish for small ages; large-ish for older trees (after about 60 years old).
- \textbf{Answers to \textit{Quick Revision} questions:}
**1.** Planting density.
**2.** Curved.
**3.** Negative.
**4.** Small.
:::
`r if (knitr::is_html_output()) '-->'`