forked from SurgicalInformatics/healthyr_book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_working_continuous.Rmd
886 lines (675 loc) · 39.6 KB
/
06_working_continuous.Rmd
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
# (PART) Data analysis {-}
```{r include=FALSE}
library(ggplot2)
theme_set(theme_bw())
library(kableExtra)
```
In the second part of this book, we focus specifically on the business of data analysis, that is, formulating clear questions and seeking to answer them using available datasets.
Again, we emphasise the importance of understanding the underlying data through visualisation, rather than relying on statistical tests or, heaven forbid, the *p*-value alone.
There are five chapters.
Testing for continuous outcome variables (6) leads naturally into linear regression (7).
We would expect the majority of actual analysis done by readers to be using the methods in chapter 7 rather than 6.
Similarly, testing for categorical outcome variables (8) leads naturally to logistic regression (9), where we would expect the majority of work to focus.
Chapters 6 and 8 however do provide helpful reminders of how to prepare data for these analyses and shouldn't be skipped.
time-to-event data (10) introduces survival analysis and includes sections on the manipulation of dates.
# Working with continuous outcome variables{#chap06-h1}
\index{continuous data@\textbf{continuous data}}
> Continuous data can be measured.
> Categorical data can be counted.
## Continuous data
Continuous data is everywhere in healthcare.
From physiological measures in patients such as systolic blood pressure or pulmonary function tests, through to population measures like life expectancy or disease incidence, the analysis of continuous outcome measures is common and important.
Our goal in most health data questions, is to draw a conclusion on a comparison between groups.
For instance, understanding differences in life expectancy between the year 2002 and 2007 is more useful than simply describing the average life expectancy across all of time.
The basis for comparisons between continuous measures is the *distribution* of the data.
That word, as many which have a statistical flavour, brings on the sweats in many people.
It needn't.
By distribution, we are simply referring to the shape of the data.
## The Question
The examples in this chapter all use the data introduced previously from the amazing [Gapminder project](https://www.gapminder.org/).
We will start by looking at the life expectancy of populations over time and in different geographical regions.
## Get and check the data {#chap06-h2-check}
```{r, message=F}
# Load packages
library(tidyverse)
library(finalfit)
library(gapminder)
# Create object gapdata from object gapminder
gapdata <- gapminder
```
It is vital that datasets be carefully inspected when first read (for help reading data into R see \@ref(chap02-h2-reading-data-into-r)).
The three functions below provide a clear summary, allowing errors or miscoding to be quickly identified.
It is particularly important to ensure that any missing data is identified (see Chapter \@ref(chap11-h1)).
If you don't do this you will regret it!
There are many times when an analysis has got to a relatively advanced stage before the researcher was hit by the realisation that the dataset was far from complete.
```{r}
glimpse(gapdata) # each variable as line, variable type, first values
missing_glimpse(gapdata) # missing data for each variable
```
```{r results = "hide"}
ff_glimpse(gapdata) # summary statistics for each variable
```
\index{functions@\textbf{functions}!glimpse}
\index{functions@\textbf{functions}!missing\_glimpse}
\index{functions@\textbf{functions}!ff\_glimpse}
```{r message=FALSE, echo=FALSE}
sum_gapdata <- ff_glimpse(gapdata) # summary statistics for each variable
library(knitr)
library(kableExtra)
sum_gapdata[[1]] %>%
select(-c(5, 8, 9, 11, 12)) %>%
kable(row.names = FALSE, align = c("l", "l", "l", "r", "r", "r", "r", "r", "r", "r"),
booktabs = TRUE, caption = "Gapminder dataset, ff\\_glimpse: continuous.",
linesep = c("", "", "\\addlinespace")) %>%
kable_styling(latex_options = c("scale_down", "hold_position")) %>%
column_spec(1, width = "4cm")
```
```{r message=FALSE, echo=FALSE}
t = sum_gapdata[[2]] %>%
select(-c(5, 9))
t$levels[2] = c("\`\`Africa\", \`\`Americas\", \`\`Asia\", \`\`Europe\", \`\`Oceania\"")
t %>%
kable(row.names = FALSE, align = c("l", "l", "l", "r", "r", "r", "r", "r", "r", "r"),
booktabs = TRUE, caption = "Gapminder dataset, ff\\_glimpse: categorical.",
linesep = c("", "", "\\addlinespace")) %>%
kable_styling(latex_options = c("scale_down", "hold_position")) %>%
column_spec(6, width = "3cm") %>%
column_spec(7, width = "3cm")
```
As can be seen, there are 6 variables, 4 are continuous and 2 are categorical. The categorical variables are already identified as `factors`. There are no missing data. Note that by default, the maximum number of factor levels shown is give, which is why 142 country names are not printed. This can be adjusted using `ff_glimpse(gapdata, levels_cut = 142)`
## Plot the data
We will start by comparing life expectancy between the 5 continents of the world in two different years.
Always plot your data first.
Never skip this step!
We are particularly interested in the distribution.
There's that word again.
The shape of the data.
Is it normal?
Is it skewed?
Does it differ between regions and years?
There are three useful plots which can help here:
- Histograms: examine shape of data and compare groups;
- Q-Q plots: are data normally distributed?
- Box-plots: identify outliers, compare shape and groups.
### Histogram{#chap06-h3-hist-plot}
```{r chap06-fig-hist-life-year, fig.width=7, fig.height=3.5, fig.cap="Histogram: Country life expectancy by continent and year."}
gapdata %>%
filter(year %in% c(2002, 2007)) %>%
ggplot(aes(x = lifeExp)) + # remember aes()
geom_histogram(bins = 20) + # histogram with 20 bars
facet_grid(year ~ continent) # optional: add scales="free"
```
What can we see?
That life expectancy in Africa is lower than in other regions.
That we have little data for Oceania given there are only two countries included, Australia and New Zealand.
That Africa and Asia have greater variability in life expectancy by country than in the Americas or Europe.
That the data follow a reasonably normal shape, with Africa 2002 a little right skewed.
### Quantile-quantile (Q-Q) plot{#chap06-h3-qq-plot}
Quantile-quantile sounds more complicated than it really is.
It is a graphical method for comparing the distribution (think shape) of our own data to a theoretical distribution, such as the normal distribution.
In this context, quantiles are just cut points which divide our data into bins each containing the same number of observations.
For example, if we have the life expectancy for 100 countries, then quartiles (note the quar-) for life expectancy are the three ages which split the observations into 4 groups each containing 25 countries.
A Q-Q plot simply plots the quantiles for our data against the theoretical quantiles for a particular distribution (the default shown below is the normal distribution).
If our data follow that distribution (e.g., normal), then our data points fall on the theoretical straight line.
```{r chap06-fig-qq-life-year, fig.width=7, fig.height=3.5, fig.cap="Q-Q plot: Country life expectancy by continent and year."}
gapdata %>%
filter(year %in% c(2002, 2007)) %>%
ggplot(aes(sample = lifeExp)) + # Q-Q plot requires 'sample'
geom_qq() + # defaults to normal distribution
geom_qq_line(colour = "blue") + # add the theoretical line
facet_grid(year ~ continent)
```
\index{plotting@\textbf{plotting}!geom\_qq}
\index{plotting@\textbf{plotting}!geom\_qq\_line}
What can we see?
We are looking to see if the data (dots) follow the straight line which we included in the plot.
These do reasonably, except for Africa which is curved upwards at each end.
This is the right skew we could see on the histograms too.
If your data do not follow a normal distribution, then you should avoid using a *t*-test or ANOVA when comparing groups.
Non-parametric tests are one alternative and are described in Section \@ref(chap06-non-param-tests).
We are frequently asked about the pros and cons of checking for normality using a statistical test, such as the Shapiro-Wilk normality test.
We don't recommend it.
The test is often non-significant when the number of observations is small but the data look skewed, and often significant when the number of observations is high but the data look reasonably normal on inspection of plots.
It is therefore not useful in practice - common sense should prevail.
### Boxplot
\index{plotting@\textbf{plotting}!geom\_boxplot}
\index{plotting@\textbf{plotting}!boxplot}
Boxplots are our preferred method for comparing a continuous variable such as life expectancy across a categorical explanatory variable.
For continuous data, box plots are a lot more appropriate than bar plots with error bars (also known as dynamite plots).
We intentionally do not even show you how to make dynamite plots.
The box represents the median (bold horizontal line in the middle) and interquartile range (where 50% of the data sits).
The lines (whiskers) extend to the lowest and highest values that are still within 1.5 times the interquartile range.
Outliers (anything outwith the whiskers) are represented as points.
The beautiful boxplot thus contains information not only on central tendency (median), but on the variation in the data and the distribution of the data, for instance a skew should be obvious.
```{r chap06-fig-boxplot-life-year, fig.width=7, fig.height=3, fig.cap="Boxplot: Country life expectancy by continent and year."}
gapdata %>%
filter(year %in% c(2002, 2007)) %>%
ggplot(aes(x = continent, y = lifeExp)) +
geom_boxplot() +
facet_wrap(~ year)
```
What can we see?
The median life expectancy is lower in Africa than in any other continent.
The variation in life expectancy is greatest in Africa and smallest in Oceania.
The data in Africa looks skewed, particularly in 2002 - the lines/whiskers are unequal lengths.
\FloatBarrier
We can add further arguments to adjust the plot to our liking.
We particularly encourage the inclusion of the actual data points, here using `geom_jitter()`.
```{r chap06-fig-boxplot-jitter, fig.width=7, fig.height=3, fig.cap="Boxplot with jitter points: Country life expectancy by continent and year."}
gapdata %>%
filter(year %in% c(2002, 2007)) %>%
ggplot(aes(x = factor(year), y = lifeExp)) +
geom_boxplot(aes(fill = continent)) + # add colour to boxplots
geom_jitter(alpha = 0.4) + # alpha = transparency
facet_wrap(~ continent, ncol = 5) + # spread by continent
theme(legend.position = "none") + # remove legend
xlab("Year") + # label x-axis
ylab("Life expectancy (years)") + # label y-axis
ggtitle(
"Life expectancy by continent in 2002 v 2007") # add title
```
## Compare the means of two groups
### *t*-test
\index{t-test@\textbf{t-test}}
A *t*-test is used to compare the means of two groups of continuous measurements.
Volumes have been written about this elsewhere, and we won't rehearse it here.
There are a few variations of the *t*-test.
We will use two here.
The most useful in our context is a two-sample test of independent groups.
Repeated-measures data, such as comparing the same countries in different years, can be analysed using a paired *t*-test.
### Two-sample *t*-tests
\index{t-test@\textbf{t-test}!two-sample}
Referring to Figure \@ref(fig:chap06-fig-boxplot-life-year), let's compare life expectancy between Asia and Europe for 2007.
What is imperative is that you decide what sort of difference exists by looking at the boxplot, rather than relying on the *t*-test output.
The median for Europe is clearly higher than in Asia.
The distributions overlap, but it looks likely that Europe has a higher life expectancy than Asia.
By running the two-sample *t*-test here, we make the assumption that life expectancy in each country represents an independent measurement of life expectancy in the continent as a whole.
This isn't quite right if you think about it carefully.
Imagine a room full of enthusiastic geniuses learning R.
They arrived today from various parts of the country.
For reasons known only to you, you want to know whether the average (mean) height of those wearing glasses is different to those with perfect vision.
You measure the height of each person in the room, check them for glasses, and run a two-sample *t*-test.
In statistical terms, your room represents a sample from an underlying population.
Your ability to answer the question accurately relies on a number of factors.
For instance, how many people are in the room?
The more there are, the more certain you can be about the mean measurement in your groups being close to the mean measurement in the overall population.
What is also crucial is that your room is a representative sample of the population.
Are the observations independent, i.e., is each observation unrelated to the others?
If you have inadvertently included a family of bespectacled nerdy giants, not typical of those in the country as a whole, your estimate will be wrong and your conclusion incorrect.
So in our example of countries and continents, you have to assume that the mean life expectancy of each country does not depend on the life expectancies of other countries in the group. In other words, that each measurement is independent.
```{r}
ttest_data <- gapdata %>% # save as object ttest_data
filter(year == 2007) %>% # 2007 only
filter(continent %in% c("Asia", "Europe")) # Asia/Europe only
ttest_result <- ttest_data %>% # example using pipe
t.test(lifeExp ~ continent, data = .) # note data = ., see below
ttest_result
```
\index{functions@\textbf{functions}!t.test}
The Welch two-sample *t*-test is the most flexible and copes with differences in variance (variability) between groups, as in this example.
The difference in means is provided at the bottom of the output.
The *t*-value, degrees of freedom (df) and *p*-value are all provided.
The *p*-value is `r ttest_result$p.value %>% round_tidy(5)`.
We used the assignment arrow to save the results of the *t*-test into a new object called `ttest_result`.
If you look at the Environment tab, you should see `ttest_result` there.
If you click on it - to view it - you'll realise that it's not structured like a table, but a list of different pieces of information.
The structure of the *t*-test object is shown in Figure \@ref(fig:chap06-ttest-object).
```{r chap06-ttest-object, echo = FALSE, out.width = "100%", fig.cap="A list object that is the result of a t-test in R. We will show you ways to access these numbers and how to wrangle them into more familiar tables/tibbles."}
knitr::include_graphics("images/chapter06/ttest-object.png")
```
The *p*-value, for instance, can be accessed like this:
```{r}
ttest_result$p.value # Extracted element of result object
```
The confidence interval of the difference in mean life expectancy between the two continents:
```{r}
ttest_result$conf.int # Extracted element of result object
```
The **broom** package provides useful methods for 'tidying' common model outputs into a `tibble`.
So instead of accessing the various bits of information by checking the `names()` and then using the `$` operator, we can use functions called `tidy()` and `glance()` to wrangle the statistical output into a table:
```{r include=FALSE}
library(broom)
tidy(ttest_result)
```
```{r chap06-tab-ttest, echo=FALSE}
tidy(ttest_result) %>%
select(-method, -alternative) %>% # removing the last 2 columns, just doesn't fit on the PDF page
knitr::kable(booktabs = TRUE, caption = "Results of a t-test wrangled into a table using library(broom).") %>%
kableExtra::kable_styling(font_size=9)
```
**Reminder: When the pipe sends data to the wrong place: use `data = .` to redirect it**
In the code above, the `data = .` bit is necessary because the pipe usually sends data to the beginning of function brackets.
So `gapdata %>% t.test(lifeExp ~ continent)` would be equivalent to `t.test(gapdata, lifeExp ~ continent)`.
However, this is not an order that `t.test()` will accept.
`t.test()` wants us to specify the formula first, and then wants the data these variables are present in.
So we have to use the `.` to tell the pipe to send the data to the second argument of `t.test()`, not the first.
### Paired *t*-tests {#ttest_paired}
\index{t-test@\textbf{t-test}!paired}
Consider that we want to compare the difference in life expectancy in Asian countries between 2002 and 2007.
The overall difference is not impressive in the boxplot.
We can plot differences at the country level directly.
```{r chap06-fig-line-life-asia, fig.height=3, fig.width=3, fig.cap="Line plot: Change in life expectancy in Asian countries from 2002 to 2007."}
paired_data <- gapdata %>% # save as object paired_data
filter(year %in% c(2002, 2007)) %>% # 2002 and 2007 only
filter(continent == "Asia") # Asia only
paired_data %>%
ggplot(aes(x = year, y = lifeExp,
group = country)) + # for individual country lines
geom_line()
```
\index{plotting@\textbf{plotting}!geom\_line}
What is the difference in life expectancy for each individual country?
We don't usually have to produce this directly, but here is one method.
```{r fig.height=3, fig.width=3}
paired_table <- paired_data %>% # save object paired_data
select(country, year, lifeExp) %>% # select vars interest
pivot_wider(names_from = year, # put years in columns
values_from = lifeExp) %>%
mutate(
dlifeExp = `2007` - `2002` # difference in means
)
paired_table
# Mean of difference in years
paired_table %>% summarise( mean(dlifeExp) )
```
On average, therefore, there is an increase in life expectancy of 1.5 years in Asian countries between 2002 and 2007.
Let's test whether this number differs from zero with a paired *t*-test:
```{r}
paired_data %>%
t.test(lifeExp ~ year, data = ., paired = TRUE)
```
\index{functions@\textbf{functions}!t.test}
The results show a highly significant difference (*p*-value = `r (paired_data %>% t.test(lifeExp ~ year, data = ., paired = TRUE))$p.value %>% round_tidy(15)`).
The average difference of 1.5 years is highly consistent between countries, as shown on the line plot, and this differs from zero.
It is up to you the investigator to interpret the relevance of the effect size of 1.5 years in reporting the finding.
A highly significant *p*-value does not necessarily mean there is a (clinically) significant change between the two groups (or in this example, two time points).
### What if I run the wrong test?
As an exercise, we can repeat this analysis comparing these data in an unpaired manner.
The resulting (unpaired) *p*-value is `r (paired_data %>% t.test(lifeExp ~ year, data = .))$p.value %>% round_tidy(3)`.
Remember, a paired *t*-test of the same data (life expectancies of Asian countries in 2002 and 2007) showed a very different, significant result.
In this case, running an unpaired two-sample *t*-test is just wrong - as the data are indeed paired.
It is important that the investigator really understands the data and the underlying processes/relationships within it.
R will not know and therefore cannot warn you if you run the wrong test.
## Compare the mean of one group: one sample *t*-tests
\index{t-test@\textbf{t-test}!one-sample}
We can use a *t*-test to determine whether the mean of a distribution is different to a specific value.
For instance, we can test whether the mean life expectancy in each continent was significantly different from 77 years in 2007.
We have included some extra code here to demonstrate how to run multiple tests in one pipe function.
```{r}
gapdata %>%
filter(year == 2007) %>% # 2007 only
group_by(continent) %>% # split by continent
do( # dplyr function
t.test(.$lifeExp, mu = 77) %>% # compare mean to 77 years
tidy() # tidy into tibble
)
```
The mean life expectancy for Europe and Oceania do not significantly differ from 77, while the others do.
In particular, look at the confidence intervals of the results above (`conf.low` and `conf.high` columns) and whether they include or exclude 77.
For instance, Oceania's confidence intervals are especially wide as the dataset only includes two countries.
Therefore, we can't conclude that its value isn't different to 77, but that we don't have enough observations and the estimate is uncertain.
It doesn't make sense to report the results of a statistical test - whether the *p*-value is significant or not - without assessing the confidence intervals.
### Interchangeability of *t*-tests
Furthermore, remember how we calculated the table of differences in the paired *t*-test section?
We can use these differences for each pair of observations (country's life expectancy in 2002 and 2007) to run a simple one-sample *t*-test instead:
```{r}
# note that we're using dlifeExp
# so the differences we calculated above
t.test(paired_table$dlifeExp, mu = 0)
```
Notice how this result is identical to the paired *t*-test.
## Compare the means of more than two groups
It may be that our question is set around a hypothesis involving more than two groups.
For example, we may be interested in comparing life expectancy across 3 continents such as the Americas, Europe and Asia.
### Plot the data
```{r, fig.width=3, fig.height=3, fig.cap="Boxplot: Life expectancy in selected continents for 2007."}
gapdata %>%
filter(year == 2007) %>%
filter(continent %in%
c("Americas", "Europe", "Asia")) %>%
ggplot(aes(x = continent, y=lifeExp)) +
geom_boxplot()
```
### ANOVA
\index{analysis of variance (ANOVA)}
Analysis of variance is a collection of statistical tests which can be used to test the difference in means between two or more groups.
In base R form, it produces an ANOVA table which includes an F-test.
This so-called omnibus test tells you whether there are any differences in the comparison of means of the included groups.
Again, it is important to plot carefully and be clear what question you are asking.
```{r}
aov_data <- gapdata %>%
filter(year == 2007) %>%
filter(continent %in% c("Americas", "Europe", "Asia"))
fit = aov(lifeExp ~ continent, data = aov_data)
summary(fit)
```
\index{functions@\textbf{functions}!aov}
We can conclude from the significant F-test that the mean life expectancy across the three continents is not the same.
This does not mean that all included groups are significantly different from each other.
As above, the output can be neatened up using the `tidy` function.
```{r}
library(broom)
gapdata %>%
filter(year == 2007) %>%
filter(continent %in% c("Americas", "Europe", "Asia")) %>%
aov(lifeExp~continent, data = .) %>%
tidy()
```
### Assumptions
As with the normality assumption of the *t*-test (for example, Sections \@ref(chap06-h3-hist-plot) and \@ref(chap06-h3-qq-plot)), there are assumptions of the ANOVA model.
These assumptions are shared with linear regression and are covered in the next chapter, as linear regression lends itself to illustrate and explain these concepts well.
Suffice to say that diagnostic plots can be produced to check that the assumptions are fulfilled.
`library(ggfortify)` includes a function called `autoplot()` that can be used to quickly create diagnostic plots, including the Q-Q plot that we showed before:
```{r fig.height=5, fig.width=5, fig.cap="Diagnostic plots: ANOVA model of life expectancy by continent for 2007."}
library(ggfortify)
autoplot(fit)
```
\FloatBarrier
## Multiple testing
\index{multiple testing}
### Pairwise testing and multiple comparisons
\index{pairwise testing}
When the F-test is significant, we will often want to determine where the differences lie.
This should of course be obvious from the boxplot you have made.
However, some are fixated on the *p*-value!
```{r}
pairwise.t.test(aov_data$lifeExp, aov_data$continent,
p.adjust.method = "bonferroni")
```
\index{functions@\textbf{functions}!pairwise.t.test}
A matrix of pairwise *p*-values can be produced using the code above.
Here we can see that there is good evidence of a difference in means between Europe and Asia.
We have to keep in mind that the *p*-value's significance level of 0.05 means we have a 5% chance of finding a difference in our samples which doesn't exist in the overall population.
Therefore, the more statistical tests performed, the greater the chances of a false positive result.
This is also known as type I error - finding a difference when no difference exists.
There are three approaches to dealing with situations where multiple statistical tests are performed.
The first is not to perform any correction at all.
Some advocate that the best approach is simply to present the results of all the tests that were performed, and let sceptical readers make adjustments for themselves.
This is attractive, but presupposes a sophisticated readership who will take the time to consider the results in their entirety.
The second and classical approach is to control for the so-called family-wise error rate.
The "Bonferroni" correction is the most famous and most conservative, where the threshold for significance is lowered in proportion to the number of comparisons made.
For example, if three comparisons are made, the threshold for significance should be lowered to 0.017.
Equivalently, all *p*-values should be multiplied by the number of tests performed (in this case 3).
The adjusted values can then be compared to a threshold of 0.05, as is the case above.
The Bonferroni method is particularly conservative, meaning that type II errors may occur (failure to identify true differences, or false negatives) in favour or minimising type I errors (false positives).
\index{Bonferroni correction}
The third approach controls for something called false-discovery rate.
The development of these methods has been driven in part by the needs of areas of science where many different statistical tests are performed at the same time, for instance, examining the influence of 1000 genes simultaneously.
In these hypothesis-generating settings, a higher tolerance to type I errors may be preferable to missing potential findings through type II errors.
\index{false discovery rate}
You can see in our example, that the *p*-values are lower with the `fdr` correction than the `Bonferroni` correction ones.
```{r}
pairwise.t.test(aov_data$lifeExp, aov_data$continent,
p.adjust.method = "fdr")
```
\index{functions@\textbf{functions}!pairwise.t.test}
Try not to get too hung up on this.
Be sensible.
Plot the data and look for differences.
Focus on effect size.
For instance, what is the actual difference in life expectancy in years, rather than the *p*-value of a comparison test.
Choose a method which fits with your overall aims.
If you are generating hypotheses which you will proceed to test with other methods, the `fdr` approach may be preferable.
If you are trying to capture robust effects and want to minimise type II errors, use a family-wise approach.
If your head is spinning at this point, don't worry.
The rest of the book will continuously revisit these and other similar concepts, e.g., "know your data", "be sensible, look at the effect size", using several different examples and datasets.
So do not feel like you should be able to understand everything immediately.
Furthermore, these things are easier to conceptualise when using your own dataset - especially if that's something you've put your blood, sweat and tears into collecting.
## Non-parametric tests{#chap06-non-param-tests}
\index{non-parametric tests@\textbf{non-parametric tests}}
What if your data is a different shape to normal, or the ANOVA assumptions are not fulfilled (see linear regression chapter)?
As always, be sensible and think what drives your measurements in the first place.
Would your data be expected to be normally distributed given the data-generating process?
For instance, if you are examining length of hospital stay it is likely that your data are highly right skewed - most patients are discharged from hospital in a few days while a smaller number stay for a long time.
Is a comparison of means ever going to be the correct approach here?
Perhaps you should consider a time-to-event analysis for instance (see Chapter \@ref(chap10-h1)).
If a comparison of means approach is reasonable, but the normality assumption is not fulfilled there are two approaches,
1. Transform the data;
2. Perform non-parametric tests.
### Transforming data {#chap06-transform}
\index{transformations}
Remember, the Welch *t*-test is reasonably robust to divergence from the normality assumption, so small deviations can be safely ignored.
Otherwise, the data can be transformed to another scale to deal with a skew.
A natural `log` scale is common.
```{r echo=FALSE, message=FALSE}
library(kableExtra)
tibble(
Distribution = c("Moderate right skew (+)", "Substantial right skew (++)", "Substantial right skew (+++)"),
Transformation = c("Square-root", "Natural log*", "Base-10 log*"),
Function = c('sqrt()', 'log()', 'log10()')
) %>%
# mutate(
# Function = kableExtra::cell_spec(Function, monospace = TRUE)) %>% # Not working
knitr::kable(booktabs = TRUE,
caption = "Transformations that can be applied to skewed data. For left skewed data, subtract all values from a constant greater than the maximum value.") %>%
footnote(general = "If data contain zero values, add a small constant to all values.") %>%
kable_styling(latex_options = c("hold_position"))
```
```{r fig.height=3, fig.width=6, fig.cap="Histogram: Log transformation of life expectancy for countries in Africa 2002."}
africa2002 <- gapdata %>% # save as africa2002
filter(year == 2002) %>% # only 2002
filter(continent == "Africa") %>% # only Africa
select(country, lifeExp) %>% # only these variables
mutate(
lifeExp_log = log(lifeExp) # log life expectancy
)
head(africa2002) # inspect
africa2002 %>%
# pivot lifeExp and lifeExp_log values to same column (for easy plotting):
pivot_longer(contains("lifeExp")) %>%
ggplot(aes(x = value)) +
geom_histogram(bins = 15) + # make histogram
facet_wrap(~name, scales = "free") # facet with axes free to vary
```
This has worked well here.
The right skew on the Africa data has been dealt with by the transformation.
A parametric test such as a *t*-test can now be performed.
### Non-parametric test for comparing two groups
\index{non-parametric tests@\textbf{non-parametric tests}!Mann-Whitney U}
\index{non-parametric tests@\textbf{non-parametric tests}!Wilcoxon rank sum}
The Mann-Whitney U test is also called the Wilcoxon rank-sum test and uses a rank-based method to compare two groups (note the Wilcoxon signed-rank test is for paired data).
Rank-based just means ordering your grouped continuous data from smallest to largest value and assigning a rank (1, 2, 3 ...) to each measurement.
We can use it to test for a difference in life expectancies for African countries between 1982 and 2007.
Let's do a histogram, Q-Q plot and boxplot first.
```{r fig.height=4, fig.width=6, fig.cap="Panels plots: Histogram, Q-Q, boxplot for life expectancy in Africa 1992 v 2007."}
africa_data <- gapdata %>%
filter(year %in% c(1982, 2007)) %>% # only 1982 and 2007
filter(continent %in% c("Africa")) # only Africa
p1 <- africa_data %>% # save plot as p1
ggplot(aes(x = lifeExp)) +
geom_histogram(bins = 15) +
facet_wrap(~year)
p2 <- africa_data %>% # save plot as p2
ggplot(aes(sample = lifeExp)) + # `sample` for Q-Q plot
geom_qq() +
geom_qq_line(colour = "blue") +
facet_wrap(~year)
p3 <- africa_data %>% # save plot as p3
ggplot(aes(x = factor(year), # try without factor(year) to
y = lifeExp)) + # see the difference
geom_boxplot(aes(fill = factor(year))) + # colour boxplot
geom_jitter(alpha = 0.4) + # add data points
theme(legend.position = "none") # remove legend
library(patchwork) # great for combining plots
p1 / p2 | p3
```
\index{plotting@\textbf{plotting}!patchwork}
The data is a little skewed based on the histograms and Q-Q plots.
The difference between 1982 and 2007 is not particularly striking on the boxplot.
```{r}
africa_data %>%
wilcox.test(lifeExp ~ year, data = .)
```
\index{functions@\textbf{functions}!wilcox.test}
### Non-parametric test for comparing more than two groups
\index{non-parametric tests@\textbf{non-parametric tests}!!Kruskal-Wallis}
The non-parametric equivalent to ANOVA, is the Kruskal-Wallis test.
It can be used in base R, or via the **finalfit** package below.
```{r}
library(broom)
gapdata %>%
filter(year == 2007) %>%
filter(continent %in% c("Americas", "Europe", "Asia")) %>%
kruskal.test(lifeExp~continent, data = .) %>%
tidy()
```
\index{functions@\textbf{functions}!kruskal.test}
## Finalfit approach
The **finalfit** package provides an easy to use interface for performing non-parametric hypothesis tests.
Any number of explanatory variables can be tested against a so-called dependent variable.
In this case, this is equivalent to a typical Table 1 in healthcare study.
```{r eval=FALSE}
dependent <- "year"
explanatory <- c("lifeExp", "pop", "gdpPercap")
africa_data %>%
mutate(
year = factor(year)
) %>%
summary_factorlist(dependent, explanatory,
cont = "median", p = TRUE)
```
Note that the *p*-values above have not been corrected for multiple testing.
```{r echo=FALSE}
dependent <- "year"
explanatory <- c("lifeExp", "pop", "gdpPercap")
africa_data %>%
mutate(
year = factor(year) # change year to factor
) %>%
summary_factorlist(dependent, explanatory,
cont = "median", p = TRUE) %>%
knitr::kable(row.names = FALSE, booktabs = TRUE,
align = c("l", "l", "r", "r", "r", "r"),
caption = "Life expectancy, population and GDPperCap in Africa 1982 vs 2007.") %>%
kable_styling(latex_options = c("scale_down", "hold_position"))
```
\index{functions@\textbf{functions}!summary\_factorlist}
There are many other options available for this function which are covered throughout this book.
For instance,
If you wish to consider only some variables as non-parametric and summarise with a median, then this can be specified using
```{r eval=FALSE}
dependent <- "year"
explanatory <- c("lifeExp", "pop", "gdpPercap")
africa_data %>%
mutate(
year = factor(year)
) %>%
summary_factorlist(dependent, explanatory,
cont_nonpara = c(1, 3), # variable 1&3 are non-parametric
cont_range = TRUE, # lower and upper quartile
p = TRUE, # include hypothesis test
p_cont_para = "t.test", # use t.test/aov for parametric
add_row_totals = TRUE, # row totals
include_row_missing_col = FALSE, # missing values row totals
add_dependent_label = TRUE) # dependent label
```
```{r echo=FALSE}
dependent <- "year"
explanatory <- c("lifeExp", "pop", "gdpPercap")
africa_data %>%
mutate(
year = factor(year) # change year to factor
) %>%
summary_factorlist(dependent, explanatory,
cont_nonpara = c(1, 3), cont_range = TRUE, p = TRUE,
add_dependent_label = TRUE, add_row_totals = TRUE, include_row_missing_col = FALSE,
p_cont_para = "t.test") %>%
knitr::kable(row.names = FALSE, booktabs = TRUE,
align = c("l", "l", "r", "r", "r", "r"),
caption = "Life expectancy, population and GDPperCap in Africa 1982 vs 2007.") %>%
kable_styling(latex_options = c("scale_down", "hold_position"))
```
## Conclusions
Continuous data is frequently encountered in a healthcare setting.
Liberal use of plotting is required to really understand the underlying data.
Comparisons can be easily made between two or more groups of data, but always remember what you are actually trying to analyse and don't become fixated on the *p*-value.
In the next chapter, we will explore the comparison of two continuous variables together with multivariable models of datasets.
## Exercises
### Exercise {#chap06-ex1}
Make a histogram, Q-Q plot, and a box-plot for the life expectancy for a continent of your choice, but for all years.
Do the data appear normally distributed?
### Exercise {#chap06-ex2}
1. Select any 2 years in any continent and perform a *t*-test to determine whether mean life expectancy is significantly different.
Remember to plot your data first.
2. Extract only the *p*-value from your `t.test()` output.
### Exercise {#chap06-ex3}
In 2007, in which continents did mean life expectancy differ from 70?
### Exercise {#chap06-ex4}
1. Use ANOVA to determine if the population changed significantly through the 1990s/2000s in individual continents.
## Solutions
Solution to Exercise \@ref(chap06-ex1):
```{r fig.height=3, fig.width=5.5}
## Make a histogram, Q-Q plot, and a box-plot for the life expectancy
## for a continent of your choice, but for all years.
## Do the data appear normally distributed?
asia_data <- gapdata %>%
filter(continent %in% c("Asia"))
p1 <- asia_data %>%
ggplot(aes(x = lifeExp)) +
geom_histogram(bins = 15)
p2 <- asia_data %>%
ggplot(aes(sample = lifeExp)) + # sample = for Q-Q plot
geom_qq() +
geom_qq_line(colour = "blue")
p3 <- asia_data %>%
ggplot(aes(x = year, y = lifeExp)) +
geom_boxplot(aes(fill = factor(year))) + # optional: year as factor
geom_jitter(alpha = 0.4) +
theme(legend.position = "none")
library(patchwork)
p1 / p2 | p3
```
Solution to Exercise \@ref(chap06-ex2):
```{r fig.height=3, fig.width=4.4}
## Select any 2 years in any continent and perform a *t*-test to
## determine whether mean life expectancy is significantly different.
## Remember to plot your data first.
asia_2years <- asia_data %>%
filter(year %in% c(1952, 1972))
p1 <- asia_2years %>%
ggplot(aes(x = lifeExp)) +
geom_histogram(bins = 15) +
facet_wrap(~year)
p2 <- asia_2years %>%
ggplot(aes(sample = lifeExp)) +
geom_qq() +
geom_qq_line(colour = "blue") +
facet_wrap(~year)
p3 <- asia_2years %>%
ggplot(aes(x = factor(year), y = lifeExp)) +
geom_boxplot(aes(fill = factor(year))) +
geom_jitter(alpha = 0.4) +
theme(legend.position = "none")
library(patchwork)
p1 / p2 | p3
asia_2years %>%
t.test(lifeExp ~ year, data = .)
```
Solution to Exercise \@ref(chap06-ex3):
```{r}
## In 2007, in which continents did mean life expectancy differ from 70
gapdata %>%
filter(year == 2007) %>%
group_by(continent) %>%
do(
t.test(.$lifeExp, mu = 70) %>%
tidy()
)
```
Solution to Exercise \@ref(chap06-ex4):
```{r}
## Use Kruskal-Wallis to determine if the mean population changed
## significantly through the 1990s/2000s in individual continents.
gapdata %>%
filter(year >= 1990) %>%
ggplot(aes(x = factor(year), y = pop)) +
geom_boxplot() +
facet_wrap(~continent)
gapdata %>%
filter(year >= 1990) %>%
group_by(continent) %>%
do(
kruskal.test(pop ~ year, data = .) %>%
tidy()
)
```