-
Notifications
You must be signed in to change notification settings - Fork 173
/
explore-numerical.qmd
1403 lines (1164 loc) · 61.9 KB
/
explore-numerical.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
# Exploring numerical data {#sec-explore-numerical}
```{r}
#| include: false
source("_common.R")
```
::: {.chapterintro data-latex=""}
This chapter focuses on exploring **numerical** data using summary statistics and visualizations.
The summaries and graphs presented in this chapter are created using statistical software; however, since this might be your first exposure to the concepts, we take our time in this chapter to detail how to create them.
Mastery of the content presented in this chapter will be crucial for understanding the methods and techniques introduced in the rest of the book.
:::
Consider the `loan_amount` variable from the `loan50` dataset, which represents the loan size for each of 50 loans in the dataset.
This variable is numerical since we can sensibly discuss the numerical difference of the size of two loans.
On the other hand, area codes and zip codes are not numerical, but rather they are categorical variables.
Throughout this chapter, we will apply numerical methods using the `loan50` and `county` datasets, which were introduced in @sec-data-basics.
If you'd like to review the variables from either dataset, see Tables @tbl-loan-50-variables and @tbl-county-variables.
::: {.data data-latex=""}
The [`county`](http://openintrostat.github.io/usdata/reference/county.html) data can be found in the [**usdata**](http://openintrostat.github.io/usdata) R package and the [`loan50`](http://openintrostat.github.io/openintro/reference/loan50.html) data can be found in the [**openintro**](http://openintrostat.github.io/openintro) R package.
:::
## Scatterplots for paired data {#sec-scatterplots}
A **scatterplot**\index{plot!scatterplot}\index{scatterplot} provides a case-by-case view of data for two numerical variables.
In @fig-county-multi-unit-homeownership, a scatterplot was used to examine the homeownership rate against the percentage of housing units that are in multi-unit structures (e.g., apartments) in the `county` dataset.
Another scatterplot is shown in @fig-loan50-amount-income, comparing the total income of a borrower `total_income` and the amount they borrowed `loan_amount` for the `loan50` dataset.
In any scatterplot, each point represents a single case.
Since there are `r nrow(loan50)` cases in `loan50`, there are `r nrow(loan50)` points in @fig-loan50-amount-income.
```{r}
#| include: false
terms_chp_05 <- c("scatterplot")
```
```{r}
#| label: fig-loan50-amount-income
#| fig-cap: |
#| A scatterplot of loan amount versus total income for the `loan50`
#| dataset.
#| fig-alt: |
#| A scatterplot with total income on the x-axis and loan amount on the
#| y-axis. The relationship is moderately positive.
#| fig-asp: 0.48
ggplot(loan50, aes(x = total_income, y = loan_amount)) +
geom_point(alpha = 0.6, shape = 21, size = 3) +
labs(x = "Total income", y = "Loan amount") +
scale_x_continuous(labels = dollar_format(scale = 0.001, suffix = "K")) +
scale_y_continuous(labels = dollar_format(scale = 0.001, suffix = "K"))
```
Looking at @fig-loan50-amount-income, we see that there are many borrowers with income below \$100,000 on the left side of the graph, while there are a handful of borrowers with income above \$250,000.
```{r}
#| label: fig-median-hh-income-poverty
#| fig-cap: |
#| A scatterplot of the median household income against the poverty
#| rate for the `county` dataset. Data are from 2017. A statistical model has
#| also been fit to the data and is shown as a dashed line.
#| fig-alt: |
#| A scatterplot with poverty rate on the x-axis and median household
#| income on the y-axis. The relationship is negative and curvilinear.
#| The bulk of the points fall with a poverty rate of 10% to 20% and a
#| median household income of $25K to $75K.
#| fig-asp: 0.48
ggplot(county, aes(x = poverty / 100, y = median_hh_income)) +
geom_point(
alpha = 0.3, fill = IMSCOL["black", "full"],
shape = 21, size = 3
) +
geom_smooth(linetype = "dashed", color = IMSCOL["red", "full"], se = FALSE) +
labs(x = "Poverty rate", y = "Median household income") +
scale_x_continuous(labels = percent_format(accuracy = 1)) +
scale_y_continuous(labels = dollar_format(scale = 0.001, suffix = "K"))
```
\vspace{-5mm}
::: {.workedexample data-latex=""}
@fig-median-hh-income-poverty shows a plot of median household income against the poverty rate for `r nrow(county)` counties in the US.
What can be said about the relationship between these variables?
------------------------------------------------------------------------
The relationship is evidently **nonlinear**\index{nonlinear}, as highlighted by the dashed line.
This is different from previous scatterplots we have seen, which indicate very little, if any, curvature in the trend.
:::
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "nonlinear")
```
\vspace{-5mm}
::: {.guidedpractice data-latex=""}
What do scatterplots reveal about the data, and how are they useful?[^05-explore-numerical-1]
:::
[^05-explore-numerical-1]: Answers may vary.
Scatterplots are helpful in quickly spotting associations relating variables, whether those associations come in the form of simple trends or whether those relationships are more complex.
\vspace{-5mm}
::: {.guidedpractice data-latex=""}
Describe two variables that would have a horseshoe-shaped association in a scatterplot $(\cap$ or $\frown).$[^05-explore-numerical-2]
:::
[^05-explore-numerical-2]: Consider the case where your vertical axis represents something "good" and your horizontal axis represents something that is only good in moderation.
Health and water consumption fit this description: we require some water to survive, but consume too much and it becomes toxic and can kill a person.
\clearpage
## Dot plots and the mean {#sec-dotplots}
Sometimes we are interested in the distribution of a single variable.
In these cases, a dot plot provides the most basic of displays.
A **dot plot**\index{plot!dot}\index{dot plot} is a one-variable scatterplot; an example using the interest rate of `r nrow(loan50)` loans is shown in @fig-loan-int-rate-dotplot.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "dot plot")
```
```{r}
#| label: fig-loan-int-rate-dotplot
#| fig-cap: |
#| A dot plot of interest rate for the `loan50` dataset. The rates
#| have been rounded to the nearest percent in this plot, and the
#| distribution's mean is shown as a red triangle.
#| fig-alt: |
#| A dot plot of interest rate (ranging from about 5% to 25%).
#| The distribution is right skewed, and the mean is shown at an interest
#| rate of about 11%.
#| fig-asp: 0.4
loan50_interest_rate_mean <- mean(loan50$interest_rate)
ggplot(loan50, aes(x = interest_rate)) +
geom_dotplot() +
labs(x = "Interest rate") +
scale_x_continuous(labels = label_percent(scale = 1)) +
theme(
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
) +
geom_polygon(
data = tibble(
x = c(
loan50_interest_rate_mean - 1,
loan50_interest_rate_mean + 1,
loan50_interest_rate_mean
),
y = c(-0.1, -0.1, 0)
),
aes(x = x, y = y),
fill = IMSCOL["red", "full"]
)
```
The **mean**\index{mean}, often called the **average**\index{average} is a common way to measure the center of a **distribution**\index{distribution} of data.
To compute the mean interest rate, we add up all the interest rates and divide by the number of observations.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "mean", "average", "distribution")
```
The sample mean is often labeled $\bar{x}.$ The letter $x$ is being used as a generic placeholder for the variable of interest and the bar over the $x$ communicates we are looking at the average interest rate, which for these 50 loans is `r round(loan50_interest_rate_mean, 2)`%.
It's useful to think of the mean as the balancing point of the distribution, and it's shown as a triangle in @fig-loan-int-rate-dotplot.
::: {.important data-latex=""}
**Mean.**
The sample mean can be calculated as the sum of the observed values divided by the number of observations:
\vspace{-5mm}
$$ \bar{x} = \frac{x_1 + x_2 + \cdots + x_n}{n} $$
:::
\vspace{-5mm}
::: {.guidedpractice data-latex=""}
Examine the equation for the mean.
What does $x_1$ correspond to?
And $x_2$?
Can you infer a general meaning to what $x_i$ might represent?[^05-explore-numerical-3]
:::
[^05-explore-numerical-3]: $x_1$ corresponds to the interest rate for the first loan in the sample, $x_2$ to the second loan's interest rate, and $x_i$ corresponds to the interest rate for the $i^{th}$ loan in the dataset.
For example, if $i = 4,$ then we are examining $x_4,$ which refers to the fourth observation in the dataset.
\vspace{-5mm}
::: {.guidedpractice data-latex=""}
What was $n$ in this sample of loans?[^05-explore-numerical-4]
:::
[^05-explore-numerical-4]: The sample size was $n = 50.$
The `loan50` dataset represents a sample from a larger population of loans made through Lending Club.
We could compute a mean for the entire population in the same way as the sample mean.
However, the population mean has a special label: $\mu.$ The symbol $\mu$ is the Greek letter *mu* and represents the average of all observations in the population.
Sometimes a subscript, such as $_x,$ is used to represent which variable the population mean refers to, e.g., $\mu_x.$ Oftentimes it is too expensive to measure the population mean precisely, so we often estimate $\mu$ using the sample mean, $\bar{x}.$
\clearpage
::: {.content-visible when-format="html"}
::: {.pronunciation data-latex=""}
The Greek letter $\mu$ is pronounced *mu*, listen to the pronunciation [here](https://youtu.be/PStgY5AcEIw?t=47).
:::
:::
::: {.content-visible when-format="pdf"}
::: {.pronunciation data-latex=""}
The Greek letter $\mu$ is pronounced *mu*.
:::
:::
::: {.workedexample data-latex=""}
Although we do not have an ability to *calculate* the average interest rate across all loans in the populations, we can *estimate* the population value using the sample data.
Based on the sample of 50 loans, what would be a reasonable estimate of $\mu_x,$ the mean interest rate for all loans in the full dataset?
------------------------------------------------------------------------
The sample mean, `r round(loan50_interest_rate_mean, 2)`, provides a rough estimate of $\mu_x.$ While it is not perfect, this is our single best guess **point estimate**\index{point estimate} of the average interest rate of all the loans in the population under study.
In @sec-foundations-randomization and beyond, we will develop tools to characterize the accuracy of point estimates, like the sample mean.
As you might have guessed, point estimates based on larger samples tend to be more accurate than those based on smaller samples.
:::
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "point estimate")
```
The mean is useful because it allows us to rescale or standardize a metric into something more easily interpretable and comparable.
Suppose we would like to understand if a new drug is more effective at treating asthma attacks than the standard drug.
A trial of 1,500 adults is set up, where 500 receive the new drug, and 1000 receive a standard drug in the control group.
Results of this trial are summarized in @tbl-drug-asthma-results.
```{r}
#| label: tbl-drug-asthma-results
#| tbl-cap: Results of a trial of 1500 adults that suffer from asthma.
#| tbl-pos: H
drug_asthma <- tribble(
~x, ~`New drug`, ~`Standard drug`,
"Number of patients", 500, 1000,
"Total asthma attacks", 200, 300
)
drug_asthma |>
kbl(
linesep = "", booktabs = TRUE,
col.names = c("", "New drug", "Standard drug"), align = "lcc"
) |>
kable_styling(
bootstrap_options = c("striped", "condensed"),
latex_options = c("striped"), full_width = FALSE
) |>
column_spec(1, width = "12em") |>
column_spec(2:3, width = "8em")
```
Comparing the raw counts of 200 to 300 asthma attacks would make it appear that the new drug is better, but this is an artifact of the imbalanced group sizes.
Instead, we should look at the average number of asthma attacks per patient in each group:
- New drug: $200 / 500 = 0.4$ asthma attacks per patient
- Standard drug: $300 / 1000 = 0.3$ asthma attacks per patient
The standard drug has a lower average number of asthma attacks per patient than the average in the treatment group.
::: {.workedexample data-latex=""}
Come up with another example where the mean is useful for making comparisons.
------------------------------------------------------------------------
Emilio opened a food truck last year where he sells burritos, and his business has stabilized over the last 3 months.
Over that 3-month period, he has made \$11,000 while working 625 hours.
Emilio's average hourly earnings provides a useful statistic for evaluating whether his venture is, at least from a financial perspective, worth it:
$$ \frac{\$11000}{625\text{ hours}} = \$17.60\text{ per hour} $$
By knowing his average hourly wage, Emilio now has put his earnings into a standard unit that is easier to compare with many other jobs that he might consider.
:::
\clearpage
::: {.workedexample data-latex=""}
Suppose we want to compute the average income per person in the US.
To do so, we might first think to take the mean of the per capita incomes across the 3,142 counties in the `county` dataset.
What would be a better approach?
------------------------------------------------------------------------
The `county` dataset is special in that each county actually represents many individual people.
If we were to simply average across the `income` variable, we would be treating counties with 5,000 and 5,000,000 residents equally in the calculations.
Instead, we should compute the total income for each county, add up all the counties' totals, and then divide by the number of people in all the counties.
If we completed these steps with the `county` data, we would find that the per capita income for the US is \$30,861.
Had we computed the *simple* mean of per capita income across counties, the result would have been just \$26,093!
This example used what is called a **weighted mean**\index{weighted mean}.
For more information on this topic, check out the following online supplement regarding [weighted means](https://www.openintro.org/go/?id=stat_extra_weighted_mean).
:::
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "weighted mean")
```
## Histograms and shape {#sec-histograms}
Dot plots show the exact value for each observation.
They are useful for small datasets but can become hard to read with larger samples.
Rather than showing the value of each observation, we prefer to think of the value as belonging to a *bin*.
For example, in the `loan50` dataset, we created a table of counts for the number of loans with interest rates between 5.0% and 7.5%, then the number of loans with rates between 7.5% and 10.0%, and so on.
Observations that fall on the boundary of a bin (e.g., 10.00%) are allocated to the lower bin.
The tabulation is shown in @tbl-binnedIntRateAmountTable, and the binned counts are plotted as bars in @fig-loan50IntRateHist into what is called a **histogram**\index{plot!histogram}\index{histogram}.
Note that the histogram resembles a more heavily binned version of the stacked dot plot shown in @fig-loan-int-rate-dotplot.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "histogram")
```
```{r}
#| label: tbl-binnedIntRateAmountTable
#| tbl-cap: Counts for the binned interest rate data.
#| tbl-pos: H
loan50 |>
mutate(interest_rate_cat = cut(interest_rate, breaks = seq(5, 27.5, 2.5))) |>
count(interest_rate_cat, name = "Count") |>
separate(interest_rate_cat, into = c("lower", "upper"), sep = ",") |>
mutate(
lower = str_remove(lower, "\\("),
upper = str_remove(upper, "]"),
lower = paste0(lower, "%"),
upper = paste0(upper, "%"),
lower = str_c("(", lower),
upper = str_c(upper, "]")
) |>
unite("Interest rate", lower:upper, sep = " - ") |>
kbl(linesep = "", booktabs = TRUE, align = "lr") |>
kable_styling(
bootstrap_options = c("striped", "condensed"),
latex_options = c("striped"),
full_width = FALSE
) |>
column_spec(1:2, width = "9em")
```
```{r}
#| label: fig-loan50IntRateHist
#| fig-cap: |
#| A histogram of interest rate. This distribution is strongly skewed
#| to the right.
#| fig-alt: |
#| A histogram of interest rate (ranging from about 5% to 25%).
#| The distribution is right skewed.
#| fig-asp: 0.4
ggplot(loan50, aes(x = interest_rate)) +
geom_histogram(breaks = seq(5, 27.5, 2.5)) +
labs(x = "Interest rate", y = "Count") +
scale_x_continuous(
breaks = seq(5, 25, 5),
labels = label_percent(scale = 1, accuracy = 1)
)
```
Histograms provide a view of the **data density**\index{data density}.
Higher bars represent where the data are relatively more common.
For instance, there are many more loans with rates between 5% and 10% than loans with rates between 20% and 25% in the dataset.
The bars make it easy to see how the density of the data changes relative to the interest rate.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "data density")
```
Histograms are especially convenient for understanding the shape of the data distribution.
@fig-loan50IntRateHist suggests that most loans have rates under 15%, while only a handful of loans have rates above 20%.
When the distribution of a variable trails off to the right in this way and has a longer right **tail**\index{tail}, the shape is said to be **right skewed**\index{right skewed}.[^05-explore-numerical-5]
[^05-explore-numerical-5]: Other ways to describe data that are right skewed: skewed to the right, skewed to the high end, or skewed to the positive end.
```{r}
#| label: fig-loan50IntRateDensity
#| fig-cap: |
#| A density plot of interest rate. Again, the distribution is strongly skewed
#| to the right.
#| fig-alt: |
#| A density plot of interest rate (ranging from about 5% to 25%).
#| The distribution is right skewed.
#| fig-asp: 0.4
ggplot(loan50, aes(x = interest_rate)) +
geom_density(fill = IMSCOL[1, 1], alpha = 0.5) +
labs(x = "Interest rate", y = "Density") +
scale_x_continuous(
breaks = seq(5, 25, 5),
labels = label_percent(scale = 1, accuracy = 1)
)
```
@fig-loan50IntRateDensity shows a **density plot**\index{plot!density}\index{density plot} which is a smoothed out histogram.
The technical details for how to draw density plots (precisely how to smooth out the histogram) are beyond the scope of this text, but you will note that the shape, scale, and spread of the observations are displayed similarly in a histogram as in a density plot.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "density plot")
```
Variables with the reverse characteristic -- a long, thinner tail to the left -- are said to be **left skewed**\index{left skewed}.
We also say that such a distribution has a long left tail.
Variables that show roughly equal trailing off in both directions are called **symmetric**\index{symmetric}.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "tail", "right skewed", "left skewed", "symmetric")
```
::: {.important data-latex=""}
When data trail off in one direction, the distribution has a **long tail**\index{tail}.
If a distribution has a long left tail, it is left skewed.
If a distribution has a long right tail, it is right skewed.
:::
::: {.guidedpractice data-latex=""}
Besides the mean (since it was labeled), what can you see in the dot plot in @fig-loan-int-rate-dotplot that you cannot see in the histogram in @fig-loan50IntRateHist?[^05-explore-numerical-6]
:::
[^05-explore-numerical-6]: The interest rates for individual loans.
In addition to looking at whether a distribution is skewed or symmetric, histograms can be used to identify modes.
A **mode** is represented by a prominent peak in the distribution.
There is only one prominent peak in the histogram of `interest_rate`.
A definition of *mode* sometimes taught in math classes is the value with the most occurrences in the dataset.
However, for many real-world datasets, it is common to have *no* observations with the same value in a dataset, making this definition impractical in data analysis.
\clearpage
@fig-singleBiMultiModalPlots shows histograms that have one, two, or three prominent peaks.
Such distributions are called **unimodal**\index{unimodal}, **bimodal**\index{bimodal}, and **multimodal**\index{multimodal}, respectively.
Any distribution with more than two prominent peaks is called multimodal.
Notice that there was one prominent peak in the unimodal distribution with a second less prominent peak that was not counted since it only differs from its neighboring bins by a few observations.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "unimodal", "bimodal", "multimodal")
```
```{r}
#| label: fig-singleBiMultiModalPlots
#| fig-cap: |
#| Counting only prominent peaks, the distributions are (left to right)
#| unimodal, bimodal, and multimodal. Note that the left plot is unimodal
#| because we are counting prominent peaks, not just any peak.
#| fig-alt: |
#| Three separate histograms on fabricated data. The first histogram
#| shows a unimodal distribution, the second histogram shows a bimodal
#| distribution, and the third histogram shows a multimodal distribution.
#| fig-asp: 0.3
#| out-width: 95%
df_modes <- tibble(
uni = rchisq(65, 6),
bi = c(rchisq(25, 5.8), rnorm(40, 20, 2)),
multi = c(rchisq(25, 3), rnorm(25, 15), rnorm(15, 25, 1.5))
)
p_uni <- ggplot(df_modes, aes(x = uni)) +
geom_histogram(binwidth = 2) +
labs(x = NULL, y = NULL) +
ylim(0, 23) +
xlim(0, 30)
p_bi <- ggplot(df_modes, aes(x = bi)) +
geom_histogram(binwidth = 2) +
labs(x = NULL, y = NULL) +
ylim(0, 23) +
xlim(0, 30)
p_multi <- ggplot(df_modes, aes(x = multi)) +
geom_histogram(binwidth = 2) +
labs(x = NULL, y = NULL) +
ylim(0, 23) +
xlim(0, 30)
p_uni + p_bi + p_multi
```
::: {.workedexample data-latex=""}
@fig-loan50IntRateHist reveals only one prominent mode in the interest rate.
Is the distribution unimodal, bimodal, or multimodal?
------------------------------------------------------------------------
Remember that *uni* stands for 1 (think *uni*cycles), and *bi* stands for 2 (think *bi*cycles).
:::
::: {.guidedpractice data-latex=""}
Height measurements of young students and adult teachers at an elementary school were taken.
How many modes would you expect in this height dataset?[^05-explore-numerical-8]
:::
[^05-explore-numerical-8]: There might be two height groups visible in the dataset: the children (students) and the adults (teachers).
That is, the data are probably bimodal.
Looking for modes isn't about finding a clear and correct answer about the number of modes in a distribution, which is why *prominent*\index{prominent} is not rigorously defined in this book.
The most important part of this examination is to better understand your data.
## Variance and standard deviation {#sec-variance-sd}
The mean was introduced as a method to describe the center of a variable, and **variability**\index{variability} in the data is also important.
Here, we introduce two measures of variability: the variance and the standard deviation.
Both of these are very useful in data analysis, even though their formulas are a bit tedious to calculate by hand.
The standard deviation is the easier of the two to comprehend, as it roughly describes how far away the typical observation is from the mean.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "variability")
```
We call the distance of an observation from its mean its **deviation**\index{deviation}.
Below are the deviations for the $1^{st},$ $2^{nd},$ $3^{rd},$ and $50^{th}$ observations in the `interest_rate` variable:
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "deviation")
```
```{r}
#| include: false
loan50_interest_rate_deviation <- round(loan50$interest_rate - loan50_interest_rate_mean, 2)
loan50_interest_rate_deviation_squared <- round(loan50_interest_rate_deviation^2, 2)
loan50_interest_rate_var <- var(loan50$interest_rate)
loan50_interest_rate_sd <- sd(loan50$interest_rate)
```
$$
\begin{aligned}
x_1 - \bar{x} &= `r round(loan50$interest_rate[1], 2)` - `r round(loan50_interest_rate_mean, 2)` = `r loan50_interest_rate_deviation[1]` \\
x_2 - \bar{x} &= `r round(loan50$interest_rate[2], 2)` - `r round(loan50_interest_rate_mean, 2)` = `r loan50_interest_rate_deviation[2]` \\
x_3 - \bar{x} &= `r round(loan50$interest_rate[3], 2)` - `r round(loan50_interest_rate_mean, 2)` = `r loan50_interest_rate_deviation[3]` \\
&\vdots \\
x_{50} - \bar{x} &= `r round(loan50$interest_rate[50], 2)` - `r round(loan50_interest_rate_mean, 2)` = `r loan50_interest_rate_deviation[50]` \\
\end{aligned}
$$
\clearpage
If we square these deviations and then take an average, the result is equal to the sample **variance**\index{variance}, denoted by $s^2$:
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "variance")
```
$$
s^2 = \frac{(`r loan50_interest_rate_deviation[1]`)^2 + (`r loan50_interest_rate_deviation[2]`)^2 + (`r loan50_interest_rate_deviation[3]`)^2 + \cdots + (`r loan50_interest_rate_deviation[50]`)^2}{50 - 1} = \frac{`r loan50_interest_rate_deviation_squared[1]` + `r loan50_interest_rate_deviation_squared[2]` + \cdots + `r loan50_interest_rate_deviation_squared[50]`}{49} = `r round(loan50_interest_rate_var, 2)`
$$
We divide by $n - 1,$ rather than dividing by $n,$ when computing a sample's variance.
There's some mathematical nuance here, but the end result is that doing this makes this statistic slightly more reliable and useful.
Notice that squaring the deviations does two things.
First, it makes large values relatively much larger.
Second, it gets rid of any negative signs.
::: {.important data-latex=""}
**Standard deviation.**
The sample standard deviation can be calculated as the square root of the sum of the squared distance of each value from the mean divided by the number of observations minus one:
\vspace{-5mm}
$$s = \sqrt{\frac{\sum_{i=1}^n (x_i - \bar{x})^2}{n-1}}$$
:::
The **standard deviation**\index{standard deviation} is defined as the square root of the variance:
$$s = \sqrt{`r round(loan50_interest_rate_var, 2)`} = `r round(loan50_interest_rate_sd, 2)`$$
While often omitted, a subscript of $_x$ may be added to the variance and standard deviation, i.e., $s_x^2$ and $s_x^{},$ if it is useful as a reminder that these are the variance and standard deviation of the observations represented by $x_1,$ $x_2,$ ..., $x_n.$
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "standard deviation")
```
::: {.important data-latex=""}
**Variance and standard deviation.**
The variance is the average squared distance from the mean.
The standard deviation is the square root of the variance.
The standard deviation is useful when considering how far the data are distributed from the mean.
The standard deviation represents the typical deviation of observations from the mean.
Often about 68% of the data will be within one standard deviation of the mean and about 95% will be within two standard deviations.
However, these percentages are not strict rules.
:::
Like the mean, the population values for variance and standard deviation have special symbols: $\sigma^2$ for the variance and $\sigma$ for the standard deviation.
::: {.content-visible when-format="html"}
::: {.pronunciation data-latex=""}
The Greek letter $\sigma$ is pronounced *sigma*, listen to the pronunciation [here](https://youtu.be/PStgY5AcEIw?t=72).
:::
:::
::: {.content-visible when-format="pdf"}
::: {.pronunciation data-latex=""}
The Greek letter $\sigma$ is pronounced *sigma*.
:::
:::
::: {.guidedpractice data-latex=""}
A good description of the shape of a distribution should include modality and whether the distribution is symmetric or skewed to one side.
Using @fig-severalDiffDistWithSdOf1 as an example, explain why such a description is important.[^05-explore-numerical-9]
:::
[^05-explore-numerical-9]: @fig-severalDiffDistWithSdOf1 shows three distributions that look quite different, but all have the same mean, variance, and standard deviation.
Using modality, we can distinguish between the first plot (bimodal) and the last two (unimodal).
Using skewness, we can distinguish between the last plot (right skewed) and the first two.
While a picture, like a histogram, tells a more complete story, we can use modality and shape (symmetry/skew) to characterize basic information about a distribution.
\clearpage
```{r}
#| label: sdRuleForIntRate
#| fig-cap: |
#| For the interest rate variable, 34 of the 50 loans (68%) had
#| interest rates within 1 standard deviation of the mean, and 48 of the 50
#| loans (96%) had rates within 2 standard deviations. Usually about 68% of
#| the data are within 1 standard deviation of the mean and 95% within 2
#| standard deviations, though this is far from a hard rule.
#| fig-alt: |
#| A histogram of the right-skewed variable, interest rates. Grey
#| shading indicates the empirical rule cutoffs of one and two standard
#| deviations. Because the variable is right-skewed, the empirical rule
#| ranges do not capture the desired amoung of data, 68% and 95% respectively.
#| fig-asp: 0.5
box_sd1 <- tibble(
x = c(
loan50_interest_rate_mean - loan50_interest_rate_sd,
loan50_interest_rate_mean - loan50_interest_rate_sd,
loan50_interest_rate_mean + loan50_interest_rate_sd,
loan50_interest_rate_mean + loan50_interest_rate_sd
),
y = c(0, 17, 17, 0)
)
box_sd2 <- tibble(
x = c(
loan50_interest_rate_mean - 2 * loan50_interest_rate_sd,
loan50_interest_rate_mean - 2 * loan50_interest_rate_sd,
loan50_interest_rate_mean + 2 * loan50_interest_rate_sd,
loan50_interest_rate_mean + 2 * loan50_interest_rate_sd
),
y = c(0, 17, 17, 0)
)
box_sd3 <- tibble(
x = c(
loan50_interest_rate_mean - 3 * loan50_interest_rate_sd,
loan50_interest_rate_mean - 3 * loan50_interest_rate_sd,
loan50_interest_rate_mean + 3 * loan50_interest_rate_sd,
loan50_interest_rate_mean + 3 * loan50_interest_rate_sd
),
y = c(0, 17, 17, 0)
)
ggplot(loan50, aes(x = interest_rate)) +
labs(x = "Interest rate", y = "Count") +
geom_histogram(breaks = seq(5, 27.5, 2.5)) +
geom_polygon(data = box_sd1, aes(x = x, y = y), fill = IMSCOL["gray", "f5"], alpha = 0.3) +
geom_polygon(data = box_sd2, aes(x = x, y = y), fill = IMSCOL["gray", "f5"], alpha = 0.3) +
geom_polygon(data = box_sd3, aes(x = x, y = y), fill = IMSCOL["gray", "f5"], alpha = 0.3) +
scale_x_continuous(breaks = seq(-5, 25, 5), labels = label_percent(scale = 1, accuracy = 1)) +
theme(
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank()
)
```
```{r}
#| label: fig-severalDiffDistWithSdOf1
#| fig-cap: |
#| Three different population distributions with the same mean (0)
#| and standard deviation (1).
#| fig-alt: |
#| Three histograms of fabricated data with empirical rule shading of
#| one and two standard deviations superimposed. The bimodal and right
#| skewed histogram demonstrate that the empirical rule is not a good
#| approximation. The empirical rule fits well to the unimodal bell-shaped
#| distribution.
#| fig-asp: 0.5
x1 <- c(rep(-0.975, 1000), rep(0.975, 1000))
x1 <- (x1 - mean(x1)) / sd(x1)
x2 <- rnorm(2000)
x2 <- (x2 - mean(x2)) / sd(x2)
x3 <- qchisq(seq(0.26, 0.8, 0.0005), 4)
x3 <- (x3 - mean(x3)) / sd(x3)
dists_mean0_sd1 <- tibble(
x = c(x1, x2, x3),
group = c(rep("A", length(x1)), rep("B", length(x2)), rep("C", length(x3)))
)
ggplot(dists_mean0_sd1, aes(x = x)) +
geom_histogram(binwidth = 1) +
facet_grid(group ~ ., scales = "free_y") +
theme(
# remove y axis
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
# strip facet labels
strip.background = element_blank(),
strip.text.y = element_blank()
) +
scale_x_continuous(breaks = seq(-3, 3, 1)) +
labs(x = NULL) +
geom_polygon(
data = tibble(x = c(-1, -1, 1, 1), y = c(0, 1000, 1000, 0)),
aes(x = x, y = y), fill = IMSCOL["gray", "f5"], alpha = 0.3
) +
geom_polygon(
data = tibble(x = c(-2, -2, 2, 2), y = c(0, 1000, 1000, 0)),
aes(x = x, y = y), fill = IMSCOL["gray", "f5"], alpha = 0.3
) +
geom_polygon(
data = tibble(x = c(-3, -3, 3, 3), y = c(0, 1000, 1000, 0)),
aes(x = x, y = y), fill = IMSCOL["gray", "f5"], alpha = 0.3
) +
theme(
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank()
)
```
::: {.workedexample data-latex=""}
Describe the distribution of the `interest_rate` variable using the histogram in @fig-loan50IntRateHist.
The description should incorporate the center, variability, and shape of the distribution, and it should also be placed in context.
Also note any especially unusual cases.
------------------------------------------------------------------------
The distribution of interest rates is unimodal and skewed to the high end.
Many of the rates fall near the mean at 11.57%, and most fall within one standard deviation (5.05%) of the mean.
There are a few exceptionally large interest rates in the sample that are above 20%.
:::
In practice, the variance and standard deviation are sometimes used as a means to an end, where the "end" is being able to accurately estimate the uncertainty associated with a sample statistic.
For example, in @sec-foundations-mathematical the standard deviation is used in calculations that help us understand how much a sample mean varies from one sample to the next.
\clearpage
## Box plots, quartiles, and the median {#sec-boxplots}
A **box plot**\index{plot!box}\index{box plot} summarizes a dataset using five statistics while also identifying unusual observations.
@fig-loan-int-rate-boxplot-dotplot provides a dot plot and a box plot of the `interest_rate` variable from the `loan50` dataset.^[Box plots were introducted by Mary Eleanor Spear who considered them to be a particular type of bar plot, see page 166 of @Spear1952. Mistakenly, box plots are often attributed to John Tukey who was the first person to call them "box-and-whisker plots."]
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "box plot")
```
```{r}
#| label: fig-loan-int-rate-boxplot-dotplot
#| fig-cap: Distribution of interest rates from the `loan50` dataset.
#| fig-subcap:
#| - Dot plot
#| - Box plot
#| fig-alt: |
#| Two plots showing the same variable, interests rates. The top image is a
#| dot plot, the bottom image is a box plot. Both images re-establish that
#| the distribution of interest rates are right skewed.
#| fig-asp: 0.3
ggplot(loan50, aes(x = interest_rate)) +
geom_dotplot(binwidth = 1, dotsize = 0.6) +
labs(x = NULL, y = NULL) +
theme(
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
) +
scale_x_continuous(
labels = label_percent(scale = 1, accuracy = 1),
limits = c(0, 30)
)
ggplot(loan50, aes(x = interest_rate)) +
geom_boxplot(outlier.size = 2.5) +
theme(
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
) +
labs(x = "Interest rate") +
scale_x_continuous(
labels = label_percent(scale = 1, accuracy = 1),
limits = c(0, 30)
)
```
The dark line inside the box represents the **median**\index{median}, which splits the data in half.
50% of the data fall below this value and 50% fall above it.
Since in the `loan50` dataset there are `r nrow(loan50)` observations (an even number), the median is defined as the average of the two observations closest to the $50^{th}$ percentile.
@tbl-loan50-int-rate-sorted shows all interest rates, arranged in ascending order.
We can see that the $25^{th}$ and the $26^{th}$ values are both `r sort(loan50$interest_rate)[25]`, which corresponds to the thick line in @fig-loan-int-rate-boxplot-dotplot-2.
```{r}
#| label: tbl-loan50-int-rate-sorted
#| tbl-cap: |
#| Interest rates from the `loan50` dataset, arranged in ascending order.
#| tbl-pos: H
loan50_interest_rate_sorted <- sort(loan50$interest_rate)
matrix(
c(
loan50_interest_rate_sorted[1:10],
loan50_interest_rate_sorted[11:20],
loan50_interest_rate_sorted[21:30],
loan50_interest_rate_sorted[31:40],
loan50_interest_rate_sorted[41:50]
),
byrow = TRUE,
ncol = 10
) |>
data.frame(row.names = c("1", "10", "20", "30", "40")) |>
kbl(
linesep = "", booktabs = TRUE,
col.names = as.character(1:10)
) |>
kable_styling(
bootstrap_options = c("striped", "condensed"),
latex_options = c("striped")
)
```
When there are an odd number of observations, there will be exactly one observation that splits the data into two halves, and in such a case that observation is the median (no average needed).
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "median")
```
::: {.important data-latex=""}
**Median: the number in the middle.**
If the data are ordered from smallest to largest, the **median** is the observation right in the middle.
If there are an even number of observations, there will be two values in the middle, and the median is taken as their average.
:::
\clearpage
The second step in building a box plot is drawing a rectangle to represent the middle 50% of the data.
The length of the box is called the **interquartile range**\index{interquartile range}, or **IQR**\index{IQR} for short.
It, like the standard deviation, is a measure of \index{variability}variability in data.
The more variable the data, the larger the standard deviation and IQR tend to be.
The two boundaries of the box are called the **first quartile**\index{first quartile} (the $25^{th}$ percentile, i.e., 25% of the data fall below this value) and the **third quartile**\index{third quartile} (the $75^{th}$ percentile, i.e., 75% of the data fall below this value), and these are often labeled $Q_1$ and $Q_3,$ respectively.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "interquartile range", "IQR", "first quartile", "third quartile", "percentile")
```
::: {.important data-latex=""}
**Interquartile range (IQR).**
The IQR interquartile range is the length of the box in a box plot.
It is computed as $IQR = Q_3 - Q_1,$ where $Q_1$ and $Q_3$ are the $25^{th}$ and $75^{th}$ percentiles, respectively.
A $\alpha$ **percentile**\index{percentile} is a number with $\alpha$% of the observations below and $100-\alpha$% of the observations above.
For example, the $90^{th}$ percentile of SAT scores is the value of the SAT score with 90% of students below that value and 10% of students above that value.
:::
::: {.guidedpractice data-latex=""}
What percent of the data fall between $Q_1$ and the median?
What percent is between the median and $Q_3$?[^05-explore-numerical-10]
:::
[^05-explore-numerical-10]: Since $Q_1$ and $Q_3$ capture the middle 50% of the data and the median splits the data in the middle, 25% of the data fall between $Q_1$ and the median, and another 25% falls between the median and $Q_3.$
Extending out from the box, the **whiskers**\index{whisker} attempt to capture the data outside of the box.
The whiskers of a box plot reach to the minimum and the maximum values in the data, unless there are points that are considered unusually high or unusually low, which are identified as potential **outliers**\index{outlier} by the box plot.
These are labeled with a dot on the box plot.
The purpose of labeling the outlying points -- instead of extending the whiskers to the minimum and maximum observed values -- is to help identify any observations that appear to be unusually distant from the rest of the data.
There are a variety of formulas for determining whether a particular data point is considered an outlier, and different statistical software use different formulas.
A commonly used formula is that any observation beyond $1.5\times IQR$ away from the first or the third quartile is considered an outlier.
In a sense, the box is like the body of the box plot and the whiskers are like its arms trying to reach the rest of the data, up to the outliers.
```{r}
#| include: false
terms_chp_05 <- c(terms_chp_05, "outlier", "whiskers")
```
::: {.important data-latex=""}
**Outliers are extreme.**
An **outlier** is an observation that appears extreme relative to the rest of the data.
Examining data for outliers serves many useful purposes, including
- identifying strong skew \index{strong skew} in the distribution,
- identifying possible data collection or data entry errors, and
- providing insight into interesting properties of the data.
Keep in mind, however, that some datasets have a naturally long skew and outlying points do **not** represent any sort of problem in the dataset.
:::
::: {.guidedpractice data-latex=""}
Using the box plot in @fig-loan-int-rate-boxplot-dotplot-2, estimate the values of the $Q_1,$ $Q_3,$ and IQR for `interest_rate` in the `loan50` dataset.[^05-explore-numerical-11]
:::
[^05-explore-numerical-11]: These visual estimates will vary a little from one person to the next: $Q_1 \approx$ 8%, $Q_3 \approx$ 14%, IQR $\approx$ 14 - 8 = 6%.
\clearpage
## Robust statistics
How are the **sample statistics** \index{sample statistic} of the `interest_rate` dataset affected by the observation, 26.3%?
What would have happened if this loan had instead been only 15%?
What would happen to these summary statistics \index{summary statistic} if the observation at 26.3% had been even larger, say 35%?
The three conjectured scenarios are plotted alongside the original data in @fig-loan-int-rate-robust-ex, and sample statistics are computed under each scenario in @tbl-robustOrNotTable.
```{r}
#| label: tbl-robustOrNotTable
#| tbl-cap: |
#| A comparison of how the median, IQR, mean, and standard deviation
#| change as the value of an extreme observation from the original interest
#| data changes.
#| tbl-pos: H
loan50_original <- loan50 |>
select(interest_rate) |>
mutate(
mark = if_else(interest_rate == 26.30, TRUE, FALSE)
)
loan50_15 <- loan50 |>
select(interest_rate) |>
mutate(
mark = if_else(interest_rate == 26.30, TRUE, FALSE),
interest_rate = if_else(interest_rate == 26.30, 15, interest_rate)
)
loan50_35 <- loan50 |>
select(interest_rate) |>
mutate(
mark = if_else(interest_rate == 26.30, TRUE, FALSE),
interest_rate = if_else(interest_rate == 26.30, 35, interest_rate)
)
loan50_robust_check <- bind_rows(
loan50_original |> mutate(Scenario = "Original data"),
loan50_15 |> mutate(Scenario = "Move 26.3% to 15%"),
loan50_35 |> mutate(Scenario = "Move 26.3% to 35%")
) |>
mutate(Scenario = fct_relevel(Scenario, "Original data", "Move 26.3% to 15%", "Move 26.3% to 35%"))
loan50_robust_check |>
group_by(Scenario) |>
summarise(
Median = median(interest_rate),
IQR = IQR(interest_rate),
Mean = mean(interest_rate),
SD = sd(interest_rate)
) |>
kbl(linesep = "", booktabs = TRUE, align = "lcccc") |>
kable_styling(
bootstrap_options = c("striped", "condensed"),
latex_options = c("striped")
) |>
add_header_above(c(" " = 1, "Robust" = 2, "Not robust" = 2))
```
```{r}
#| label: fig-loan-int-rate-robust-ex
#| fig-cap: Dot plots of the original interest rate data and two modified datasets.
#| fig-subcap:
#| - Original data
#| - Move 26.3% to 15%
#| - Move 26.3% to 35%
#| fig-alt: |
#| Three dot plots are displayed where a single point is highlighted.
#| In the top plot is the original data where the highlighted point is the
#| largest value, at 26.3%. The second plot shows the distribution of the
#| interest rate data after moving the highlighted point from 26.3% to 15%. The
#| third plot shows the distribution of the interest rate data after moving the
#| highlighted point from 26.3% to 35%. The corresponding change in statistics
#| are given in @tbl--robustOrNotTable.
#| fig-asp: 0.3
#| fig-width: 5
ggplot(loan50_original, aes(x = interest_rate)) +
geom_dotplot(binwidth = 1, dotsize = 0.7) +
scale_x_continuous(
labels = label_percent(scale = 1, accuracy = 1),
limits = c(0, 35)