-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-probability-distributions.qmd
2702 lines (2071 loc) · 73.4 KB
/
04-probability-distributions.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
# Probability distribution {#sec-chap04}
```{r}
#| label: setup
#| include: false
base::source(file = "R/helper.R")
```
## Achievements to unlock
::: {#obj-chap04}
::: {.my-objectives}
::: {.my-objectives-header}
Objectives for chapter 04
:::
::: {.my-objectives-container}
**SwR Achievements**
- **Achievement 1**: Defining and using probability distributions to infer from a sample (@sec-chap04-achievement1)
- **Achievement 2**: Understanding the characteristics and uses of a binomial distribution of a binary variable (@sec-chap04-achievement2)
- **Achievement 3**: Understanding the characteristics and uses of the normal distribution of a continuous variable (@sec-chap04-achievement3)
- **Achievement 4**: Computing and interpreting z-scores to compare observations to groups (@sec-chap04-achievement4)
- **Achievement 5**: Estimating population means from sample means using the normal distribution (@sec-chap04-achievement5)
- **Achievement 6**: Computing and interpreting confidence intervals around means and proportions (@sec-chap04-achievement6)
:::
:::
Achievements for chapter 04
:::
## The opioid overdose problem
There is an alarming increases in drug overdoses in the United States in recent years (see [County Health Rankings & Roadmaps website](https://https://www.countyhealthrankings.org/findings-and-insights/2023-county-health-rankings-national-findings-report) and [Data & Documentation](https://www.countyhealthrankings.org/health-data/methodology-and-sources/rankings-data-documentation#main)).
The `r glossary("CDC")` Wonder website has data on the underlying cause of each death in the United States. For drug deaths, the CDC WONDER data include the drug implicated in each death, if available.
States had begun to adopt policies to try to combat the opioid epidemic. Some of the state-level policy solutions to addressing the increasing number of opioid overdoses:
- Imposition of quantity limits
- Required prior authorization for opioids
- Use of clinical criteria for prescribing opioids
- Step therapy requirements
- Required use of prescription drug monitoring programs.
The Kaiser Family Foundation (`r glossary("KFF")`) keeps track of the adoption of these policies across all 50 states and the District of Columbia.
Treatment programs as well as policies depend partly on the distance people have to travel to the nearest health facility. `r glossary("amfAR")`, the Foundation for AIDS Research, which has an Opioid & Health Indicators Database (https://opioid.amfar.org). The data in amfAR’s database includes distance to the nearest substance abuse treatment facility that has medication assisted therapies (MAT).
## Resources & Chapter Outline
### Data, codebook, and R packages {#sec-chap04-data-codebook-packages}
::: {.my-resource}
::: {.my-resource-header}
:::::: {#lem-chap04-resources}
: Data, codebook, and R packages for learning about descriptive statistics
::::::
:::
::: {.my-resource-container}
**Data**
1. Download clean data sets `pdmp_2017_kff_ch4.csv` and `opioid_dist_to_facility_2017_ch4.csv` from
<https://edge.sagepub.com/harris1e>.
2. Download the county-level distance data files directly from the amfAR website (https://opioid.amfar.org/indicator/dist_MAT)
3. Import and clean the data for 2017 from Table 19 in the online report on the [KFF website](https://www.kff.org/report-section/implementing-coverage-and-payment-initiatives-benefits-and-pharmacy/)
**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)
- {**tidyverse**}: @sec-tidyverse (Hadley Wickham)
2. My additional packages (sorted alphabetically)
:::
:::
### Get data
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap04-get-data}
: Get data for chapter 4
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### PDMP
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-get-pdmp-book}
: Get the cleaned PDMP data from the book `.csv` file
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: get-pdmp-book
#| reslts: hold
#| eval: false
## run code only once manually ##########
## get pdmp data from .csv file of the book
pdmp_2017_book <- readr::read_csv("data/chap04/pdmp_2017_kff_ch4.csv")
save_data_file("chap04", pdmp_2017_book, "pdmp_2017_book.rds")
```
***
(*For this R code chunk is no output available*)
::::
:::::
###### anfAR
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-amfAR}
: Numbered R Code Title (Tidyverse)
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: get-amfar-data
#| eval: false
## run only once, manually ############
amfar_file <- "data/chap04/opioid_dist_to_facility_2017_ch4.csv"
dist_mat <- readr::read_csv(amfar_file)
save_data_file("chap04", dist_mat, "dist_mat.rds")
```
***
(*For this R code chunk is no output available*)
::::
:::::
:::
::::
:::::
***
### Show raw data
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap04-show-data}
: Show raw data for chapter 4
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### PDMP
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-show-pdmp-data}
: Show data for the prescription drug monitoring programs (PDMPs)
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: show-pdmp-data
#| results: hold
pdmp_2017_book <- base::readRDS("data/chap04/pdmp_2017_book.rds")
glue::glue("********************* Show summary *******************")
base::summary(pdmp_2017_book)
glue::glue("")
glue::glue("****************** Show selected data ****************")
my_glance_data(pdmp_2017_book)
```
::::
:::::
###### dist-mat
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-show-dist-mat}
: Show the distances to nearest substance abuse facility providing medication assisted treatment (MAT)
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: show-dist-mat
#| results: hold
dist_mat <- base::readRDS("data/chap04/dist_mat.rds")
glue::glue("********************* Show summary *******************")
base::summary(dist_mat)
glue::glue("")
glue::glue("****************** Show selected data ****************")
my_glance_data(dist_mat)
```
::::
:::::
:::
::::
:::::
***
### Recode data
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap04-recode}
: Recode data for chapter 4
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### Transform amfAR
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-code-name-a}
: Extend amfAR data with transformed values
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: transform-amfar-distances
#| results: hold
#| cache: true
dist_mat_clean <- dist_mat |>
dplyr::mutate(square_root = sqrt(VALUE),
cube_root = VALUE^(1/3),
log = log(VALUE),
inverse = 1/VALUE
)
save_data_file("chap04", dist_mat_clean, "dist_mat_clean.rds")
base::summary(dist_mat_clean)
my_glance_data(dist_mat_clean)
```
::::
:::::
###### Rename `VALUE` in amfAR
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-rename-amfar-distance}
: Rename amfAR `VALUE` to `distance`
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: rename-amfar-distance
#| cache: true
dist_mat_clean2 <- dist_mat |>
dplyr::rename(distance = VALUE)
save_data_file("chap04", dist_mat_clean2, "dist_mat_clean2.rds")
```
***
(*For this R code chunk is no output available*)
::::
:::::
###### Prepare PDMP data
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-prepare-pdmp}
: Rename column in PDMP and recode Yes/No to 1/0
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: prepare-bdmp
pdmp_2017_book <- base::readRDS("data/chap04/pdmp_2017_book.rds")
## recode Yes to 1 and No to 0
pdmp_2017_book_clean <- pdmp_2017_book |>
dplyr::rename(PDMP = 6) |>
dplyr::mutate(PDMP =
dplyr::if_else(PDMP == "Yes", 1, 0)
) |>
dplyr::mutate(PDMP = as.numeric(PDMP))
save_data_file("chap04", pdmp_2017_book_clean, "pdmp_2017_book_clean.rds")
```
***
(*For this R code chunk is no output available*)
::::
:::::
:::
::::
:::::
***
## Achievement 1: Probability distributions to infer from a sample {#sec-chap04-achievement1}
A `r glossary("probability distribution")` is the set of probabilities that each possible value (or range of values) of a variable occurs.
Probability distributions have two characteristics:
1. The probability of each real value of some variable is non-negative; it is either zero or positive. 2. The sum of the probabilities of all possible values of a variable is 1.
There are two categories of probability distributions:
1. Discrete probability distributions: An example is the binomial distribution.
2. Continuous probability distributions: An example is the normal distribution.
## Achievement 2: Binomial distribution of a binary variable {#sec-chap04-achievement2}
### Characteristics of binomial random variables
:::{#bul-chap04-binomial-random-variable}
:::::{.my-bullet-list}
:::{.my-bullet-list-header}
Bullet List
:::
::::{.my-bullet-list-container}
- A variable is measured in the same way n times.
- There are only two possible values of the variable, often called “success” and “failure.”
- Each observation is independent of the others.
- The probability of “success” is the same for each observation.
- The random variable is the number of successes in n measurements.
The binomial distribution is defined by two things:
- **n**, which is the number of observations (e.g., coin flips, people surveyed, states selected)
- **p**, which is the probability of success (e.g., 50% chance of heads for a coin flip, 51% chance of a state having a PDMP)
::::
:::::
Characteristics of binomial random variables
:::
***
### dbinomial() & pbinomial()
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap04-binomial-distributions}
: Statistical properties of binomial distributions
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### `dbinomial()` with exact `n`
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-comp-dbinomial-exact}
: Compute binomial probability with exact number of success
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: comp-dbinomial-exact
## exact 5 successes from 20 selections
## with 51% probability of success
stats::dbinom(x = 5, size = 20, prob = .51) * 100
```
***
Computed the probability given
- the number of successes (`x`),
- the sample size (`size =`), and
- the probability of success (`prob =`).
The probabilities are very small for scenarios of getting *exactly* 10 states with PDMPs in a sample.
::::
:::::
The probabilities are very small for scenarios of getting *exactly* 10 states with `r glossary("PDMP")`s in a sample. The `r glossary("cumulative distribution function")` for the binomial distribution can determine the probability of getting some range of values, which is often more useful than finding the probability of one specific number of successes.
###### `pbinomial()` with range
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-comp-dbinomial-range}
: Compute binomial probability of getting some range of values
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: comp-pbinomial-range
#| results: hold
#| cache: true
base::options(scipen = 999)
## 5 or less successes from 20 selections
## with 51% probability of success
pbinom(q = 5, size = 20, prob = .51) * 100
## 10 or more successes from 20 selections
### with 51% probability of success
pbinom(q = 5, size = 20, prob = .51, lower.tail = FALSE) * 100
base::options(scipen = 0)
```
- **Exactly 5** successes with a success probability of 51% = `base::round(dbinom(x = 5, size = 20, prob = .51) * 100, 3)` : `r base::round(dbinom(x = 5, size = 20, prob = .51) * 100, 3)`%.
- **5 or fewer** successes with a success probability of 51% = `base::round(pbinom(q = 5, size = 20, prob = .51) * 100, 3)`: `r base::round(pbinom(q = 5, size = 20, prob = .51) * 100, 3)`%.
- **6 or more** successes with a success probability of 51% = `base::round(pbinom(q = 5, size = 20, prob = .51, lower.tail = FALSE) * 100, 3)`:
`r base::round(pbinom(q = 5, size = 20, prob = .51, lower.tail = FALSE) * 100, 3)`%.
:::::{.my-important}
:::{.my-important-header}
For probabilities `q and more` you have to take `q - 1` and add `lower.tail = FALSE`.
:::
:::::
::::
:::::
###### Sample PDMPs from data
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-sample-pdmp}
: Sample 25 states from population data (n = 51)
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: sample-25-pmpd
pdmp_2017_book <- base::readRDS("data/chap04/pdmp_2017_book.rds")
## set a starting value for sampling
set.seed(seed = 10)
## sample 25 states and check
pdmp_2017_book |>
dplyr::select(`Required Use of Prescription Drug Monitoring Programs`) |>
dplyr::mutate(`Required Use of Prescription Drug Monitoring Programs` =
forcats::as_factor(`Required Use of Prescription Drug Monitoring Programs`)) |>
dplyr::slice_sample(n = 25) |>
base::summary()
```
***
The book features a lengthy explication of the `set.seed()` function and their revised working after R version 3.6. But this important detail is now --- several years after 3.6.0 appeared in April 2019 --- not so relevant anymore.
I had to recode the character variable to a factor and I used `dplyr::slice_sample()` instead of the superseded `dplyr::sample_n()` function.
::::
:::::
:::
::::
:::::
### Visualizing the binomial distribution
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap04-visualize-binomial-dist}
: Visualizing the binomial distribution
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### Distribution only
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-binomial-dist-only}
: Binomial distribution of 20 selected states when 51% have PDMPs
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-binomial-dist-only
#| fig-cap: "Probability mass function plot showing probability of number of selected states \nwith PDMPs out of 20 total selected when 51% have PDMPs overall"
base::set.seed(42)
binomial_data <- tibble::tibble(stats::rbinom(1000, 20, .51)) |>
dplyr::rename(data = 1) |>
dplyr::mutate(my_color =
dplyr::if_else(data <= 5, "purple", "grey")
)
binomial_data |>
ggplot2::ggplot() +
ggplot2::aes(x = data,
y = ggplot2::after_stat(count) /
base::sum(count)
) +
ggplot2::geom_histogram(
color = "black",
fill = "grey",
binwidth = 1
) +
ggplot2::theme_bw() +
ggplot2::scale_x_continuous(
breaks = base::seq(0, 20, 2)) +
ggplot2::labs(x = 'States with monitoring programs',
y = 'Probability exactly this many selected')
```
::::
:::::
:::::{.my-resource}
:::{.my-resource-header}
:::::: {#lem-chap04-econ41-lab}
Helpful code snippet at "ECON 41 Lab"
::::::
:::
::::{.my-resource-container}
I got help for the code from [15 Tutorial 4: The Binomial Distribution](https://bookdown.org/gabriel_butler/ECON41Labs/tutorial-4-the-binomial-distribution.html) [@butler2019].
::::
:::::
###### Distribution with marker
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-binomial-dist-marker}
: Probability of 5 or fewer selected states with PDMPs out of 20 total selected \nwhen 51% have PDMPs overall
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-binomial-dist-marker
#| fig-cap: "Probability of 5 or fewer selected states with PDMPs out of 20 total selected when 51% have PDMPs overall"
base::set.seed(42)
colors <- c(rep("purple", 2), rep("grey", 13))
binomial_data <- tibble::tibble(stats::rbinom(1000, 20, .51)) |>
dplyr::rename(data = 1) |>
dplyr::mutate(my_color =
dplyr::if_else(data <= 5, "purple", "grey")
)
binomial_data |>
ggplot2::ggplot() +
ggplot2::aes(x = data,
y = ggplot2::after_stat(count) /
base::sum(count)
) +
ggplot2::geom_histogram(
color = "black",
fill = colors,
binwidth = 1
) +
ggplot2::geom_vline(xintercept = 5,
linewidth = 1,
linetype = 'dashed',
color = 'red') +
ggplot2::theme_bw() +
ggplot2::scale_x_continuous(breaks = base::seq(0, 20, 2)) +
ggplot2::labs(x = 'States with monitoring programs',
y = 'Probability exactly this many selected')
```
::::
:::::
###### Histogram colorized
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-binomial-dist-color}
: Probability of 5 or fewer selected states with PDMPs out of 20 total selected \nwhen 51% have PDMPs overall
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-binomial-dist-color
#| fig-cap: "Probability of 5 or fewer selected states with PDMPs out of 20 total selected when 51% have PDMPs overall"
base::set.seed(42)
binomial_data <- tibble::tibble(stats::rbinom(1000, 20, .51)) |>
dplyr::rename(data = 1) |>
dplyr::mutate(my_color =
dplyr::if_else(data <= 5, "purple", "grey")
) |>
dplyr::mutate(my_color =
forcats::as_factor(my_color))
binomial_data |>
ggplot2::ggplot() +
ggplot2::aes(x = data,
y = ggplot2::after_stat(count) /
base::sum(count),
fill = my_color
) +
ggplot2::geom_histogram(
binwidth = 1,
color = "black"
) +
ggplot2::geom_vline(xintercept = 5,
linewidth = 1,
linetype = 'dashed',
color = 'red') +
ggplot2::theme_bw() +
ggplot2::scale_x_continuous(breaks = base::seq(0, 20, 2)) +
ggplot2::scale_fill_manual(name = "Number of states\nwith PDMP",
values = c("grey" = "grey",
"purple" = "purple"),
labels = c("> 5", "5 or fewer")) +
ggplot2::labs(x = 'States with monitoring programs',
y = 'Probability exactly this many selected')
```
::::
:::::
:::
::::
:::::
***
## Achievement 3: Normal distribution of a continuous variable {#sec-chap04-achievement3}
### Working with normal distributions
Binomial data in social sciences are only one type of data. Many data are continuous variables. Just as the shape of the binomial distribution is determined by `n` and `p`, the shape of the normal distribution for a variable in a sample is determined by `$mu$` and `$sigma$`.
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap04-dist-mat-dist}
: Distribution of the distances to nearest facility providing MAT
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### Distances
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-dist-mat-normal}
: Distribution of the original distance variable
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-dist-mat-normal
#| fig-cap: "Distribution of the distance to the nearest facility with MAT"
dist_mat_clean <- base::readRDS("data/chap04/dist_mat_clean.rds")
dist_mat_clean |>
ggplot2::ggplot(
ggplot2::aes(x = VALUE)
) +
ggplot2::geom_histogram(
bins = 30,
fill = "grey",
color = "black"
) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Distance in miles",
y = "Number of counties"
)
```
::::
:::::
###### Distances transformed
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-dist-mat-transformed}
: Distribution of the distance variable transformed by various factors
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-dist-mat-transformed
#| fig-cap: "Distribution of the distance variable transformed by various factors"
#| warning: false
#| cache: true
## using the extended data frame
## with square root, cube root, inverse $ log values
p_cube_root <- dist_mat_clean |>
ggplot2::ggplot(
ggplot2::aes(x = cube_root)
) +
ggplot2::geom_density(
color = "black",
fill = "grey"
) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Cube root of miles to nearest facility",
y = "Density"
)
p_square_root <- dist_mat_clean |>
ggplot2::ggplot(
ggplot2::aes(x = square_root)
) +
ggplot2::geom_density(
color = "black",
fill = "grey"
) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Distance in square root of miles",
y = "Density"
)
p_inverse <- dist_mat_clean |>
ggplot2::ggplot(
ggplot2::aes(x = inverse)
) +
ggplot2::geom_density(
color = "black",
fill = "grey"
) +
ggplot2::theme_bw() +
ggplot2::xlim(0, 1) +
ggplot2::labs(
x = "Inverse of miles to nearest facility",
y = "Density"
)
p_log <- dist_mat_clean |>
ggplot2::ggplot(
ggplot2::aes(x = log)
) +
ggplot2::geom_density(
color = "black",
fill = "grey"
) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Log of miles to nearest facility",
y = "Density"
)
gridExtra::grid.arrange(grobs = list(p_cube_root,
p_square_root,
p_inverse,
p_log),
ncol = 2)
```
***
The best result of these transformation was with cube root.
I tried to write a function for these four graphs, but it was not easy to pass the dataframe and column to the function. I finally succeeded with passing the column name as character string and using `[[` inside the function to select the column. (See [StackOverflow](https://stackoverflow.com/a/36015931/7322615)) But I gave up with `xlim()` parameter for the inverse transformation.
::::
:::::
###### Mean and sd
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-mean-sd-distance-transformed}
: Mean and standard deviation for cube root of mile transformation
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: mean-sd-distance-transformed
dist_mat_clean |>
dplyr::summarize(mean = mean(cube_root),
sd = sd(cube_root))
```
::::
:::::
###### Probability distribution
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-prob-distance-dist}
: Probability density function for a variable with a mean of 2.66 and a standard deviation of .79
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-prob-distance-dist
#| fig-cap: "Probability density function for a variable with a mean of 2.66 and a standard deviation of .79"
#| cache: true
base::set.seed(42)
normal_data <- tibble::tibble(stats::rnorm(
n = 1e3,
mean = 2.66,
sd = .79)) |>
dplyr::rename(data = 1)
normal_data |>
ggplot2::ggplot() +
ggplot2::aes(x = data,
y = ggplot2::after_stat(count) /
base::sum(count)
) +
ggplot2::geom_density() +
ggplot2::theme_bw() +
ggplot2::labs(x = 'Cube root of miles to the nearest facility with MAT',
y = 'Probability density')
```
***
In this plot I draw the probability density function with randomly generated data. The above curve will smooth out when I will take a bigger sample (for instance 1e5 instead 1e3).
::::
:::::
###### with shaded area
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-prob-shaded}
: Probability density function of the cube root transformation for 64 miles distance to a treatment facility
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-chap04-prob-shaded
#| fig-cap: "Probability density function of the cube root transformation for 64 miles distance to a treatment facility"
#| cache: true
normal_data |>
ggplot2::ggplot(
ggplot2::aes(x = data)
) +
ggplot2::stat_function(
fun = dnorm,
n = 1e3,
args = list(mean = 2.66,
sd = .79),
linewidth = .5) +
ggplot2::geom_area(stat = 'function',
fun = dnorm,
fill = 'blue',
args = list(mean = 2.66,
sd = .79),
xlim = c(4, 6),
alpha = 0.3) +
ggplot2::theme_bw() +
ggplot2::labs(x = 'Cube root of miles to the nearest facility with MAT',
y = 'Probability density')
```
***
For this plot I have used the `dnorm()` function. Therefore this normal distribution curve is smooth.
The shaded area is the probability for counties that are $4^3 = 64$ miles from a facility that provides medical assisted treatment (MAT)
::::
:::::
###### Compute shaded area
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-comp-shaded-area}
: Compute shaded area: Percentage of counties where the nearest facility with MAT is 64 miles or more far away
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: comp-shaded-area
stats::pnorm(4, 2.66, .79, lower.tail = FALSE)
```
***
If you want to calculate the right part of the distribution then you need to change the default value from `lower.tail = TRUE` to `lower.tail = FALSE`.
::::
:::::
4.49% of observations were in the shaded part of this distribution and therefore had a value for the distance variable of 4 or greater. Reversing the transformation, this indicated that residents of 4.49% of counties have to travel 43 or 64 miles or more to get to the nearest substance abuse facility providing medication-assisted treatment.
:::
::::
:::::
### Check understanding
Shows shading for the part of the distribution that is less than 2. Estimate (without computing the answer) the percentage of counties in the shaded area.
:::::{.my-exercise}