-
Notifications
You must be signed in to change notification settings - Fork 0
/
06-t-test.qmd
3238 lines (2522 loc) · 97.6 KB
/
06-t-test.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
# T-test {#sec-chap06}
```{r}
#| label: setup
#| include: false
base::source(file = "R/helper.R")
ggplot2::theme_set(ggplot2::theme_bw())
```
```{r}
#| label: cranlogs
#| include: false
#| eval: false
## run only once manually #########
cranlogs_cohensd <- pkgs_dl(c("lsr", "effectsize", "rstatix", "effsize"))
save_data_file("chap06", cranlogs_cohensd, "cranlogs_cohensd.rds")
cranlogs_skewness <-
pkgs_dl(c("datawizard", "e1071", "moments", "psych", "semTools", "statpsych"))
save_data_file("chap06", cranlogs_skewness, "cranlogs_skewness.rds")
cranlogs_ad_test <- pkgs_dl(c("cmstatr", "DescTools", "kSamples", "nortest"))
save_data_file("chap06", cranlogs_ad_test, "cranlogs_ad_test.rds")
cranlogs_levene_test <- pkgs_dl(c("car", "DescTools", "misty", "rstatix"))
save_data_file("chap06", cranlogs_levene_test, "cranlogs_levene_test.rds")
cranlogs_sign_test <- pkgs_dl(c("BSDA", "DescTools", "rstatix"))
save_data_file("chap06", cranlogs_sign_test, "cranlogs_sign_test.rds")
cranlogs_misc <-
pkgs_dl(c("ggstats", "ggstatsplot", "rcompanion", "statsExpressions"))
save_data_file("chap06", cranlogs_misc, "cranlogs_misc.rds")
```
## Achievements to unlock
:::::: {#obj-chap06}
::::: my-objectives
::: my-objectives-header
Objectives for chapter 06
:::
::: my-objectives-container
**SwR Achievements**
- **Achievement 1**: Understanding the relationship between one categorical variable and one continuous variable using histograms, means, and standard deviations (@sec-chap06-achievement1)
- **Achievement 2**: Comparing a sample mean to a population mean with a `r glossary("one-sample", "one-sample t-test")` (@sec-chap06-achievement2)
- **Achievement 3**: Comparing two unrelated sample means with an `r glossary("independent", "independent-samples t-test")` (@sec-chap06-achievement3)
- **Achievement 4**: Comparing two related sample means with a `r glossary("paired", "dependent-samples t-test")` (@sec-chap06-achievement4)
- **Achievement 5**: Computing and interpreting an `r glossary("effect size")` for significant t-tests (@sec-chap06-achievement5)
- **Achievement 6**: Examining and checking the underlying assumptions for using the t-test (@sec-chap06-achievement6)
- **Achievement 7**: Identifying and using alternate tests when t-test assumptions are not met (@sec-chap06-achievement7)
:::
:::::
Achievements for chapter 06
::::::
## The blood pressure predicament
- **Systolic blood pressure** is measured in millimeters of mercury, or mmHG, and ranges from 74 to 238.
- **Diastolic blood pressure** is also measured in mmHG and ranges from 0 to 120.
## Resources & Chapter Outline
### Data, codebook, and R packages {#sec-chap04-data-codebook-packages}
:::::: my-resource
:::: my-resource-header
::: {#lem-chap06-resources}
: Data, codebook, and R packages for learning about t-test
:::
::::
::: my-resource-container
**Data**
Two options for accessing the data:
- Download the data set `nhanes_2015–2016_ch6.csv` from <https://edge.sagepub.com/harris1e>.
- Follow the instructions in Box 6.1 to import the data directly with the halp of {**NHANES**} from the Internet into R.
**Codebook**
Two options for accessing the codebook:
- Download the codebook files `nhanes_demographics_20152016_codebook.html` and `nhanes_examination_20152016_codebook.html` from <https://edge.sagepub.com/harris1e>.\
- Use the online version of the codebook on the NHANES website (https://www.cdc.gov/nchs/nhanes/index.htm)
**Packages**
1. Packages used with the book (sorted alphabetically)
- {**BSDA**} @sec-BSDA (Alan T. Arnholt)
- {**car**} @sec-car (John Fox)
- {**lsr**} @sec-lsr (Danielle Navarro)\
- {**rcompanion**} 1 (Salvatore Mangiafico)
- {**RNHANES**} @sec-RNHANES (Herb Susmann)
- {**tidyverse**}: @sec-tidyverse (Hadley Wickham)
2. My additional packages new introduced (sorted alphabetically)
- {**datawizard**} @sec-datawizard (Etienne Bacher)
- {**e1071**} @sec-e1071 (David Meyer)
- {**effectsize**} @sec-effectsize (Mattan S. Ben-Shachar)
- {**moments**} @sec-moments (Lukasz Komsta)
- {**misty**} @sec-misty (Takuya Yanagida)
- {**nhanesA**} @sec-nhanesA (Christopher Endres)
- {**nortest**} @sec-nortest (Uwe Ligges)
- {**psych**} @sec-psych (William Revelle)
- {**rcompanion**} 1 (Salvatore Mangiafico)
:::
::::::
### Get data
::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap06-get-data}
: Numbered Example Title
:::
::::
:::::::::::: my-example-container
::::::::::: panel-tabset
###### NHANES data
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-get-nhanes-data}
: Get NHANES data for blood pressure examination with demographics variable for 2015-2016
:::
::::
::: my-r-code-container
```{r}
#| label: get-nhanes-data
#| cache: true
#| eval: false
## run one once manually #########
## list EXAM tables for 2016 to get file names
exam_tables_2016 <- nhanesA::nhanesTables('EXAM', 2016)
## list variables in BPX_I (Blood Pressure file)
bpx_i_variables <- nhanesA::nhanesTableVars('EXAM', 'BPX_I')
bpx_i <- nhanesA::nhanes('BPX_I')
demo_i <- nhanesA::nhanes('DEMO_I')
bpx_2016 <- dplyr::full_join(demo_i, bpx_i, by = "SEQN")
save_data_file("chap06", bpx_2016, "bpx_2016.rds")
```
(*For this R code chunk is no output available. For the raw data see* )
:::
::::::
###### NHANES codebook
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-get-nhanes-codebook}
: Get NHANES codebook for blood pressure examination with demographics variable for 2015-2016
:::
::::
::: my-r-code-container
```{r}
#| label: get-nhanes-codebook
cb_systolic <- nhanesA::nhanesCodebook("BPX_I", "BPXSY1")
cb_diastolic <- nhanesA::nhanesCodebook("BPX_I", "BPXDI1")
```
------------------------------------------------------------------------
(*For this R code chunk is no output available. For the raw data see*)
Besides to call the appropriate website for 2015-2016 [examination codebook](nhanes_examination_20152016_codebook.html) and [demographic codebook](nhanes_demographics_20152016_codebook.html) there is also the option to download information via {**nhanesA**}.
:::
::::::
:::::::::::
::::::::::::
:::::::::::::::
------------------------------------------------------------------------
### Show raw data
:::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap06-show-raw-data}
: Numbered Example Title
:::
::::
::::::::::::: my-example-container
:::::::::::: panel-tabset
###### Blood pressure data
::::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-glance-nhanes-data}
: Glance at NHANES data for blood pressure examination with demographics variable for 2015-2016
:::
::::
:::: my-r-code-container
::: {#lst-glance-nhanes-data}
```{r}
#| label: glance-nhanes-data
bpx_2016 <- base::readRDS("data/chap06/bpx_2016.rds")
skimr::skim(bpx_2016)
my_glance_data(bpx_2016)
```
Glance at NHANES data for blood pressure examination with demographics variable for 2015-2016
:::
::::
:::::::
###### Blood pressure codebook
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-glance-nhanes-codebook}
: Glance at NHANES codebook for systolic & diastolic blood pressure (2015-2016)
:::
::::
::: my-r-code-container
```{r}
#| label: glance-nhanes-codebook
#| results: hold
glue::glue("*********************** Systolic blood pressure ******************")
cb_systolic
glue::glue(" ")
glue::glue("*********************** Diastolic blood pressure ******************")
cb_diastolic
```
:::
::::::
::::::::::::
:::::::::::::
::::::::::::::::
------------------------------------------------------------------------
### Recode data
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-clean-data}
: Clean NHANES blood pressure data (2015-2016)
:::
::::
::: my-r-code-container
```{r}
#| label: clean-data
## load bpx_2016 #######
bpx_2016 <- base::readRDS("data/chap06/bpx_2016.rds")
bp_clean <- bpx_2016 |>
dplyr::rename(
systolic = BPXSY1,
systolic2 = BPXSY2,
sex = RIAGENDR
) |>
dplyr::mutate(diff_syst = systolic - systolic2) |>
dplyr::relocate(c(systolic, systolic2, diff_syst), .before = sex)
save_data_file("chap06", bp_clean, "bp_clean.rds")
```
------------------------------------------------------------------------
(*For this R code chunk is no output available*)
:::
::::::
## Achievement 1: Relationship between one categorical and one continuous variable {#sec-chap06-achievement1}
For this first achievement we are going to look into the relationship between one categorical variable and one continuous variable using histograms, means, and standard deviations.
::::::::::::::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap06-descriptive}
: Description of blood pressure data from NHANES 2015-2016
:::
::::
:::::::::::::::::::::::: my-example-container
::::::::::::::::::::::: panel-tabset
###### Histogram 1
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-systolic-histo1}
: Histogram of systolic blood pressure (NHANES 2015-2016)
:::
::::
::: my-r-code-container
```{r}
#| label: systolic-histo1
#| fig-cap: "Histogram of systolic blood pressure (NHANES 2015-2016)"
## load bpx_2016 #######
bpx_2016 <- base::readRDS("data/chap06/bpx_2016.rds")
## graph systolic blood pressure variable BPXSY1 (Figure 6.1)
sys_histo <- bpx_2016 |>
ggplot2::ggplot(
ggplot2::aes(x = BPXSY1)
) +
ggplot2::geom_histogram(
fill = "mediumpurple",
color = "white",
bins = 30,
na.rm = TRUE
) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Systolic blood pressure (mmHg)",
y = "NHANES participants"
)
sys_histo
```
------------------------------------------------------------------------
This is the replication of the book’s Figure 6.1.
The graph is not exactly normally distributed; it has a little right skew. The `r glossary("quantile")` values (0% 25% 50% 75% 100%) are `r quantile(bpx_2016$BPXSY1, na.rm = TRUE)`. The middle 50% lies in the range between `r quantile(bpx_2016$BPXSY1, 0.25, na.rm = TRUE)` and `r quantile(bpx_2016$BPXSY1, 0.75, na.rm = TRUE)` mmHG. You can't see the highest values because their frequencies are too small.
:::
::::::
###### Histogram 2
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-systolic-histo2}
: Histogram of systolic blood pressure with risk factors (NHANES 2015-2016)
:::
::::
::: my-r-code-container
```{r}
#| label: systolic-histo2
#| fig-cap: "Histogram of systolic blood pressure with risk factors (NHANES 2015-2016)"
## graph systolic blood pressure with risk factors (Figure 6.2)
sys_histo2 <- bpx_2016 |>
ggplot2::ggplot(
ggplot2::aes(
x = BPXSY1,
fill = BPXSY1 > 120)
) +
ggplot2::geom_histogram(
color = "white",
bins = 30,
na.rm = TRUE) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Systolic blood pressure (mmHg)",
y = "NHANES participants"
) +
ggplot2::scale_fill_manual(
values = c("mediumpurple", "grey"),
labels = c("Normal range",
"at-risk or high"),
name = "Systolic\nBlood Pressure"
)
sys_histo2
```
------------------------------------------------------------------------
This is the replication of the book’s Figure 6.2.
:::
::::::
###### Experiment
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-systolic-histo3}
: Blood pressure histogram with several colors according to their medical conditions
:::
::::
::: my-r-code-container
```{r}
#| label: systolic-histo3
## graph systolic blood pressure differentiated
sys_histo3 <- bpx_2016 |>
dplyr::select(BPXSY1) |>
dplyr::mutate(sys = dplyr::case_when(
BPXSY1 < 105 ~ "0",
BPXSY1 >= 105 & BPXSY1 < 120 ~ "1",
BPXSY1 >= 120 & BPXSY1 < 130 ~ "2",
BPXSY1 >= 130 & BPXSY1 < 140 ~ "3",
BPXSY1 >= 140 ~ "4"
)
) |>
ggplot2::ggplot(
ggplot2::aes(x = BPXSY1, fill = sys)
) +
ggplot2::geom_histogram(
color = "white",
binwidth = 2,
na.rm = TRUE) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "bottom") +
ggplot2::labs(
x = "Systolic blood pressure (mmHg)",
y = "NHANES participants"
) +
ggplot2::scale_fill_manual(
values = c(
"0" = "grey",
"1" = "mediumpurple",
"2" = "yellow",
"3" = "darkorange",
"4" = "red"
),
labels = c("Low",
"Optimal",
"Normal",
"At-risk",
"High"
),
name = "Systolic\nBlood Pressure"
) +
ggplot2::xlim(70, 240)
sys_histo3
```
------------------------------------------------------------------------
Here I have experimented to colorize the histogram with different colors. I took as borders the medical condition for isolated blood pressure measures:
- Low: \< 105
- Optimal: \>= 105 & \< 120
- Normal: \>= 120 & \< 130
- At Risk: \>= 130 & \< 140
- High: \>= 140
In this case I can’t use the color directly as `fill` variable into the `ggplots::aes()` function. Besides I learned two other solve two other issues:
- The sequence of colors are aligned to the values alphabetically. Therefore I had to take characters that are sorted in the correct order. I took c("0", "1", "2", "3", "4") but c("a", "b", "c", "d" ,"e") would have worked too.
- Wider bins brought the problem that the color has changed in the middle of the bar length. I did not know how to solve this issue generally, for instance with providing `breaks` or to provide borders conforming to the medical status. Only `binwidth` of 1 and 2 worked, 3 already showed the problem. Other people had the same problem, see for instance the section "Example 2: Draw Histogram with Different Colors Using ggplot2 Package" in [Draw Histogram with Different Colors in R (2 Examples)](https://statisticsglobe.com/draw-histogram-with-different-colors-in-r) [@schorkn.d].
:::
::::::
###### Histogram 3
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-diastolic-histo}
: Histogram of diastolic blood pressure with risk factors (NHANES 2015-2016)
:::
::::
::: my-r-code-container
```{r}
#| label: diastolic-histo
#| fig-cap: "Histogram of diastolic blood pressure with risk factors (NHANES 2015-2016)"
## graph systolic blood pressure with risk factors (Figure 6.3)
dia_histo <- bpx_2016 |>
ggplot2::ggplot(
ggplot2::aes(
x = BPXDI1,
fill = BPXDI1 > 80)
) +
ggplot2::geom_histogram(
color = "white",
bins = 30,
na.rm = TRUE) +
ggplot2::theme_bw() +
ggplot2::labs(
x = "Diastolic blood pressure (mmHg)",
y = "NHANES participants"
) +
ggplot2::scale_fill_manual(
values = c("mediumpurple", "grey"),
labels = c("Normal range",
"at-risk or high"),
name = "Diastolic\nBlood Pressure"
)
dia_histo
```
------------------------------------------------------------------------
This is the replication of the book’s Figure 6.3.
:::
::::::
###### `mean()` & `sd()`
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-systolic-mean-sd}
: Mean and standard deviation of systolic blood pressure in the NHANES data sample (2015-2016)
:::
::::
::: my-r-code-container
```{r}
#| label: systolic-mean-sd
bpx_stats <-
bpx_2016 |>
tidyr::drop_na(BPXSY1) |>
dplyr::summarize(
mean = base::mean(BPXSY1),
sd = stats::sd(BPXSY1),
n = dplyr::n()
)
bpx_stats
```
:::
::::::
:::::::::::::::::::::::
::::::::::::::::::::::::
:::::::::::::::::::::::::::
## Achievement 2: One-Sample t-test {#sec-chap06-achievement2}
### Introduction
We have a mean of the systolic blood pressure a little bit above 120.54 mmHG. This is almost exactly the upper cutoff value of 120 mmHG for the "normal range" of blood pressure. Is this only valid for the sample of also for the whole population? Have about half of the US people high systolic blood pressure, e.g. more than 120mmHG? The question can be answered with a `r glossary("one-sample", "one-sample t-test")`. The one sample t-test compares a sample mean to a *hypothesized or population* mean.
::::: my-important
::: my-important-header
There are three different t-tests
:::
::: my-important-container
- **One-sample t-test**: compares a mean to a population or hypothesized value
- **Independent-samples t-test**: compares the means of two unrelated groups
- **Dependent-samples t-test**: compares the means of two related groups
:::
:::::
The t-distribution has a bell shape like the normal distribution. But unlike the normal distribution its variance is not known but approximated with its only parameter `r glossary("degrees of freedom")` (df). `df` is calculated by the number of observations minus one ($n-1$). With higher degrees of freedom the t-distribution will get closer to the normal distribution. Often the number 30 is recommended as the cutting point where t-distribution and normal distribution are equivalent.
I am following @prp-chap05-nhst from @sec-chap05-achievement5.
### NHST Step 1
Write the null and alternate hypotheses:
Two considerations:
1. The Null relates most of the times to a situation where no change occurs. In this case that there is no difference in the means of the systolic blood pressure. This is different to the assumption that the mean difference is not higher than 120 mmHG!
2. In the one-sample t-test we are comparing sample mean with population mean. In this case the NHANES sample from the 2015-2016 data with the population mean of the US population.
::: callout-note
- **H0**: There is no difference in the mean systolic blood pressure in the US population and the cutoff for normal blood pressure of 120 mmHG in the NHANES 2015-2016 data set.
- **HA**: There is a difference in the mean systolic blood pressure in the US population and the cutoff for normal blood pressure of 120 mmHG in the NHANES 2015-2016 data set.
:::
### NHST Step 2
Compute the test statistic. The one-sample t-test uses the `r glossary("t-statistic")` (sort of like a z-statistic)
:::::: my-theorem
:::: my-theorem-header
::: {#thm-chap06-t-statistic}
: t-test formula
:::
::::
::: my-theorem-container
$$
t = \frac{m_{x} - \mu_{x}}{\frac{s_x}{\sqrt{n_{x}}}}
$$ {#eq-chap06-t-statistic}
- $m_{x}$ represents the mean of the variable x, the variable to be tested,
- $\mu_{x}$ is the *population mean or hypothesized value* of the variable,
- $s_{x}$ is the sample standard deviation of x, and
- $n_{x}$ is the sample size
:::
::::::
The formula is very similar as the `r glossary("Z-score")` statistic in @eq-chap04-z-score. The only difference is that in the above `r glossary("t-statistic")` the denominator is the `r glossary("standard deviation")` rather than the `r glossary("standard error")`.
- `z` shows how many sample standard deviations some value is away from the mean.
- `t` shows how many standard errors (i.e., population standard deviations) some value is away from the mean.
$$
t = \frac{120.5394 - 120}{\frac{18.61692}{\sqrt{7145}}} = 2.45
$$
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-t-statistic-systolic}
: t-statistic of systolic blood pressure aof NHANES sample with hypothesized population mean
:::
::::
::: my-r-code-container
```{r}
#| label: t-statistic-systolic
(
t_test_systolic <- stats::t.test(
bpx_2016$BPXSY1,
alternative = "two.sided",
mu = 120)
)
## for later use #########
t_sys = t_test_systolic[["statistic"]][["t"]]
df_sys = t_test_systolic[["parameter"]][["df"]]
null_sys = t_test_systolic[["null.value"]][["mean"]]
estimate_sys = t_test_systolic[["estimate"]][["mean of x"]]
p_value_sys = t_test_systolic[["p.value"]]
se_sys = t_test_systolic[["stderr"]]
```
------------------------------------------------------------------------
I have stored the result of the t-test into variables for later use.
:::
::::::
:::::: my-assessment
:::: my-assessment-header
::: {#cor-chap06-t-test-output}
: Explications of the t-test output
:::
::::
::: my-assessment-container
**1. Line**: Data (variable) used. **2. Line**: - `t`: value of the t-test statistic. - `df`: degrees of freedom, with t-statistic = subtracting 1 from sample size = $n - 1$. - `p-value`: The probability of the sample coming from a population where the null hypothesis is true. **3. Line**: wording of the alternative hypothesis. **4. Line**: Chosen confidence interval. **5. Line**: The lower and upper boundary of the confidence interval. **6. Line**: Sample estimates that has to be compared to the value of the null hypothesis.
:::
::::::
### NHST Step 3
Review and interpret the test statistics: Calculate the probability that your test statistic is at least as big as it is if there is no relationship (i.e., the null is true).
The following examples replicates Figure 6.4, 6.5 and 6.6. I will break down the final code into several steps following the nice article \[Visualizing Sampling Distributions: Learn how to add areas under the curve in sampling distributions\]https://ggplot2tutor.com/tutorials/sampling_distributions [@burkhart2021].
::::::::::::::::::::::::::::::::::: my-example
:::: my-example-header
::: {#exm-chap06-prob-dist-t-test}
: Probability distribution of t-test statistic
:::
::::
:::::::::::::::::::::::::::::::: my-example-container
::::::::::::::::::::::::::::::: panel-tabset
###### t (df=1)
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-two-t-prob-dist}
: Student t distributions with 1 degree of freedom (df)
:::
::::
::: my-r-code-container
```{r}
#| label: fig-t-prob-dist
#| fig-cap: Student t distributions with 1 degree of freedom (df)
ggplot2::ggplot() +
ggplot2::xlim(-7, 7) +
## or as an alternative
# ggplot2::ggplot(tibble::tibble(x = c(-7, 7)),
# ggplot2::aes(x)) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = 1),
geom = "line",
linewidth = 0.7
) +
ggplot2::theme_bw()
```
:::
::::::
:::::: my-procedure
:::: my-procedure-header
::: {#prp-chap06-plot-dist}
: Plotting a distribution with {**ggplot2**}
:::
::::
::: my-procedure-container
1. As there is no data (just the formula for the function) we need to specify the x-limits.
2. `ggplot2::stat_function` draws the function. We can specify the function extra or create an anonymous function or --- as I have done here --- use a function from an R package. Note that there is no parenthesis behind the function name.
:::
::::::
###### comparing t
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-compare-t-prob-dist}
: Student t distributions with 1 and 7144 degree of freedom (df) and normal distribution compared
:::
::::
::: my-r-code-container
```{r}
#| label: fig-compare-t-prob-dist
#| fig-cap: Student t distributions with 1 and 7144 degree of freedom (df) and normal distribution compared
ggplot2::ggplot(tibble::tibble(x = c(-7, 7)),
ggplot2::aes(x)) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = 1),
geom = "line",
linewidth = 0.7,
ggplot2::aes(linetype = "1")
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = 7144),
geom = "line",
linewidth = 0.7,
ggplot2::aes(linetype = "5")
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = 30),
geom = "line",
linewidth = 0.7,
ggplot2::aes(linetype = "3")
) +
ggplot2::stat_function(
fun = stats::dnorm,
geom = "line",
linewidth = 0.7,
ggplot2::aes(color = "red")
) +
ggplot2::scale_linetype_discrete(
name = "t dist",
labels = c("df = 1", "df = 30", "df = 7144")
) +
ggplot2::scale_color_discrete(
name = "normal dist",
labels = "mean = 0, sd = 1"
) +
ggplot2::theme_bw()
```
------------------------------------------------------------------------
The plot shows two things:
1. There is a big difference between a t distribution with df = 1 and df = 30.
2. There is no visible difference between t with df = 30, df = 7144 and a normal distribution.
:::
::::::
:::::: my-procedure
:::: my-procedure-header
::: {#prp-chap06-plot-several-dist}
: Plotting several distributions with {**ggplot2**}
:::
::::
::: my-procedure-container
1. Use for every distribution `ggplot2::stat_function()`.
2. Put the aesthetic into an `ggplot2::aes()` function.
3. Add for each legend a corresponding scale with name and labels.
:::
::::::
###### t systolic
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-code-name-b}
: t-distribution (df = 7,144) shaded for values of 2.4491 or higher (replicating Figure 6.5)
:::
::::
::: my-r-code-container
```{r}
#| label: fig-t-test-systolic
#| fig-cap: "t-distribution (df = 7,144) shaded for values of 2.4491 or higher (replicating Figure 6.5)"
ggplot2::ggplot() +
ggplot2::xlim(-4, 4) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "line",
linewidth = 0.7
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "area",
xlim = c(t_sys, 4),
ggplot2::aes(fill =
paste("t >=", round(t_sys, 3))
)
) +
ggplot2::theme_bw() +
ggplot2::scale_fill_manual(
name = "",
values = "steelblue"
)
```
------------------------------------------------------------------------
The plot shows that the t-value of 2.499 is very unlikely if the null hypotheses were true, e.g. if the sample comes from a population with a systolic blodd pressure mean of 240.
:::
::::::
###### 2.5% shaded
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-two-sided-shaded}
: t-distribution (df = 7,144) with 2.5% shaded in each tail of the distribution (replicating Figure 6.6)
:::
::::
::: my-r-code-container
```{r}
#| label: fig-two-sided-shaded
#| fig-cap: "t-distribution (df = 7,144) with 2.5% shaded in each tail of the distribution (replicating Figure 6.6)"
ggplot2::ggplot() +
ggplot2::xlim(-4, 4) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "line",
linewidth = 0.7
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "area",
xlim = c(1.96, 4),
ggplot2::aes(fill =
paste("Rejection region")
)
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "area",
xlim = c(-4, -1.96),
ggplot2::aes(fill =
paste("Rejection region")
)
) +
ggplot2::theme_bw() +
ggplot2::scale_fill_manual(
name = "",
values = "purple3"
) +
ggplot2::labs(
x = "t-statistic",
y = "Probability density"
)
```
------------------------------------------------------------------------
The plot shows the rejection regions for the probability of 95%.
$$
\begin{align*}
p_{low}(x > 1.96) \approx 0.025 \\
p_{high}(x < 1.96) \approx 0.975 \\
p_{high} - p_{low} = \\
0.975 - 0.025 = 0.95
\end{align*}
$$
:::
::::::
###### t systolic & 2.5% shaded overlaid
:::::: my-r-code
:::: my-r-code-header
::: {#cnj-chap06-t-two-sided-shaded}
: t-distribution (df = 7,144) with 2.5% shaded in each tail of the distribution (replicating Figure 6.6)
:::
::::
::: my-r-code-container
```{r}
#| label: fig-t-two-sided-shaded
#| fig-cap: "t-distribution (df = 7,144) with 2.5% shaded in each tail of the distribution (replicating Figure 6.6)"
ggplot2::ggplot() +
ggplot2::xlim(-4, 4) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "line",
linewidth = 0.7
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "area",
xlim = c(1.96, 4),
alpha = 0.5,
ggplot2::aes(fill =
paste("Rejection region"),
)
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "area",
xlim = c(-4, -1.96),
alpha = 0.5,
ggplot2::aes(fill =
paste("Rejection region"),
),
) +
ggplot2::stat_function(
fun = stats::dt,
args = list(df = df_sys),
geom = "area",
xlim = c(t_sys, 4),
alpha = 0.5,
ggplot2::aes(fill =
paste("t >=", round(t_sys, 3))
)
) +
ggplot2::theme_bw() +
ggplot2::scale_fill_manual(
name = "",
values = c("purple3", "red")
) +
ggplot2::labs(
x = "t-statistic",
y = "Probability density"
)
```
------------------------------------------------------------------------
The plot shows that the t-value is in the `r glossary("rejection region", "rejection area")`, e.g., the null has to be rejected.
:::
::::::
:::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::
### NHST Step 4
Conclude and write the report.
Even though the difference between the mean systolic blood pressure of `r round(estimate_sys, 2)` and the hypothesized value of `r null_sys` is small, it is statistically significant. The probability of this sample that it comes from a population where the mean systolic blood pressure is actually `r null_sys` is just `r round(p_value_sys, 3)*100`%. This sample is likely to be from a population with a higher mean blood pressure.
::: callout-tip
The mean systolic blood pressure in a sample of `r df_sys + 1` people was `r round(estimate_sys, 2)` (sd = `r round(bpx_stats$sd, 2)`). A one-sample t-test found this mean to be statistically significantly different from the hypothesized mean of `r null_sys` \[t(`r df_sys`) = `r round(t_sys, 3)`; p = `r round(p_value_sys, 3)`\]. The sample likely came from a population with a mean systolic blood pressure not equal to `r null_sys`.
:::
## Achievement 3: Independent-samples t-test {#sec-chap06-achievement3}
Instead of comparing one mean to a hypothesized or population mean, the `r glossary("independent", "independent-samples t-test")` compares the means of two groups to each other.