-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09-linear-regression.qmd
3971 lines (2951 loc) · 135 KB
/
09-linear-regression.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
# Linear regression {#sec-chap09}
```{r}
#| label: setup
#| include: false
options(warn = 0) # default value: change for debugging
base::source(file = "R/helper.R")
ggplot2::theme_set(ggplot2::theme_bw())
```
::: {.callout-note #nte-chap09-differenct-chapter-structure style="color: blue;"}
### Different chapter structure, especially in `r glossary("EDA")` (@sec-chap09-achievement1)
As I have already read some books on linear regression I will not follow exactly the text in this chapter. I will leave out those passages that are not new for me and where I feel confident. Other passages I will only summarize to have content to consult whenever I would need it.
:::
## Achievements to unlock
::: {#obj-chap09}
::: {.my-objectives}
::: {.my-objectives-header}
Objectives for chapter 09
:::
::: {.my-objectives-container}
**SwR Achievements**
- **Achievement 1**: Using exploratory data analysis to learn about the data before developing a linear regression model (@sec-chap09-achievement1)
- **Achievement 2**: Exploring the statistical model for a line (@sec-chap09-achievement2)
- **Achievement 3**: Computing the slope and intercept in a simple linear regression (@sec-chap09-achievement3)
- **Achievement 4**: Slope interpretation and significance ($b_{1}$, p-value, CI) (@sec-chap09-achievement4)
- **Achievement 5**: Model significance and model fit (@sec-chap09-achievement5)
- **Achievement 6**: Checking assumptions and conducting diagnostics (@sec-chap09-achievement6)
- **Achievement 7**: Adding variables to the model and using transformation (@sec-chap09-achievement7)
:::
:::
Achievements for chapter 09
:::
## The needle exchange examination
Some infectious diseases like HIV and Hepatitis C are on the rise again with young people in non-urban areas having the highest increases and needle-sharing being a major factor. Clean needles are distributed by syringe services programs (SSPs), which can also provide a number of other related services including overdose prevention, referrals for substance use treatment, and infectious disease testing. But even there are programs in place --- which is not allowed legally in some US states! --- some people have to travel long distances for health services, especially for services that are specialized, such as needle exchanges.
In discussing the possible quenstion one could analyse it turned out that for some questions critical data are missing:
- There is a distance-to-syringe-services-program variable among the health services data sources of `r glossary("amfAR")` (https://opioid.amfar.org/).
- Many of the interesting variables were not available for much of the nation, and many of them were only at the state level.
Given these limitations, the book focuses whether the distance to a syringe program could be explained by
- whether a county is urban or rural,
- what percentage of the county residents have insurance (as a measure of both access to health care and socioeconomic status [SES]),
- HIV prevalence,
- and the number of people with opioid prescriptions.
As there is no variable for rural or urban status in the amfAR database, the book will tale a variable from the U.S. Department of Agriculture Economic Research Services website (https://www.ers.usda.gov/data-products/county-typology-codes/) that classifies all counties as metro or non-metro.
## Resources & Chapter Outline
### Data, codebook, and R packages {#sec-chap04-data-codebook-packages}
::: {.my-resource}
::: {.my-resource-header}
:::::: {#lem-chap09-resources}
: Data, codebook, and R packages for learning about descriptive statistics
::::::
:::
::: {.my-resource-container}
**Data**
Two options for accessing the data:
1. Download the clean data set `dist_ssp_amfar_ch9.csv` from https://edge.sagepub.com/harris1e.
2. Follow the instructions in Box 9.1 to import, merge, and clean the data from multiple files or from the original online source
**Codebook**
Two options for accessing the codebook:
1. Download the codebook file `opioid_county_codebook.xlsx` from https://edge.sagepub.com/harris1e.
2. Use the online codebook from the amfAR Opioid & Health Indicators Database website (https://opioid.amfar.org/)
**Packages**
1. Packages used with the book (sorted alphabetically)
- {**broom**}, @sec-broom (David Robinson and Alex Hayes)
- {**car**}, @sec-car (John Fox)
- {**lmtest**}: @sec-lmtest (Achim Zeileis)
- {**tableone**}: @sec-tableone (Kazuki Yoshida)
- {**tidyverse**}: @sec-tidyverse (Hadley Wickham)
2. My additional packages (sorted alphabetically)
- {**gt**}: @sec-gt (Richard Iannone)
- {**gtsummary**}: @sec-gtsummary (Daniel D. Sjoberg)
:::
:::
### Get, recode and show data
I will use the data file provided by the book because I am feeling quite confident with reading and recoding the original data. But I will change the columns names so that the variable names conform to the [tidyverse style guide](https://style.tidyverse.org/).
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap09-data}
: Data for chapter 9
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### Get & recode
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-get-recode-data}
: Get & recode data for chapter 9
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: get-recode-data
#| eval: FALSE
## run only once (manually)
distance_ssp <- readr::read_csv(
"data/chap09/dist_ssp_amfar_ch9.csv",
show_col_types = FALSE)
distance_ssp_clean <- distance_ssp |>
dplyr::rename(
state = "STATEABBREVIATION",
dist_ssp = "dist_SSP",
hiv_prevalence = "HIVprevalence",
opioid_rate = "opioid_RxRate",
no_insurance = "pctunins"
) |>
dplyr::mutate(
state = forcats::as_factor(state),
metro = forcats::as_factor(metro)
) |>
dplyr::mutate(
hiv_prevalence = dplyr::na_if(
x = hiv_prevalence,
y = -1
)
)
save_data_file("chap09", distance_ssp_clean, "distance_ssp_clean.rds")
```
(*For this R code chunk is no output available*)
::::
:::::
###### Show data
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-show-data}
: Show data for chapter 9
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tbl-chap09-show-data
#| tbl-cap: "Descriptive statistics for data of chapter 9"
distance_ssp_clean <- base::readRDS("data/chap09/distance_ssp_clean.rds")
skimr::skim(distance_ssp_clean)
```
::::
:::::
***
:::{.my-bulletbox}
:::: {.my-bulletbox-header}
::::: {.my-bulletbox-icon}
:::::
:::::: {#bul-chap09-codebook}
::::::
: Codebook: Explanation of variables used in Chapter 9
::::
:::: {.my-bulletbox-body}
- **county**: the county name
- **state**: the two-letter abbreviation for the state the county is in
- **dist_ssp**: distance in miles to the nearest syringe services program
- **hiv_prevalence**: people age 13 and older living with diagnosed HIV per 100,000
- **opioid_rate**: number of opioid prescriptions per 100 people
- **no_insurance**:percentage of the civilian non-institutionalized population with no health insurance coverage
- **metro**: county is either non-metro, which includes open countryside, rural towns, or smaller cities with up to 49,999 people, or metro
::::
:::
###### metro
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-metro}
: Summary of `metro` variable
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap09-metro}
```{r}
#| label: chap09-metro
distance_ssp_clean |>
dplyr::group_by(metro) |>
skimr::skim()
```
Summary of `metro` variable
:::
***
For the exploratory data analysis I need more details about the association between the distance to the next SSP separated for people living in metro and non-metro areas. See
::::
:::::
:::
::::
:::::
:::::{.my-watch-out}
:::{.my-watch-out-header}
WATCH OUT! Do missing values have a pattern?
:::
::::{.my-watch-out-container}
We know from @tbl-chap09-show-data that the variable `hiv_prevalence` has many missing values. In all the forthcoming analyses we will remove those 70 `NAs` and work with complete cases. 70 NA’s in a sample of 500 is with 14% a big proportion from the available data. The question arises: Is there a reason why there are so many missing values? Could it be that this reason is distorting our analysis?
Most of the time I have provided code that suppresses these warnings. This is a dangerous enterprise as it could bias results and conclusions without knowledge of the researcher. I think that a more prudent approach would need an analysis of the missing values. I do not know how to do this yet, but with {**naniar**} (@sec-naniar) there is a package for exploring missing data structures. Its website and package has [several vignettes](https://naniar.njtierney.com/) to learn its functions and there is also an scientific article about the package [@tierney2023].
Exploring missing data structures is in the book no planned achievement, therefore it is here enough to to get rid of the NA’s and to follow the books outline. But I am planning coming back to this issue and learn how to address missing data structures appropriately.
::::
:::::
## Achievement 1: Explorative Data Analysis {#sec-chap09-achievement1}
### Introduction
Instead following linearly the chapter I will try to compute my own `r glossary("EDA")`. I will try three different method:
1. Manufacturing the data and graphs myself. Writing own functions and using {**tidyverse**} packages to provide summary plots and statistics.
2. Trying out the `graphics::pairs()` function.
3. Experimenting with {**GGally**}, an extension package to {**ggplot2**} where one part (`GGally::ggpairs()`) is the equivalent to the base R `graphics::pairs()` function.
### Steps for EDA
I will apply the following steps:
:::::{.my-procedure}
:::{.my-procedure-header}
:::::: {#prp-chap09-eda-steps}
: Some useful steps to explore data for regression analysis
::::::
:::
::::{.my-procedure-container}
Order and completeness of the following tasks is not mandatory.
1. **Browse the data**:
- **RStudio Data Explorer**: I am always using the data explorer in RStudio to get my first impression of the data. Although this step is not reproducible it forms my frame of mind what EDA steps I should follow and if there are issues I need especially to care about.
- **Skim data**: Look at the data with `skimr::skim()` to get a holistic view of the data: names, data types, missing values, ordered (categorical) minimum, maximum, mean, sd, distribution (numerical).
- **Read the codebook:** It is important to understand what the different variables mean.
- **Check structure:** Examine with `utils::str()` if the dataset has special structures, e.g. labelled data, attributes etc.
- **Glimpse actual data**: To get a feeling about data types and actual values use `dplyr::glimpse()`.
- **Glance at example rows**: As an alternative of `utils::head()` / `utils::tails()` get random row examples including first and last row of the dataset with my own function `my_glance_data()`.
2. **Check normality assumption**:
- **Draw histograms of numeric variables**: To get a better idea I have these `r glossary("histograms")` overlaid with the theoretical normal distributions and the `r glossary("density plots")` of the current data. The difference between these two curves gives a better impression if normality is met or not.
- **Draw Q-Q plots of numeric variables**: `r glossary("Q-Q-Plot", "Q-Q plots")` gives even a more detailed picture if normality is met.
- **Compute normality tests**: If your data has less than 5.000 rows then use the `r glossary("Shapiro-Wilk", "Shapiro-Wilk test")`, otherwise the `r glossary("Anderson-Darling"," Anderson-Darling test")`.
3. **Check homogeneity assumption**: If the normality assumption is not met, then test if the homogeneity of variance assumption between groups is met with `r glossary("Levene", "Levene’s test")` or with the more robust `r glossary("Fligner", "Fligner-Killeen’s test")`. In the following steps use always median instead of mean and do not compute the `r glossary("Pearson", "Pearson’s r")` but the `r glossary("Spearman", "Spearman’s rho")` coefficient.
4. **Compute correlation coefficient**: Apply either Pearson’s r or the Spearman’s rho coefficient.
5. **Explore categorical data with box plots or violin plots**: Box plots work well between a numerical and categorical variable. You could also overlay the data and violin plots to maximize the information in one single graph (see @fig-chap09-eda-violin-boxplot).
***
There are packages like {**GGally**} and {**ggfortify**} (see @sec-GGally and @sec-ggfortify) that provide a graphical and statistical representation of all combinations of bivariate relationships. They can be used as convenient shortcuts to many of the task listed here above.
::::
:::::
### Executing EDA for chapter 9
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap09-eda}
: Explorative Data Analysis for chapter 9
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### tableone
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-tableone}
: Descriptive statics with the {**tableone**} package
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tbl-eda-tableone
#| tbl-cap: "Descriptive statics with the 'tableone' package"
tableone::CreateTableOne(data = distance_ssp_clean,
vars = c('dist_ssp', 'hiv_prevalence',
'opioid_rate', 'no_insurance',
'metro'))
```
***
`skimr::skim()` with @tbl-chap09-show-data is a much better alternative! The second version of {**tableone**} in the book with the median instead of the mean is not necessary because it is in `skimr::skim()` integrated.
::::
:::::
###### Histograms
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-histograms}
: Histograms of numeric variables
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-eda-histograms
#| fig-cap: "Histograms for numeric variables of chapter 9"
#| fig-height: 8
hist_distance <- my_hist_dnorm(
df = distance_ssp_clean,
v = distance_ssp_clean$dist_ssp,
n_bins = 30,
x_label = "Nearest syringe services program in miles"
)
hist_hiv <- my_hist_dnorm(
df = distance_ssp_clean,
v = distance_ssp_clean$hiv_prevalence,
n_bins = 30,
x_label = "People with diagnosed HIV per 100,000"
)
hist_opioid <- my_hist_dnorm(
df = distance_ssp_clean,
v = distance_ssp_clean$opioid_rate,
n_bins = 30,
x_label = "Opioid prescriptions per 100 people"
)
hist_insurance <- my_hist_dnorm(
df = distance_ssp_clean,
v = distance_ssp_clean$no_insurance,
n_bins = 30,
x_label = "Percentage with no health insurance coverage"
)
gridExtra::grid.arrange(
hist_distance, hist_hiv, hist_opioid, hist_insurance, nrow = 2
)
```
***
I developed a function where I can overlay the theoretical normal distribution and the density of the current data. The difference between the two curves gives an indication if we have a normal distribution.
From our data we see that the biggest difference is between SPP distance and HIV prevalence. This right skewed distribution could also be detected from other indicator already present in the `skimr::skim()`view of @tbl-chap09-show-data:
- The small histogram on the right is the most right skewed distribution.
- The standard deviation of `hiv_prevalence` is the only one, that is bigger than the mean of the variable.
- There is a huge difference between mean and the median (p50) where the mean is much bigger than the median (= right skewed distribution), e.g. there is a long tail to the right as can also be seen in the tiny histogram.
Aside from `hiv_prevalence` the variable `distance_ssp` is almost equally right skewed. The situation seems better for the rest of the numeric variables. But let's manufacture `r glossary("Q-Q-Plot", "Q-Q plots")` for all of them to see more in detail if they are normally distributed or not.
::::
:::::
###### Q-Q plots
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-qq-plots}
: Q-Q plots of numeric variables
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-eda-qq-plots
#| fig-cap: "Q-Q plots for numeric variables of chapter 9"
#| fig-height: 8
qq_distance <- my_qq_plot(
df = distance_ssp_clean,
v = distance_ssp_clean$dist_ssp,
col_qq = "Distance to SSP"
)
qq_hiv <- my_qq_plot(
df = distance_ssp_clean,
v = distance_ssp_clean$hiv_prevalence,
col_qq = "HIV diagnosed"
)
qq_opioid <- my_qq_plot(
df = distance_ssp_clean,
v = distance_ssp_clean$opioid_rate,
col_qq = "Opioid prescriptions"
)
qq_insurance <- my_qq_plot(
df = distance_ssp_clean,
v = distance_ssp_clean$no_insurance,
col_qq = "Health insurance"
)
gridExtra::grid.arrange(
qq_distance, qq_hiv, qq_opioid, qq_insurance, nrow = 2
)
```
***
It turned out that all four numeric variables are not normally distributed. Some of them looked in the histograms quite OK, because the differences to the normal distribution on the lower and upper end of the data compensate each other.
Testing normality with `r glossary("Shapiro-Wilk")` or `r glossary("Anderson-Darling")` test will show that they are definitely not normally distributed.
::::
:::::
###### Normality
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-test-normality}
: Normality checking with Shapiro-Wilk & Anderson-Darling tests
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tbl-chap09-eda-test-normality
#| tbl-cap: "Testing normality with Shapiro-Wilk & Anderson-Darling tests"
dist_test <- stats::shapiro.test(distance_ssp_clean$dist_ssp)
hiv_test <- stats::shapiro.test(distance_ssp_clean$hiv_prevalence)
opioid_test <- stats::shapiro.test(distance_ssp_clean$opioid_rate)
insurance_test <- stats::shapiro.test(distance_ssp_clean$no_insurance)
dist_test2 <- nortest::ad.test(distance_ssp_clean$dist_ssp)
hiv_test2 <- nortest::ad.test(distance_ssp_clean$hiv_prevalence)
opioid_test2 <- nortest::ad.test(distance_ssp_clean$opioid_rate)
insurance_test2 <- nortest::ad.test(distance_ssp_clean$no_insurance)
normality_test <-
dplyr::bind_rows(
broom:::glance.htest(dist_test),
broom:::glance.htest(hiv_test),
broom:::glance.htest(opioid_test),
broom:::glance.htest(insurance_test),
broom:::glance.htest(dist_test2),
broom:::glance.htest(hiv_test2),
broom:::glance.htest(opioid_test2),
broom:::glance.htest(insurance_test2)
) |>
dplyr::bind_cols(
variable = c("dist_ssp", "hiv_prevalence",
"opioid_rate", "no_insurance",
"dist_ssp", "hiv_prevalence",
"opioid_rate", "no_insurance")
) |>
dplyr::relocate(variable)
normality_test
```
***
The `r glossary("p-value", "p-values")` from both tests are for all four variables very small, e.g. statistically significant. Therefore we have to reject the Null that they are normally distributed.
::::
:::::
::: {.callout-tip}
It turned out that all four variable are not normally distributed. We can't therefore not use `r glossary("Pearson", "Pearson’s r coefficient")`.
:::
Before we are going to use `r glossary("Spearman", "Spearman’s rho")` let's check the homogeneity of variance assumption (`r glossary("homoscedasticity")`) with a scatterplot with `lm` and `loess` curve and using `r glossary("Levene", "Levene’s Test")` and the `r glossary("Fligner", "Fligner-Killeen’s test")`.
###### Scatterplots
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-scatterplots}
: Scatterplots of numeric variables
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-eda-scatterplots
#| fig-cap: "Scatterplots of numeric variables"
#| fig-height: 10
scatter_dist_hiv <- my_scatter(
df = distance_ssp_clean,
v = distance_ssp_clean$hiv_prevalence,
w = distance_ssp_clean$dist_ssp,
x_label = "HIV prevalence",
y_label = "Distance to SSP"
)
scatter_dist_opioid <- my_scatter(
df = distance_ssp_clean,
v = distance_ssp_clean$opioid_rate,
w = distance_ssp_clean$dist_ssp,
x_label = "Opioid rate",
y_label = "Distance to SSP"
)
scatter_dist_insurance <- my_scatter(
df = distance_ssp_clean,
v = distance_ssp_clean$no_insurance,
w = distance_ssp_clean$dist_ssp,
x_label = "No insurance",
y_label = "Distance to SSP"
)
gridExtra::grid.arrange(
scatter_dist_hiv, scatter_dist_opioid, scatter_dist_insurance, nrow = 3
)
```
::::
:::::
###### Homogeneity
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-test-homogeneity}
: Testing homogeneity of variances with Levene’s and Fligner-Killeen’s test
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tbl-chap09-eda-test-homogeneity
#| tbl-cap: "Homogeneity of variances tested with Levene’s and Fligner-Killeen’s test"
#| results: hold
hiv_test <- stats::fligner.test(
distance_ssp_clean$dist_ssp,
distance_ssp_clean$hiv_prevalence
)
opioid_test <- stats::fligner.test(
distance_ssp_clean$dist_ssp,
distance_ssp_clean$opioid_rate
)
insurance_test <- stats::fligner.test(
distance_ssp_clean$dist_ssp,
distance_ssp_clean$no_insurance
)
hiv_test2 <- car::leveneTest(
distance_ssp_clean$dist_ssp,
forcats::as_factor(distance_ssp_clean$hiv_prevalence)
)
opioid_test2 <- car::leveneTest(
distance_ssp_clean$dist_ssp,
forcats::as_factor(distance_ssp_clean$opioid_rate)
)
insurance_test2 <- car::leveneTest(
distance_ssp_clean$dist_ssp,
forcats::as_factor(distance_ssp_clean$no_insurance)
)
homogeneity_test <-
dplyr::bind_rows(
broom::tidy(hiv_test2),
broom::tidy(opioid_test2),
broom::tidy(insurance_test2)
) |>
dplyr::mutate(method = "Levene's Test for Homogeneity of Variance") |>
dplyr::bind_rows(
broom:::glance.htest(hiv_test),
broom:::glance.htest(opioid_test),
broom:::glance.htest(insurance_test),
) |>
dplyr::bind_cols(
variable = c("dist_hiv",
"dist_opioid",
"dist_insurance",
"dist_hiv",
"dist_opioid",
"dist_insurance"
)
) |>
dplyr::relocate(variable)
homogeneity_test
```
***
All p-values are higher than the threshold of .05 and are therefore not statistically significant. The Null must not rejected, the homogeneity of variance assumption for all variables is met.
::::
:::::
###### Correlations
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-cor}
: Correlations for numeric variables of chapter 9
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tbl-chap09-cor
#| tbl-cap: "Correlations for numeric variables of chapter 9"
cor_pearson <- distance_ssp_clean |>
dplyr::summarize(
hiv_cor = stats::cor(
x = dist_ssp,
y = hiv_prevalence,
use = "complete.obs",
method = "pearson"
),
opioid_cor = stats::cor(
x = dist_ssp,
y = opioid_rate,
use = "complete.obs",
method = "pearson"
),
insurance_cor = stats::cor(
x = dist_ssp,
y = no_insurance,
use = "complete.obs",
method = "pearson"
),
`n (sample)` = dplyr::n()
)
cor_spearman <- distance_ssp_clean |>
dplyr::summarize(
hiv_cor = stats::cor(
x = dist_ssp,
y = hiv_prevalence,
use = "complete.obs",
method = "spearman"
),
opioid_cor = stats::cor(
x = dist_ssp,
y = opioid_rate,
use = "complete.obs",
method = "spearman"
),
insurance_cor = stats::cor(
x = dist_ssp,
y = no_insurance,
use = "complete.obs",
method = "spearman"
),
`n (sample)` = dplyr::n()
)
cor_kendall <- distance_ssp_clean |>
dplyr::summarize(
hiv_cor = stats::cor(
x = dist_ssp,
y = hiv_prevalence,
use = "complete.obs",
method = "kendall"
),
opioid_cor = stats::cor(
x = dist_ssp,
y = opioid_rate,
use = "complete.obs",
method = "kendall"
),
insurance_cor = stats::cor(
x = dist_ssp,
y = no_insurance,
use = "complete.obs",
method = "kendall"
),
`n (sample)` = dplyr::n()
)
cor_chap09 <- dplyr::bind_rows(cor_pearson, cor_spearman, cor_kendall)
cor_chap09 <- dplyr::bind_cols(
method = c("Pearson", "Spearman", "Kendall"), cor_chap09)
cor_chap09
```
***
Here I have computed for a comparison all three correlation coefficients of the nearest distance to the next `r glossary("SSP")` with the numeric variabeles of the dataset.
- Pearson’s $r$ is not allowed for all of the three variables, because our data didn't meet the normality assumption.
- Using Spearman’s $\rho$ or Kendall’s $\tau$ instead of Pearson’s $r$ results in big differences. For instance: the correlation of distance to the next SSP and HIV prevalence reverses it direction.
- Kendall’s tau $\tau$ is more conservative (smaller) than Spearman’s rho and it is also preferred in most scenarios. (Kendall’s tau is not mentioned in the book. Maybe the reason is --- as far as I understand -- that Spearman’s is the most widely used correlation coefficient?)
***
I want to confirm my internet research with the following quotes:
**First quote**
> In the normal case, Kendall correlation is more robust and efficient than Spearman correlation. It means that Kendall correlation is preferred when there are small samples or some outliers. ([Pearson vs Spearman vs Kendall](https://datascience.stackexchange.com/questions/64260/pearson-vs-spearman-vs-kendall)) [@pluviophile2019].
**Second quote**
> Kendall’s Tau: usually smaller values than Spearman’s rho correlation. Calculations based on concordant and discordant pairs. Insensitive to error. P values are more accurate with smaller sample sizes.
>
> Spearman’s rho: usually have larger values than Kendall’s Tau. Calculations based on deviations. Much more sensitive to error and discrepancies in data.
>
> The main advantages of using Kendall’s tau are as follows:
>
> - The distribution of Kendall’s tau has better statistical properties.
> - The interpretation of Kendall’s tau in terms of the probabilities of observing the agreeable (concordant) and non-agreeable (discordant) pairs is very direct.
> - In most of the situations, the interpretations of Kendall’s tau and Spearman’s rank correlation coefficient are very similar and thus invariably lead to the same inferences. ([Kendall’s Tau and Spearman’s Rank Correlation Coefficient](https://www.statisticssolutions.com/free-resources/directory-of-statistical-analyses/kendalls-tau-and-spearmans-rank-correlation-coefficient/)) [@statisticssolutionsn.d]
**Third quote**
> - Kendall Tau-b is more accurate for small sample sizes with strong correlations.
> - Spearman’s rho is preferred for weak correlations in small datasets.
> - In large samples, Kendall Tau-b’s reliability surpasses Spearman’s rho.
> - Kendall’s Tau is a robust estimator against outliers and non-normality.
> - Overall, Kendall Tau-b outperforms Spearman for most statistical scenarios [Kendall Tau-b vs Spearman: Which Correlation Coefficient Wins?](https://statisticseasily.com/kendall-tau-b-vs-spearman/) [@learnstatisticseasily2024]
:::::{.my-resource}
:::{.my-resource-header}
:::::: {#lem-chap09-corr-coefficient}
Understanding the different correlation coefficients
::::::
:::
::::{.my-resource-container}
- [Kendall Tau-b vs Spearman: Which Correlation Coefficient Wins?](https://statisticseasily.com/kendall-tau-b-vs-spearman/): This important article wxplains the decisive factors in choosing the proper non-parametric correlation coefficient (Kendall Tau-b vs Spearman) for your data analysis. [@learnstatisticseasily2024]
- [Pearson, Spearman and Kendall correlation coefficients by hand](https://statsandr.com/blog/pearson-spearman-kendall-correlation-by-hand/#introduction): This articles illustrates how to compute the Pearson, Spearman and Kendall correlation coefficients by hand and under two different scenarios (i.e., with and without ties). [@soetewey2023]
- [Chapter 22: Correlation Types and When to Use Them](https://ademos.people.uic.edu/Chapter22.html): This chapter of [@demos2024] covers the strengths, weaknesses, and when or when not to use three common types of correlations (Pearson, Spearman, and Kendall). It’s part statistics refresher, part R tutorial. [@sarmenton.d]
::::
:::::
::::
:::::
###### metro
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-metro}
: Distance in miles to nearest syringe programs by metro or non-metro status for a sample of 500 counties
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tbl-chap09-eda-violin-boxplot
#| tbl-cap: "Distance in miles to nearest syringe programs by metro or non-metro status for a sample of 500 counties"
distance_ssp_clean |>
dplyr::group_by(metro) |>
dplyr::summarize(mean.dist = base::mean(dist_ssp),
median.dist = stats::median(dist_ssp),
min.dist = base::min(dist_ssp),
max.dist = base::max(dist_ssp)
)
```
***
The big difference between mean and median reflects a right skewed distribution. There are some people living extremely far from the next `r glossary("SSP")` both in non-metro *and* metro areas.
It is no surprise that the distance for people living in a non-metro area is much longer than for people in big city. But what certainly surprised me, is that even in big cities half of people live more than 50 miles form the next SSP.
::::
:::::
###### Violin
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap09-eda-violin-plot}
: Distance in miles to nearest syringe programs by metro or non-metro status for a sample of 500 counties
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-chap09-eda-violin-boxplot
#| fig-cap: "Distance in miles to nearest syringe programs by metro or non-metro status for a sample of 500 counties"
distance_ssp_clean |>
ggplot2::ggplot(
ggplot2::aes(
x = metro,
y = dist_ssp,
fill = metro
)
) +
ggplot2::geom_violin(
ggplot2::aes(
color = metro
),
fill = "white",
alpha = .8
) +
ggplot2::geom_boxplot(
ggplot2::aes(
fill = metro,
color = metro
),
width = .2,
alpha = .3
) +
ggplot2::geom_jitter(
ggplot2::aes(
color = metro
),
alpha = .4
) +
ggplot2::labs(
x = "Type of county",
y = "Miles to syringe program"
) +
ggplot2::scale_fill_manual(
values = c("#78A678", "#7463AC"),
guide = "none") +
ggplot2::scale_color_manual(
values = c("#78A678", "#7463AC"),
guide = "none") +
ggplot2::coord_flip()
```
***
::::
:::::
:::
::::
:::::
:::::: {#tdo-chap09-exploring-several-variables-together}
:::::{.my-checklist}
:::{.my-checklist-header}
TODO: Exploring several variables together with {**GGally}
:::
::::{.my-checklist-container}
During working the material of `r glossary("SwR")` I had often to look for more details in the internet. During one of this (re)searches I learned about about the possibility to explore multiple variables together with graphics::pairs and the {**tidyverse**} pendant {**GGally**}.
After exploring {**GGally**} I noticed that there is with the `ggnostic()` function, working as a wrapper around `GGally::ggduo()`, also a tool that displays full model diagnostics for each given explanatory variable. There are even many other tools where "GGally extends ggplot2 by adding several functions to reduce the complexity of combining geoms with transformed data" [GGally: Extension to ggplot2](https://ggobi.github.io/ggally/index.html).
I plotted some examples in @sec-chap09-experiments but I need to learn these very practical tools much more in detail. Admittedly I have to understand all these different diagnostic tests before I am going to read the extensive documentation (currently 14 articles) and trying to apply shortcuts with the {**GGally**} functions.
::::
:::::
Learn to explore several variables together with {**GGally**}
:::
## Achivement 2: Exploring line model {#sec-chap09-achievement2}
### Introduction
:::::{.my-theorem}
:::{.my-theorem-header}
:::::: {#thm-chap09-line-model}
: Equation for linear model
::::::
:::
::::{.my-theorem-container}
$$
\begin{align*}
y = &m_{x}+b \\
y = &b_{0}+b_{1}x \\
y = &c+b_{1}x
\end{align*}
$$ {#eq-chap09-linear-model}
***
- $m, b_{1}$: `r glossary("slope")` of the line
- $b, b_{0}, c$: y-`r glossary("intercept")` of the line, or the value of y when x = 0
- $x, y$: the coordinates of each point along the line
Sometimes $b^*$ is used. This means that the variable had been standardized, or transformed into z-scores, before the regression model was estimated.
::::
:::::
An example of a linear equation would be $y = 3 + 2x$.
::: {.callout-important #imp-variable-names-linear-equation}
## Variable names and the difference between deterministic and stochastic
- The y variable on the left-hand side of the equation is called the dependent or outcome variable.
- The x variable(s) on the right-hand side of the equation is/are called the independent or predictor variable(s).
***
- A deterministic equation, or model, has one precise value for y for each value of x. Some equation in physics are deterministic, e.g., $e = mc^2$.
- In a stochastic equation, or model, you cannot predict or explain something exactly. Most of the time, there is some variability that cannot be fully explained or predicted. This unexplained variability is represented by an error term that is added to the equation. Relationships measured in social science are typically stochastic.
:::
@eq-chap09-linear-model can be re-written with these terms:
:::::{.my-theorem}
:::{.my-theorem-header}
:::::: {#thm-chap09-linear-model}
: Equation of a linear model (rewritten)
::::::
:::
::::{.my-theorem-container}
$$
\begin{align*}
outcome = &b_{0} + b_{1} \times predictor \\
outcome = &b_{0} + b_{1} \times predictor + error \\
\end{align*}
$$ {#eq-chap09-lm-rewritten}
::::
:::::
### Plotting an example
:::::{.my-example}
:::{.my-example-header}