-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-correlation.qmd
2617 lines (2060 loc) · 93.9 KB
/
08-correlation.qmd
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
---
execute:
cache: true
---
# Correlation coefficient {#sec-chap08}
```{r}
#| label: setup
#| include: false
base::source(file = "R/helper.R")
ggplot2::theme_set(ggplot2::theme_bw())
```
## Achievements to unlock
:::::: {#obj-chap08}
::::: my-objectives
::: my-objectives-header
Objectives for chapter 08
:::
::: my-objectives-container
**SwR Achievements**
- **Achievement 1**: Exploring the data using graphics and descriptive statistics (@sec-chap08-achievement1).
- **Achievement 2**: Computing and interpreting Pearson’s *r* correlation coefficient (@sec-chap08-achievement2).
- **Achievement 3**: Conducting an inferential statistical test for Pearson’s *r* correlation coefficient (@sec-chap08-achievement3).
- **Achievement 4**: Examining effect size for Pearson’s *r* with the coefficient of determination (@sec-chap08-achievement4).
- **Achievement 5**: Checking assumptions for Pearson’s *r* correlation analyses (@sec-chap08-achievement5).
- **Achievement 6**: Transforming the variables as an alternative when Pearson’s *r* correlation assumptions are not met (1).
- **Achievement 7**: Using Spearman’s rho as an alternative when Pearson’s *r* correlation assumptions are not met (@sec-chap08-achievement7).
- **Achievement 8**: Introducing partial correlations (@sec-chap08-achievement8).
:::
:::::
Achievements for chapter 08
::::::
## The clean water conundrum
- Women and girls tend to be responsible for collecting water for their families, often walking long distances in unsafe areas and carrying heavy loads.
- In some cultures, lack of access to sanitation facilities also means that women can only defecate after dark, which can be physically uncomfortable and/or put them at greater risk for harassment and assault.
- The lack of sanitation facilities can keep girls out of school when they are menstruating.
**Goals**
1. With data from a few different sources examining the relationship between the percentage of people in a country with water access and the percentage of school-aged girls who are in school.
2. With data exploring the relationship between the percentage of females in school and the percentage of people living on less than \$1 per day.
## Resources & Chapter Outline
### Data, codebook, and R packages {#sec-chap08-data-codebook-packages}
::::::::: my-resource
:::: my-resource-header
::: {#lem-chap08-resources}
: Data, codebook, and R packages for learning about descriptive statistics
:::
::::
:::::: my-resource-container
**Data**
Two options:
1. Download the `water_educ_2015_who_unesco_ch8.csv` and `2015-outOfSchoolRate-primarySecondary-ch8.xlsx` data sets from <https://edge.sagepub.com/harris1e>.
2. Follow the instructions in Box 8.1 to import and clean the data directly from the original Internet sources. Please note that the WHO makes small corrections to past data occasionally, so use of data imported based on Box 8.1 instructions may result in minor differences in results throughout the chapter. To match chapter results exactly, use the data provided.
::::: my-note
::: my-note-header
Using data provided from the book
:::
::: my-note-container
I have learned a lot about data cleaning procedures in the last chapters. I feel secure and decided from now on that I will take data provided by the book. This help me to focus my attention on the statistical subjects of the book.
:::
:::::
**Codebook**
Two options:
1. Download the codebook file `opioid_county_codebook.xlsx` from <https://edge.sagepub.com/harris1e>.
2. Use the online version of the codebook from the amfAR Opioid & Health Indicators Database website (https://opioid.amfar.org)
**Packages**
1. Packages used with the book (sorted alphabetically) (Install the following R packages if not already installed.)
- {**tidyverse**}: @sec-tidyverse (Hadley Wickham)
- {**readxl**}: @sec-readxl (Jennifer Bryan)
- {**lmtest**}: @sec-lmtest (Achim Zeileis)
- {**rcompanion**}: @sec-rcompanion (Salvatore Mangiafico)
- {**ppcor**}: @sec-ppcor (Seongho Kim)
2. My additional packages (sorted alphabetically)
::::::
:::::::::
### Get data & show raw data
::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap08-get-data}
: Get data and show raw for chapter 8
:::
::::
:::::::::::: my-example-container
::::::::::: panel-tabset
###### Get water-educ
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-get-water-educ-data}
: Get Water-Education data
:::
::::
::: my-r-code-container
```{r}
#| label: get-water-educ-data
#| eval: false
## run only once (manually)
water_educ <- readr::read_csv(
file = "data/chap08/water_educ_2015_who_unesco_ch8.csv",
show_col_types = FALSE
)
save_data_file("chap08", water_educ, "water_educ.rds")
```
(*For this R code chunk is no output available*)
:::
::::::
###### Show water_educ
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-show-water-educ}
: Show Water & Education data
:::
::::
::: my-r-code-container
```{r}
#| label: tbl-show-water-educ
#| tbl-cap: "Show descriptive data from the Water-Edcuation UNESCO file"
water_educ <- base::readRDS("data/chap08/water_educ.rds")
water_educ |>
skimr::skim()
```
------------------------------------------------------------------------
Instead of `base::summary()` I used `skimr::skim()` which fives more descriptive information.
**Codebook**
- **country**: the name of the country
- **med.age**: the median age of the citizens in the country
- **perc.1dollar**: percentage of citizens living on \$1 per day or less
- **perc.basic2015sani**: percentage of citizens with basic sanitation access
- **perc.safe2015san**i: percentage of citizens with safe sanitation access
- **perc.basic2015water**: percentage of citizens with basic water access
- **perc.safe2015water**: percentage of citizens with safe water access
- **perc.in.school**: percentage of school-age people in primary and secondary school
- **female.in.school**: percentage of female school-age people in primary and secondary school
- **male.in.school**: percentage of male school-age people in primary and secondary school
:::
::::::
:::::::::::
::::::::::::
:::::::::::::::
## Exploring data {#sec-chap08-achievement1}
The two variables of interests are:
- female.in.school and
- perc.basic2015water
:::::::::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap08-exploring-data}
: Exploring data for chapter 8
:::
::::
::::::::::::::::::: my-example-container
:::::::::::::::::: panel-tabset
###### mean & sd
::::::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-mean-sd-water-educ}
: Mean and standard deviation for `female.in.school` and `perc.basic2015water`
:::
::::
:::::: my-r-code-container
```{r}
#| label: mean-sd-water-educ
water_educ |>
skimr::skim(c(female.in.school, perc.basic2015water)
)
```
------------------------------------------------------------------------
The mean percent of school-aged females in school was 87.06 (sd = 15.1), and the mean percent of citizens who had basic access to water was 90.16 (sd = 15.82).
This is a pretty high percentage. The very high median shows that there is a heavy left-skewed distribution. 93 & 97% are in the first half of the distribution located!
::::: my-note
::: my-note-header
Advantages of the `skimr::skim()` function
:::
::: my-note-container
This above summary show the advantage of the `skimr::skim()` function versus the `base::summary()` resp. the extra calculation of mean and sd. `skimr::skim()` is (a) easier to use (just one line!) and (b) displays much more information, e.g., different percentiles with a small histogram. Important here is, for instance, that we can compare mean and median in one step.
:::
:::::
::::::
:::::::::
###### scatterplot1
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-scatterplot-female-water}
: Scatterplot of `female.in.school` and `perc.basic2015water`
:::
::::
::: my-r-code-container
```{r}
#| label: fig-scatterplot-female-water
#| fig-cap: "Relationship of percentage of females in school and percentage of citizens with basic water access in countries worldwide"
water_educ |>
ggplot2::ggplot(
ggplot2::aes(
x = female.in.school / 100,
y = perc.basic2015water / 100
)
) +
ggplot2::geom_point(
na.rm = TRUE,
ggplot2::aes(
color = "Country"
),
size = 2.5,
alpha = 0.3
) +
ggplot2::labs(
x = "Percent with basic water access",
y = "Percent of school-aged females in school"
) +
ggplot2::scale_color_manual(
name = "",
values = "purple3"
) +
ggplot2::scale_x_continuous(
labels = scales::label_percent()
) +
ggplot2::scale_y_continuous(
labels = scales::percent
)
```
------------------------------------------------------------------------
I have used two different argument styles for the percent scale from the {**scales**} package (see: @sec-scales):
- `labels = scales::percent` as in the book
- `labels = scales::label_percent()` from the help file of the {**scales**} package.
:::
::::::
###### scatterplot2
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-scatterplot-female-dollar}
: Scatterplot of `female.in.school` and `perc.1dollar`
:::
::::
::: my-r-code-container
```{r}
#| label: fig-scatterplot-female-dollar
#| fig-cap: "Relationship of percentage of females in school and percentage of people living on less than $1 per day in countries worldwide"
water_educ |>
ggplot2::ggplot(
ggplot2::aes(
x = perc.1dollar / 100,
y = female.in.school / 100
)
) +
ggplot2::geom_jitter(
na.rm = TRUE,
ggplot2::aes(
color = "Country"
),
size = 2.5,
alpha = 0.3
) +
ggplot2::labs(
x = "Percent of people living on less than $1 per day",
y = "Percent with basic water access"
) +
ggplot2::scale_color_manual(
name = "",
values = "purple3"
) +
ggplot2::scale_x_continuous(
labels = scales::label_percent()
) +
ggplot2::scale_y_continuous(
labels = scales::percent
)
```
------------------------------------------------------------------------
:::
::::::
::::::::::::::::::
:::::::::::::::::::
::::::::::::::::::::::
## Pearson’s *r* correlation coefficient {#sec-chap08-achievement2}
### Introduction
One method of measuring the relationship between two continuous variable is `r glossary("covariance cov", "covariance")`, which quantifies whether two variables vary together (co-vary).
:::::: my-theorem
:::: my-theorem-header
::: {#thm-chap08-covariance}
: Formula for covariance
:::
::::
::: my-theorem-container
$$
cov_{xy} = \sum_{i=1}^{n}\frac{(x_{i}-m_{x})(y_{i}-m_{y})}{n-1}
$$ {#eq-chap08-covariance}
:::
::::::
The numerator essentially adds up how far each observation is away from the mean values of the two variables being examined, so this ends up being a very large number quantifying how far away all the observations are from the mean values. The denominator divides this by `r glossary("Bessel’s correction")` (@sec-chap04-clt) of $n – 1$, which is close to the sample size and essentially finds the average deviation from the means for each observation.
I skipped Figure 8.4 and 8.5 because they do not bring any news for me. (Note that there is a wrong label for x-axis in Figure 8.5: Instead of "Percent living on less than \$1 per day" it says wrongly "Percent with basic water access".)
### Missing values
The covariance function `stats::cov()` is like the `base::mean()` function in that it cannot handle NA values. As we are going to calculate `female.in.school` with `perc.basic2015water` and `female.in.school` with `perc.1dollar` we would have three different variables with NA's.
It is important not to to remove all rows with missing data of all three variables at the same time because that would delete more rows as for each pair of variable would be necessary. We know from @tbl-show-water-educ that
- `female.in.school` has no missing values
- `perc.basic2015water` has 1 missing value
- `perc.1dollar` has 33 missing values
There are two options:
a) To use two different covariance calculations, each time with the appropriate `tidyr::drop_na()` function as used finally in the book.
b) To apply the appropriate `use` argument of the `stats::cov()` function for each calculations, which I will use and which was the first try in the book.
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-cov-female-water-pov}
: Covariance of females in school and percentage with basic access to drinking water
:::
::::
::: my-r-code-container
```{r}
#| label: cov-female-water-pov
water_educ |>
dplyr::summarize(
cov_females_water = stats::cov(
x = perc.basic2015water,
y = female.in.school,
use = "pairwise.complete.obs",
method = "pearson"
),
cov_females_pov = stats::cov(
x = perc.1dollar,
y = female.in.school,
use = "pairwise.complete.obs",
method = "pearson")
)
```
------------------------------------------------------------------------
The book argument for NA's is `use = "complete"` which is an allowed abbreviation for `use = "complete.obs"`. I have employed `use = "pairwise.complete.obs"` which is a more precise argument but works only for the (default) "pearson" method.
:::
::::::
### Interpretation
The covariance does not have an intuitive inherent meaning; it is not a percentage or a sum or a difference. In fact, the size of the covariance depends largely on the size of what is measured. For example, something measured in millions might have a covariance in the millions or hundreds of thousands. The value of the covariance indicates whether there is a relationship at all and the direction of the relationship --- that is, whether the relationship is positive or negative.
In this case, a nonzero value indicates that there is some relationship. In the first case (`cov_females_water`) it is a positive relationship; in the second case (`cov_females_pov`) it is a negative relationship. The size of the numbers are irrelevant!
Therefore `r glossary("standardization")` by dividing by the `r glossary("standard deviation")` of the two involved variables is necessary. The result is called the `r glossary("correlation", "correlation coefficient")` and is referred to as *r*.
:::::::::: my-theorem
:::: my-theorem-header
::: {#thm-chap08-pearson-r}
: Computing the Pearson *r* correlation between two variables
:::
::::
::::::: my-theorem-container
$$
\begin{align*}
r_{xy} = \frac{cov_{xy}}{s_{x}s_{y}} \\
r_{xy} = \sum_{i = 1}^{n}\frac{z_{x}z_{y}}{n-1}
\end{align*}
$$ {#eq-chap08-pearson-r}
------------------------------------------------------------------------
The second line is also know as the product-moment correlation coefficient. The formula for *r* can be organized in many different ways, one of which is as the mean of the summed products of `r glossary("z-score", "z-scores")`.
:::::: my-assessment
:::: my-assessment-header
::: {#cor-chap08-pearson-r}
: Range of Pearson’s *r* and interpretation of strength
:::
::::
::: my-assessment-container
- **-1: Negative correlations** occur when one variable goes up and the other goes down.
- **0: No correlation** happens when there is no discernable pattern in how two variables vary.
- **+1: Positive correlations** occur when one variable goes up, and the other one also goes up (or when one goes down, the other one does too).
------------------------------------------------------------------------
- **r = –1.0** is perfectly negative
- **r = –.8** is strongly negative
- **r = –.5** is moderately negative
- **r = –.2** is weakly negative
- **r = 0** is no relationship
- **r = .2** is weakly positive
- **r = .5** is moderately positive
- **r = .8** is strongly positive
- **r = 1.0** is perfectly positive
:::
::::::
:::::::
::::::::::
:::::::::::::::::::::::::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap08-correlation}
: Compute and show correlation
:::
::::
::::::::::::::::::::::::::::::::::: my-example-container
:::::::::::::::::::::::::::::::::: panel-tabset
###### compute cor()
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-cor-water-pov-female}
: Compute correlations for water access, poverty and female education
:::
::::
::: my-r-code-container
```{r}
#| label: cor-water-pov-female
water_educ <- base::readRDS("data/chap08/water_educ.rds")
water_educ |>
dplyr::summarize(
cor_females_water = cor(
x = perc.basic2015water,
y = female.in.school,
use = "complete.obs"
),
cor.females.pov = cor(
x = perc.1dollar,
y = female.in.school,
use = "complete.obs"
)
)
```
:::
::::::
###### graph1 cor
::::::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-graph1-cor}
: Display correlation water access and female education with `lm` and `loess` smoother with a special constructed legend
:::
::::
:::::: my-r-code-container
```{r}
#| label: fig-graph1-cor
#| fig-cap: "Display correlation water access and female education with `lm` and `loess` smoother with a special constructed legend"
water_educ |>
ggplot2::ggplot(
ggplot2::aes(
y = female.in.school/100,
x = perc.basic2015water/100
)
) +
ggplot2::geom_smooth(
ggplot2::aes(color = "Linear fit line"),
formula = y ~ x,
method = "lm",
se = FALSE,
na.rm = TRUE
) +
ggplot2::geom_smooth(
ggplot2::aes(color = "Loess line"),
formula = y ~ x,
method = "loess",
se = FALSE,
na.rm = TRUE
) +
ggplot2::geom_point(
ggplot2::aes(size = "Country"),
color = "#7463AC",
alpha = .6,
na.rm = TRUE
) +
ggplot2::labs(
y = "Percent of school-aged females in school",
x = "Percent with basic water access"
) +
ggplot2::scale_x_continuous(labels = scales::percent) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::scale_color_manual(
values = c("gray60", "darkred"),
name = ""
) +
ggplot2::scale_size_manual(values = 2, name = "")
```
------------------------------------------------------------------------
**`ggplot2::geom_smooth()` layer**
- The formula argument would not be necessary, because the program assumes y \~ x for fewer than 1000 observations.
- If I haven't specified the method with `lm` than the default value would have been chosen, e.g. (depending on fewer than 1000) which is a local polynomial regression fitting.
- To show the difference I had used both `method = lm` and in another layer `method = loess`. The `r glossary("Loess", "Loess curve")` results in the slightly curved line (the red curve). Instead of fitting the whole data at once (= "lm"), method "loess" creates a local regression because the fitting at say point x is weighted toward the data nearest to x and not to the general mean.
::::: my-watch-out
::: my-watch-out-header
WATCH OUT! Legends are generated from attributes inside the `ggplot2::aes()` statement
:::
::: my-watch-out-container
It is important to know:
- If all aesthetics are determined outside the `ggplot2::aes()` functions then there is not legend generated.
- The name of the aesthetics are arbitrary and result as labels inside the legend.
In this case I have used twice the "color" aesthetic, but as value I gave as argument was the type of line and not an actual color. The actual color for the lines you will fin in the `ggplot2::scale_color_manual()` layer at the very bottom of the code.
See also the next two graphs (@fig-graph2-cor and @fig-graph3-cor) about water access and female education where I have explored different types of points and lines inside the aesthetic function.
:::
:::::
::::::
:::::::::
###### graph2 cor
::::::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-graph3-cor}
: Display correlation water access and female education with two legends explaining what the different symbols represent
:::
::::
:::::: my-r-code-container
```{r}
#| label: fig-graph2-cor
#| fig-cap: "Display correlation water access and female education with two legends explaining what the different symbols represent"
water_educ |>
ggplot2::ggplot(
ggplot2::aes(
y = female.in.school/100,
x = perc.basic2015water/100
)
) +
ggplot2::geom_smooth(
ggplot2::aes(color = "Linear fit line"),
formula = y ~ x,
method = "lm",
se = FALSE,
na.rm = TRUE
) +
ggplot2::geom_point(
ggplot2::aes(size = "Country"),
color = "#7463AC",
alpha = .6,
na.rm = TRUE
) +
ggplot2::labs(
y = "Percent of school-aged females in school",
x = "Percent with basic water access"
) +
ggplot2::scale_x_continuous(labels = scales::percent) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::scale_color_manual(values = "gray60", name = "Legend 2") +
ggplot2::scale_size_manual(values = 2, name = "Legend 1")
```
------------------------------------------------------------------------
::::: my-watch-out
::: my-watch-out-header
WATCH OUT! Legends are generated from attributes inside the `ggplot2::aes()` statement
:::
::: my-watch-out-container
The two `ggplot2::aes()` functions used for this graph are `ggplot2::aes(size = "Country")` and `ggplot2::aes(linetype = "Linear fit line")`. To get two different legends (point and lines), two different attributes were used within the `aes()`.
:::
:::::
::::::
:::::::::
###### graph3 cor
:::::::::: my-r-code
:::: my-r-code-header
<div>
: Display correlation water access and female education with a legend explaining what the different symbols represent
</div>
::::
::::::: my-r-code-container
```{r}
#| label: fig-graph3-cor
#| fig-cap: "Display correlation water access and female education with a legend explaining what the different symbols represent"
water_educ |>
ggplot2::ggplot(
ggplot2::aes(
y = female.in.school/100,
x = perc.basic2015water/100
)
) +
ggplot2::geom_smooth(
ggplot2::aes(color = "Linear fit line"),
formula = y ~ x,
method = "lm",
se = FALSE,
na.rm = TRUE
) +
ggplot2::geom_point(
ggplot2::aes(color = "Country"),
size = 2,
alpha = .6,
na.rm = TRUE
) +
ggplot2::labs(
y = "Percent of school-aged females in school",
x = "Percent with basic water access"
) +
ggplot2::scale_x_continuous(labels = scales::percent) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::scale_color_manual(
name = "Legend",
values = c("#7463AC", "gray60")
)
```
------------------------------------------------------------------------
::::: my-watch-out
::: my-watch-out-header
WATCH OUT! The name of the attribute inside the `aes()` is arbitrary
:::
::: my-watch-out-container
@fig-graph3-cor has the color attribute for both the points and the line within `aes()` and so both colors are included in the only legend.
The name of the attribute inside the `aes()` is arbitrary and will result in the **label of the legend**. The type of this attribute has to be addressed and specified with the correct manual scale (`ggplot2::scale_xxx_manual()`) and will display the appropriate symbol for the attribute.
**ATTENTION**: With new versions of {**ggplot2**} the symbols are not merged as in the book’s version. This would have been not correct, because the line does not go through all points. Points and lines are different aesthetics but they are merged under on legend with one common attribute, their color.
:::
:::::
::: callout-tip
The Pearson’s product-moment correlation coefficient demonstrated that the percentage of females in school is positively correlated with the percentage of citizens with basic access to drinking water (r = 0.81). Essentially, as access to water goes up, the percentage of females in school also increases in countries.
:::
:::::::
::::::::::
###### graph4 cor
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-graph4-cor}
: Display relationship of percentage of citizens living on less than \$1 per day and the percent of school-aged females in school in countries worldwide
:::
::::
::: my-r-code-container
```{r}
#| label: fig-graph4-cor
#| fig-cap: "Display correlation of percentage of citizens living on less than $1 per day and the percent of school-aged females in school in countries worldwide"
water_educ |>
ggplot2::ggplot(
ggplot2::aes(
y = female.in.school/100,
x = perc.1dollar/100
)
) +
ggplot2::geom_smooth(
ggplot2::aes(color = "Linear fit line"),
formula = y ~ x,
method = "lm",
se = FALSE,
na.rm = TRUE
) +
ggplot2::geom_point(
ggplot2::aes(color = "Country"),
size = 2,
alpha = .6,
na.rm = TRUE
) +
ggplot2::labs(
y = "Percent of school-aged females in school",
x = "Percent of citizens living on less than $1 per day"
) +
ggplot2::scale_x_continuous(labels = scales::percent) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::scale_color_manual(
name = "",
values = c("#7463AC", "gray60")
)
```
------------------------------------------------------------------------
:::
::::::
::: callout-tip
The Pearson’s product-moment correlation coefficient demonstrated that the percentage of females in school is negatively correlated with the percentage of citizens living on less than \$1 per day (r = -0.71). Essentially, as the percentage of citizens living on less than \$1 per day goes up, the percentage of females in school decreases in countries.
:::
::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::
## Achievement 3: Inferential statistical test for Pearson’s r {#sec-chap08-achievement3}
### Introduction
The null hypothesis is tested using a `r glossary("t-statistic")` comparing the `r glossary("correlation", "correlation coefficient of r")` to a hypothesized value of zero.
:::::: my-theorem
:::: my-theorem-header
::: {#thm-chap08-cor-test}
: One.sample t-test
:::
::::
::: my-theorem-container
$$
t = \frac{m_{x}-0}{se_{m_{x}}}
$$ {#eq-chap08-one-sample-t-test}
------------------------------------------------------------------------
- $m_{x}$: mean of $x$
- $se_{m_{x}}$: standard error of the mean of $x$
:::
::::::
But we are not actually working with means, but instead comparing the correlation of $r_{xy}$ to zero.
:::::: my-theorem
:::: my-theorem-header
<div>
: Rewriting @eq-chap08-one-sample-t-test to get the t-statistic for the significance test of *r*
</div>
::::
::: my-theorem-container
$$
t = \frac{r_{xy}}{se_{r_{xy}}}
$$ {#eq-chap08-t-test-for-r}
:::
::::::
There are multiple ways to compute the standard error for a correlation coefficient:
:::::: my-theorem
:::: my-theorem-header
::: {#thm-chap08-se-for-r}
: Standard error for a correlation coefficient
:::
::::
::: my-theorem-container
$$
se_{r_{xy}} = \sqrt\frac{1-r_{xy}^2}{n-2}
$$ {#eq-chap08-se-for-r}
:::
::::::
Now we can substitute $se_{r_{xy}}$ into the t-statistic of @eq-chap08-t-test-for-r and simplify the formula.
:::::: my-theorem
:::: my-theorem-header
<div>
: t-statistic for the significance test of r
</div>
::::
::: my-theorem-container
$$
\begin{align*}
t = \frac{r_{xy}}{\sqrt\frac{1-r_{xy}^2}{n-2}} =\\
t = \frac{r_{xy}\sqrt{n-2}}{\sqrt{1-r_{xy}^2}}
\end{align*}
$$ {#eq-chap08-t-test-for-significance-test-r}
:::
::::::
### NHST Step 1
Write the null and alternate hypotheses:
::: callout-note
- **H0**: There is no relationship between the two variables (r = 0).
- **HA**: There is a relationship between the two variables (r ≠ 0).
:::
### NHST Step 2
Compute the test statistic.
::::::::::::::: my-example
:::: my-example-header
::: {#exm-ID-text}
: Compute t-statistic for the significance test of r
:::
::::
:::::::::::: my-example-container
::::::::::: panel-tabset
###### manual
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-cor-test-manual}
: Compute t-statistic for the significance test of *r* manually
:::
::::
::: my-r-code-container
```{r}
#| label: cor-test-manual
test_data <- water_educ |>
tidyr::drop_na(perc.basic2015water) |>
tidyr::drop_na(female.in.school) |>
dplyr::summarize(
cor_females_water = cor(
x = perc.basic2015water,
y = female.in.school
),
sample_n = dplyr::n()
)
(test_data$cor_females_water * (sqrt(test_data$sample_n - 2))) /
(sqrt(1 - (test_data$cor_females_water^2)))
```
:::
::::::
###### cor.test()
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-cor-test-pearson}
: Compute t-statistic for the significance test of *r* with `stats::cor.test()`
:::
::::
::: my-r-code-container
```{r}
#| label: tbl-cor-test-pearson
#| tbl-cap: "T-statistic for the significance test of *r* with `stats::cor.test()`"
# cor.test(x = water_educ$perc.basic2015water,
# y = water_educ$female.in.school)
# using instead the formula interface
cor.test(
formula = ~ female.in.school + perc.basic2015water,
data = water_educ
)
```
------------------------------------------------------------------------
I have used the formula interface because it has a different syntax as I thought. My first trials were with `female.in.school ~ perc.basic2015water` but this didn't work. The (last) example in the help page demonstrated to me the other syntax.
Note that it is not necessary to remove NA’s before applying `cor.test()` in both cases.
:::
::::::
:::::::::::
::::::::::::
:::::::::::::::
------------------------------------------------------------------------
### NHST Step 3
Review and interpret the test statistics: Calculate the probability that your test statistic is at least as big as it is if there is no relationship (i.e., the null is true).
The very tiny p-value is statistically significant.
### NHST Step 4
Conclude and write report.
::: callout-tip
The percentage of people who have basic access to water is statistically significantly, positively, and very strongly correlated with the percentage of primary- and secondary-age females in school in a country \[r = .81; t(94) = 13.33; p \< .05\]. As the percentage of people living with basic access to water goes up, the percentage of females in school also goes up. While the correlation is .81 in the sample, it is likely between .73 and .87 in the population (95% CI: .73–.87).
:::
## Achievement 4: Coefficient of determiniation as effect size {#sec-chap08-achievement4}
Pearson’r is already a kind of effect size because it measures the strength of a relationship. But with the `r glossary("determination", "coefficient of determination")` $R^2$ (also $r^2$) there is another effect size measure with a more direct interpretation. The coefficient of determination is the percentage of the variance in one variable that is shared, or explained, by the other variable.
:::::: my-theorem
:::: my-theorem-header
::: {#thm-chap08-formula-r-squared}
: Computing the coefficient of determination $R^2$
:::
::::
::: my-theorem-container
$$
r_{xy}^2 = (\frac{cov_{xy}}{s_{x}s_{y}})^2
$$ {#eq-chap08-r-squared}
:::
::::::
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap08-compute-r-squared}
: Compute r-squared ($R^2$)
:::
::::
::: my-r-code-container
```{r}
#| label: compute-r-squared
(stats::cor.test(
x = water_educ$perc.basic2015water,
y = water_educ$female.in.school)$estimate
)^2
```
------------------------------------------------------------------------
The `stats::cor.test()` function creates an object of type `htest` which is a list of 9 different object. One of these object is the numeric vector `estimate` that holds the correlation value. There are two option to calculate r-squared:
1. Assign the result of `stats::cor.test()` function to a named object. Append `$estimate^2` to this object to get r-squared. I have this done in one step, and appended `$estimate^2` at the end of the function without providing an interim object.