-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-Covariance.Rmd
705 lines (445 loc) · 25.6 KB
/
03-Covariance.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
# Covariance {#covariance}
```{r, echo = FALSE, fig.align= "center"}
knitr::include_graphics("graphics/covariance.png")
```
## Calculating covariance {#covariance-calculating}
The last chapter was about variance, which measures the spread of a single variable. Now we extend this idea to pairs of variables.
We say that two variables "co-vary" when the spread of one variable is related to the spread of another variable. This relationship represents an *association* between the two variables.
We'll call our two variables $X_{1}$ and $X_{2}$. To keep things simple, let's assume that we have already mean centered our variables.
::: {.rmdnote}
If $X_{1}$ and $X_{2}$ are already mean centered, then what are $\overline{X_{1}}$ and $\overline{X_{2}}$?
:::
As we did in the last chapter with variance, we'll build up the calculation of covariance step-by-step using a table to keep track of intermediate quantities we need.
Here are two variables (with $n = 7$) that have been mean centered:
| $X_{1}$ | $X_{2}$ | $\qquad$ | $\qquad$ |
|--------:|--------:|----------|----------|
| -1 | -2 | | |
| -2 | 2 | | |
| 2 | -2 | | |
| -3 | -1 | | |
| 4 | 2 | | |
| -1 | -2 | | |
| 1 | 3 | | |
::: {.rmdnote}
Check that the mean of both columns is truly zero.
:::
Something interesting happens when we look at the product $X_{1}X_{2}$.
::: {.rmdnote}
If $X_{1}$ and $X_{2}$ both lie above their means, they are both positive numbers. Therefore, their product is positive.
What if both $X_{1}$ and $X_{2}$ lie below their means? What do we know about their values individually and what do we know about their product?
:::
Here is the chart again, but with the products listed in a new column:
| $X_{1}$ | $X_{2}$ | $X_{1}X_{2}$ | $\qquad$ |
|--------:|--------:|-------------:|----------|
| -1 | -2 | 2 | |
| -2 | 2 | -4 | |
| 2 | -2 | -4 | |
| -3 | -1 | 3 | |
| 4 | 2 | 8 | |
| -1 | -2 | 2 | |
| 1 | 3 | 3 | |
Now we add up the products across all seven data pairs:
| $X_{1}$ | $X_{2}$ | $X_{1}X_{2}$ | $\qquad$ |
|--------:|--------:|-------------:|----------|
| -1 | -2 | 2 | |
| -2 | 2 | -4 | |
| 2 | -2 | -4 | |
| -3 | -1 | 3 | |
| 4 | 2 | 8 | |
| -1 | -2 | 2 | |
| 1 | 3 | 3 | |
| | | Sum: 10 | |
So when $X_{1}$ and $X_{2}$ tend to have similar values (both positive or both negative), their product is usually positive. It's not true of every pair of values in the table above; some products are negative. But the majority are positive. Therefore, the sum of all such products will be positive.
We're almost there. Just like we wanted the average squared deviation to calculate the variance, here we want the average of the products from the third column above. And just like in the case of variance, it's not *quite* the average we calculate. Instead of dividing by $n$, we divide by $n - 1$ for exactly the same esoteric reason. In our example, there are 7 data points (in other words, 7 rows of data), so we divide by 6.
Putting this all together:
| $X_{1}$ | $X_{2}$ | $X_{1}X_{2}$ | $\quad$ |
|--------:|--------:|-------------:|----------|
| -1 | -2 | 2 | |
| -2 | 2 | -4 | |
| 2 | -2 | -4 | |
| -3 | -1 | 3 | |
| 4 | 2 | 8 | |
| -1 | -2 | 2 | |
| 1 | 3 | 3 | |
| | | Sum: 10 | |
| | | Covariance: 10/6 = $\boxed{1.67}$ | |
In our diagrams, the covariance of two variables is indicated by a curved, double-headed arrow pointing at both boxes and labeled with the value of the covariance, like this:
```{r, echo = FALSE, fig.align= "center"}
knitr::include_graphics("graphics/covariance_labeled.png")
```
Note that we still include the variances of each of the individual variables. They are still important to us. We just have one new type of arrow now.
::: {.rmdnote}
Verify that the variances in the diagram are correct for our example. You can do it by hand if you want, but using R is fine too.
:::
Here is the final formula for covariance, written as $Cov\left(X_{1}, X_{2}\right)$. This works for all pairs of variables, even if they aren't mean centered. The terms $\left(X_{1} - \overline{X_1}\right)$ and $\left(X_{2} - \overline{X_2}\right)$ do the mean centering:
::: {.rmdimportant}
$$
Cov\left(X_{1}, X_{2}\right) = \frac{\sum \left(X_{1} - \overline{X_{1}}\right)\left(X_{2} - \overline{X_{2}}\right)}{n - 1}
$$
:::
::: {.rmdnote}
Suppose $X_{1}$ tends to be above its mean when $X_{2}$ is below its mean and $X_{1}$ tends to be below its mean when $X_{2}$ is above its mean. What will the product $\left(X_{1} - \overline{X_{1}}\right)\left(X_{2} - \overline{X_{2}}\right)$ usually be? Therefore, what will the sum of all such products likely be?
:::
For general variables (not necessarily mean centered), the table will actually look like this:
|$X_{1}$| $X_{2}$|$\left(X_{1} - \overline{X_{1}}\right)$ | $\left(X_{2} - \overline{X_{2}}\right)$ | $\left(X_{1} - \overline{X_{1}}\right)\left(X_{2} - \overline{X_{2}}\right)$ |
|----:|----:|----:|----:|----:|
| 17 | 23 | -2 | 11 | -22 |
| 25 | 15 | 6 | 3 | 18 |
| ... | ... | ... | ... | ... |
::: {.rmdnote}
Calculate the covariance by hand by making a table like the one above. (These variables are *not* mean centered, so you'll have to calculate the mean of each variable in order to fill out the third and fourth columns.)
$X_{3}$: 8, 10, 16, 7, 4, 3
$X_{4}$: 6, 5, 4, 9, 11, 7
Explain intuitively why the covariance is negative for these two variables.
:::
::: {.rmdnote}
When calculating variance, the order of the data points does not matter. Why?
When calculating covariance, the order of the data points *does* matter. Why?
What if you keep pairs together, but rearrange the rows of the table. How does that affect the covariance?
:::
## Calculating covariance in R {#covariance-r}
Once we’ve done it by hand a few times to make sure we understand how the formula works, from here on out we can let R do the work for us:
```{r}
X1 <- c(-1,-2, 2, -3, 4, -1, 1)
X2 <- c(-2, 2, -2, -1, 2, -2, 3)
cov(X1, X2)
```
```{r}
X3 <- c(8, 10, 16, 7, 4, 3)
X4 <- c(6, 5, 4, 9, 11, 7)
cov(X3, X4)
```
And here's some real world data. In addition to temperature (which we've already seen), we can use wind speed and see if there is an association between them:
```{r}
cov(airquality$Temp, airquality$Wind)
```
## Covariance rules {#covariance-rules}
We'll think of the variance and covariance rules as one big list. We left off on [**Rule 4**](./variance.html#Rule4), so now we'll introduce [**Rule 5**](#Rule5).
::: {.rmdimportant}
- <a id = "Rule5">**Rule 5**</a>
$$
Cov(X, X) = Var(X)
$$
:::
In words, [**Rule 5**](#Rule5) states that the covariance of a variable *with itself* is just the same thing as the variance of that variable. This is quite remarkable! It means that variance is really just a special case of covariance.
::: {.rmdnote}
Explain why [**Rule 5**](#Rule5) is true. (Hint: think about how you would calculate $Cov(X, X)$ using either the formula or the table---or both!)
:::
::: {.rmdimportant}
- <a id = "Rule6">**Rule 6**</a>
$$
Cov\left(X_{1}, X_{2}\right) = Cov\left(X_{2}, X_{1}\right)
$$
:::
In words, we would say that covariance is *symmetric*.
::: {.rmdnote}
Explain why [**Rule 6**](#Rule6) is true. (Again, think about the formula or the table---or both!)
:::
The next four rules are analogous to similar rules for variance ([**Rule 1**](./variance.html#Rule1), [**Rule 2**](./variance.html#Rule2), [**Rule 3**](./variance.html#Rule3), and [**Rule 4**](./variance.html#Rule4)).
::: {.rmdimportant}
- <a id = "Rule7">**Rule 7**</a>
Suppose that $C$ is a "constant" variable, meaning that it always has the same value (rather than being a variable that could contain lots of different numbers). Then,
$$
Cov\left(X, C\right) = 0
$$
:::
::: {.rmdnote}
As always, try to explain this rule. Give an intuitive explanation of why this rule "should" be true. Then think about it computationally, thinking of either the formula or the table---or both!
:::
::: {.rmdimportant}
- <a id = "Rule8">**Rule 8**</a>
$$
Cov\left(X_{1} + X_{2}, X_{3}\right) = Cov\left(X_{1}, X_{3}\right) + Cov\left(X_{2}, X_{3}\right)
$$
:::
What you should appreciate here is that there is no longer any restriction on the relationships among the variables involved. [**Rule 2**](./variance.html#Rule2) only worked when the two variables were independent. On the other hand, [**Rule 8**](#Rule8) works for any combination of variables, no matter their relation.
Even more satisfying is this next rule:
::: {.rmdimportant}
- <a id = "Rule9">**Rule 9**</a>
$$
Cov\left(X_{1} - X_{2}, X_{3}\right) = Cov\left(X_{1}, X_{3}\right) - Cov\left(X_{2}, X_{3}\right)
$$
:::
Yay! The minus sign behaves sensibly now! Of course, since covariances can be positive or negative (unlike variances which are always positive!) we can more safely subtract two of them without worry. And this rule, like [**Rule 8**](#Rule8), does not depend on $X_{1}$ and $X_{2}$ being independent. They can be any two variables.
There are versions of these rules with the addition or subtraction on the other side, but these are just minor variations of [**Rule 8**](#Rule8) and [**Rule 9**](#Rule9), so they're not worth mentioning as a separate rule. Remember that covariance is symmetric, so you can always swap things on the left and right of the comma.
::: {.rmdimportant}
$$
Cov\left(X_{1}, X_{2} \pm X_{3}\right) = Cov\left(X_{1}, X_{2}\right) \pm Cov\left(X_{1}, X_{3}\right)
$$
:::
::: {.rmdimportant}
- <a id = "Rule10">**Rule 10**</a>
If $a$ is any number,
$$
Cov\left(a X_{1}, X_{2}\right) = a Cov\left(X_{1}, X_{2}\right) = Cov\left(X_{1}, a X_{2}\right)
$$
:::
This rule is also very sensible. Instead of [**Rule 4**](./variance.html#Rule4) that takes a number $a$ and pulls out an $a^{2}$, [**Rule 10**](#Rule10) just pulls out a single factor of $a$ (from either slot).
Just a couple more rules. We were talking about independence in conjunction with [**Rule 8**](#Rule8) and [**Rule 9**](#Rule9). That leads directly to an interesting and super-important rule:
::: {.rmdimportant}
- <a id = "Rule11">**Rule 11**</a>
If $X_{1}$ and $X_{2}$ are independent, then
$$
Cov\left(X_{1}, X_{2}\right) = 0
$$
:::
::: {.rmdnote}
Why is [**Rule 11**](#Rule11) true, intuitively?
It's interesting to note that this rule only works one way. In other words, if you know that two variables are independent, then you can conclude their covariance is zero. However, if you know the covariance is zero, that doesn't necessarily mean that the two variables are independent. We'll see an example of this later in the chapter.
:::
Finally, one rule to rule them all:
::: {.rmdimportant}
- <a id = "Rule12">**Rule 12**</a>
For *any* two variables $X_{1}$ and $X_{2}$:
$$
Var(aX_{1} + bX_{2}) =
a^2Var(X_{1}) + b^2Var(X_{2}) + 2abCov(X_{1}, X_{2})
$$
:::
This brings practically everything we know together into one rule!
::: {.rmdnote}
Proving [**Rule 12**](#Rule12) will give us good practice with the type of manipulation we'll need to do in future chapters. So here goes. For the first few steps, you name what rule we're invoking. Then, you'll pick up the thread and follow it through the last few steps on your own.
\begin{align}
Var(aX_{1} + bX_{2}) &= Cov(aX_{1} + bX_{2}, aX_{1} + bX_{2}) \\
&= Cov(aX_{1} + bX_{2}, aX_{1}) + Cov(aX_{1} + bX_{2}, bX_{2}) \\
&= Cov(aX_{1}, aX_{1}) +
Cov(bX_{2}, aX_{1}) + \\
& \qquad Cov(aX_{1}, bX_{2}) +
Cov(bX_{2}, bX_{2}) \\
&= \quad ???
\end{align}
:::
You'll need these rules to do calculations in future chapters. Rather than having to search for them in Chapter \@ref(variance) and this chapter, we've gathered up all the rules in one convenient place in Appendix \@ref(appendix-rules).
## Correlation {#covariance-correlation}
The pros and cons for calculating covariance are similar to those for variance. The mathematics is much nicer for covariance, but we lose interpretability.
::: {.rmdnote}
Let's suppose that $X_{1}$ measures salary in dollars and $X_{2}$ measures years of education. We would expect there to be some association between these variables, so we calculate the covariance. What is the unit of measurement of the resulting number?
:::
The solution to the problem here is not as simple as it was for variance. Since variance had squared units, all we had to do was take the square root. Covariance has a weird product of units, so we have to do something more clever.
Following up on the activity above, let's suppose we have a covariance with units of "dollar-years". If we divide by a number expressed in dollars, we get rid of those units and we're left with years. But that seems unsatisfying; covariance should express something about both variables that went into it. Likewise, it makes no sense to divide by a number expressed in years as that would leave us just with dollars.
The solution to the dilemma is to accept that we aren't going to be able to keep any units in a meaningful way. Therefore, what we want is something *standardized*, meaning that it has no units.
::: {.rmdnote}
If $X_{1}$ is expressed in dollars, can you think of a statistic that measures spread and is also in units of dollars?
Likewise, if $X_{2}$ is measured in years, what statistic that measures spread is also in units of years?
:::
The previous activity gives us an idea. What if we divide the covariance by *both* the standard deviation of $X_{1}$ *and* the standard deviation of $X_{2}$?
$$
\frac{Cov(X_{1},X_{2})}{SD(X_{1}) SD(X_{2})}
$$
Sometimes it's written like this:
$$
\frac{Cov(X_{1},X_{2})}{\sqrt{Var(X_{1})} \sqrt{Var(X_{2})}}
$$
But that's the same thing, right?
This quantity has no units. We call this the *correlation* between $X_{1}$ and $X_{2}$. We'll either write
$$
Corr(X_{1}, X_{2})
$$
or, if we need to be more concise,
$$
r_{X_{1}X_{2}}
$$
Yes, this is the same as the correlation coefficient you learned about in your intro stats class, although it wasn't likely presented to you quite this way.^[Karl Pearson is credited with inventing the correlation coefficient. Pearson was a life-long eugenicist and a proponent of using "science" to prove that some races were superior to others. It important to disentangle the truly valuable notion of correlation from the discredited hands that may have first written it down. Therefore, we will not be referring to it in this text as the Pearson correlation coefficient.]
One great thing about correlation is that it has no units, so it serves as a sort of "universal" measure of how two variables co-vary. But the best part is that it has a nice intuitive meaning precisely because it factors out the pieces of the covariance that are only there because of the spread of the two variables individually. In other words, the fact that $X_{1}$ and $X_{2}$ have their own variability actually *complicates* the notion of covariance. Those individual variances "corrupt" the interpretation of covariance. But after excising them, all that's left in the correlation is the "pure" part of the covariance that expresses the relationship or association between $X_{1}$ and $X_{2}$.
## Covariance with standardized data {#covariance-standardized}
In the last chapter, you showed that the variance of a standardized variable was 1. What is the covariance between two standardized variables?
::: {.rmdnote}
Let's standardize both $X_{1}$ and $X_{2}$. To make the math a little easier, we'll use similar notation to what we used at the end of the last chapter.
$M_{1} = \overline{X_{1}}$
$S_{1} = SD(X_{1})$
$M_{2} = \overline{X_{2}}$
$S_{2} = SD(X_{2})$
And we'll write the z-scores in a way that is more amenable to mathematical manipulation (like before):
$$
Z_{1} = \frac{1}{S_{1}}\left(X_{1} - M_{1}\right)
$$
$$
Z_{2} = \frac{1}{S_{2}}\left(X_{2} - M_{2}\right)
$$
This looks a little more intimidating, but if you apply the rules, it works out:
\begin{align}
Cov(Z_{1}, Z_{2}) &= Cov\left( \frac{1}{S_{1}}\left(X_{1} - M_{1}\right), \frac{1}{S_{2}}\left(X_{2} - M_{2}\right) \right) \\
&= \quad ???
\end{align}
Work this out. Take your time. Apply the rules carefully. So that you know what you're aiming for, you should get
$$
Cov(Z_{1}, Z_{2}) = \frac{Cov\left( X_{1}, X_{2} \right)}{S_{1} S_{2}}
$$
Okay, now remember that $S_{1}$ is just a convenient substitute for $SD(X_{1})$ and $S_{2}$ is just a substitute for $SD(X_{2})$. Wait, does that answer look familiar?
:::
This is cool! Correlation is simply the covariance of two variables after they've been standardized.
This also reinforces the earlier comment about interpreting covariance after removing the extraneous influence of the spread of the individual variables. Standardizing variables makes the spread of all variables 1, so their covariance is now a pure representation of just the association between them.
You probably remember from intro stats that correlation takes on values between -1 and 1. That fact is not obvious from the formula we have. Why should the fraction
$$
\frac{Cov(X_{1},X_{2})}{SD(X_{1}) SD(X_{2})}
$$
be bounded by -1 and 1?
::: {.rmdnote}
Let's go back to standardized variable to keep things simple. The correlation is just the covariance of two standardized variables:
$$
Corr(X_{1}, X_{2}) = Cov(Z_{1}, Z_{2})
$$
Use the rules to calculate this:
$$
Var(Z_{1} + Z_{2})
$$
Remember that $Z_{1}$ and $Z_{2}$ are not necessarily independent. (In fact, we hope they are not. Otherwise, why do we care about their correlation? It would be zero!) So you need [**Rule 12**](#Rule12), not [**Rule 2**](./variance.html#Rule2). Keep manipulating until you get
$$
2 + 2Corr(X_{1}, X_{2})
$$
Since variances are always non-negative, we now know that
$$
0 \leq 2 + 2Corr(X_{1}, X_{2})
$$
Solve this inequality for $Corr(X_{1}, X_{2})$.
Now follow the exact same steps for
$$
Var(Z_{1} - Z_{2})
$$
Very little should change in your answer, but there is one small change. Again, solve the resulting inequality. (Don't forget the key rule when working with inequalities that multiplying or dividing by a negative number changes the direction of the inequality.)
:::
Here is a fact we will state without proof:
::: .{rmdimportant}
Correlations are only interpretable as the strength of **linear** associations.
:::
Why is this? Basically, it boils down to the fact that a "perfect" correlation of 1 or -1 is only achievable when data points lie on a perfectly straight line. Therefore, thinking of correlation as lying between 0 and 1 (or 0 and -1) is only sensible if you are judging how close points are to lying on a straight line. We'll see examples of this in the next section when we plot some data.
To calculation correlation in R, use the `cor` command:
```{r}
cor(airquality$Temp, airquality$Wind)
```
::: {.rmdnote}
Use R to confirm that the number above is the covariance divided by the product of the standard deviations.
:::
## Visualizing correlation {#covariance-visualizing}
Covariance is hard to interpret, so when we're visualizing data and we want to understand any association that might exist between two variables, correlation is a much better statistic to calculate. Let's see how correlation relates to the graph of two variables.
Before getting into the graphing, we will need to load some packages. The `tidyverse` is a whole set of commonly used packages that will allow us to work with data frames (or "tibbles" as the cool kids are calling them) and make graphs. Be sure to load the package by typing the following in R before going any further:
```{r}
library(tidyverse)
```
In fact, from here on out, we'll start each chapter by loading any necessary libraries in R that we'll need.
The standard graph of two numerical variables is a scatterplot. Let's start with a straight line relationship. First, we define two variables. We'll use some shortcuts here to make our lives a little easier. The `seq` command just generates a sequence of numbers.
```{r}
X5 <- seq(1, 9)
X5
```
Then we can establish a linear relationship just by declaring one in a formula:
```{r}
X6 <- 3 + 0.5 * X5
X6
```
To put both variables into the same graph, it helps to make them both columns in a single tibble.
```{r}
linear_data <- tibble(X5, X6)
linear_data
```
And here is the graph:
```{r}
ggplot(linear_data, aes(y = X6, x = X5)) +
geom_point()
```
Now the correlation:
```{r}
cor(X5, X6)
```
It is 1, as expected.
What about a perfectly straight line with a negative slope?
```{r}
X7 <- 5 - 0.2 * X5
X7
```
We'll throw this new variable into the tibble we already have (for convenience). To explain the syntax below, the `%>%` symbol is called a "pipe" and it tells R to pass the `linear_data` tibble on to the next row to process it. And the processing itself is dictated by the `bind_cols` command which tells R to "bind a new column" to the tibble. The part that says `X7 = X7` may be a little confusing. It says to add the new column `X7`, but also still call it `X7`.
```{r}
linear_data <- linear_data %>%
bind_cols(X7 = X7)
linear_data
```
```{r}
ggplot(linear_data, aes(y = X7, x = X5)) +
geom_point()
```
```{r}
cor(X5, X7)
```
Again, that is what we expected.
What happens if we plot random data? The `runif` command just chooses random numbers uniformly between 0 and 1.^[Sean's brain always want to parse this command as "run if". Run if what? No, no, it's "r unif".] We use `set.seed` to make our work reproducible. You will get the same set of random numbers on your machine if you use the same seed as we use here.
```{r}
set.seed(1234)
X8 <- runif(20)
X9 <- runif(20)
```
```{r}
X8
```
```{r}
X9
```
```{r}
random_data <- tibble(X8, X9)
random_data
```
```{r}
ggplot(random_data, aes(y = X9, x = X8)) +
geom_point()
```
::: {.rmdnote}
What do you guess is the correlation between $X_{8}$ and $X_{9}$?
Now calculate it using R? Did you get the *exact* answer you guessed? If not, why not?
:::
What about data that follows a perfect mathematical relationship that is not a straight line? For example, here is a part of a parabola.
```{r}
X10 <- 0.1 * X5^2
X10
```
```{r}
nonlinear_data <- tibble(X5, X10)
nonlinear_data
```
```{r}
ggplot(nonlinear_data, aes(y = X10, x = X5)) +
geom_point()
```
Now for the correlation:
```{r}
cor(X5, X10)
```
This is a large correlation, but it is not exactly 1, even though the points follow a precise mathematical relationship. That relationship is not linear.
Here's a fascinating example. For this, we'll want a parabola that goes down and then up.
```{r}
X11 <- 0.5 * (X5 - 5)^2
X11
```
```{r}
nonlinear_data <- nonlinear_data %>%
bind_cols(X11 = X11)
nonlinear_data
```
```{r}
ggplot(nonlinear_data, aes(y = X11, x = X5)) +
geom_point()
```
::: {.rmdnote}
Before looking at the answer, what is your guess for the correlation between $X_{5}$ and $X_{11}$?
Now calculate the correlation in R.
Again, there's a perfect mathematical relationship between these two variables. They are most definitely associated. So why is the correlation 0?
:::
Recall the earlier promise to discuss [**Rule 11**](#Rule11). If two variables are independent, then their covariance is zero, and, therefore, their correlation is also zero. However, this rule doesn't work the other way around. The claim is that knowing the covariance/correlation is zero does not imply (necessarily) that the two variables are independent. Here is the promised example of that phenomenon. $X_{5}$ and $X_{11}$ have zero correlation. And yet, $X_{5}$ and $X_{11}$ are definitely *not* independent.
This is important enough for a fancy box:
::: {.rmdimportant}
**When you see that the correlation between two variables is zero or near zero, be careful not to conclude that the variables are independent.**
:::
A zero or near-zero correlation indicates only the lack of a *linear* association between two variables. There may be nonlinear associations. That's why it's always a good idea to graph your data.
Real data is, of course, much messier and it's just not possible to have perfect correlations between two variables measured out there in the real world. (If you do find a perfect correlation between two columns of your data, chances are that you either recorded the same column twice, or the second column is some simple transformation of first column, like multiplying every value by the same number or something like that.)
Here is a plot of the temperature (degrees Fahrenheit) and wind speed (mph) from the New York air quality data set.
```{r}
ggplot(airquality, aes(y = Temp, x = Wind)) +
geom_point()
```
::: {.rmdnote}
Just looking at the scatterplot (without calculating anything), is the correlation between these two variables positive or negative? Try guessing the exact value of the correlation.
Now calculate the exact value of the correlation to see how close you were.
:::
::: {.rmdnote}
If you want some practice with looking at scatterplots and guessing the correlation, try this online game:
[Guess the Correlation](http://guessthecorrelation.com/)
Turn up the sound! If the whole class plays at the same time, your classroom will sound like an arcade. Compete with your classmates to see who can get the high score.
:::