forked from PeterKDunn/SRM-Textbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
33-Testing-OddsRatios.Rmd
1599 lines (1200 loc) · 65.7 KB
/
33-Testing-OddsRatios.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
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
# Tests for comparing odds {#TestsOddsRatio}
<!-- Introductions; easier to separate by format -->
```{r, child = if (knitr::is_html_output()) {'./introductions/33-Testing-OddsRatios-HTML.Rmd'} else {'./introductions/33-Testing-OddsRatios-LaTeX.Rmd'}}
```
## Introduction: meals on-campus {#MealsOnCampus}
<div style="float:right; width: 222x; border: 1px; padding:10px">
<img src="Illustrations/pexels-startup-stock-photos-7096.jpg" width="200px"/>
</div>
In Sect. \@ref(OddsRatioIntro), a study was introduced that examined the eating habits of university students [@data:Mann12017:UniStudents].
Researchers classified $n = 183$ students into groups according to two qualitative variables (Table \@ref(tab:MealsDataTableHT)): Where they lived, and where they ate most of their meals.
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
Every cell in the $2\times 2$ table contain different students, so the comparison is *between* individuals.
:::
```{r MealsDataTableHT}
Counts <- c(52, 105, 2, 24)
Live <- rep( c(1, 2), 2)
Live <- ordered(Live,
levels = 1:2,
labels = c("Lives with parents",
"Doesn't live with parents") )
Meals <- c( rep(1, 2),
rep(2, 2))
Meals <- ordered(Meals,
levels = 1:2,
labels = c("Most meals off-campus",
"Most meals on-campus"))
Eating <- data.frame( Counts = Counts,
Live = Live,
Meals = Meals)
Eating.tab <- Eating.tab.Counts <- xtabs(Counts ~ Meals + Live + Meals,
data = Eating)
Eating.tab <- cbind( Eating.tab,
"Total" = rowSums(Eating.tab))
Eating.tab <- rbind( Eating.tab,
"Total" = colSums(Eating.tab))
if( knitr::is_latex_output() ) {
kable(Eating.tab,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
align = "r",
caption = "Where university students live and eat"
) %>%
column_spec(4, bold = TRUE) %>%
row_spec(0, bold = TRUE) %>%
row_spec(3, bold = TRUE) %>%
kable_styling(font_size = 10) %>%
row_spec(2, hline_after = TRUE)
}
if( knitr::is_html_output() ) {
out <- kable(Eating.tab,
format = "html",
booktabs = TRUE,
longtable = FALSE,
align ="r",
caption = "Where university students live and eat"
) %>%
column_spec(4, bold = TRUE) %>%
row_spec(3, bold = TRUE)
out
}
```
Since both qualitative variables have two levels, the table is a $2\times 2$ table.
A **graphical summary** is shown in Fig. \@ref(fig:EatingGraphs), and a **numerical summary** in Table \@ref(tab:EatingNumericalSummaryHT).
(The details of the computations appear in Sect. \@ref(OddsRatioIntro)).
```{r}
UniS <- matrix( ncol = 2,
data = c(52, 2, 105, 24),
byrow = TRUE)
rownames(UniS) <- c("Lives\nwith parents",
"Doesn't live\nwith parents")
colnames(UniS) <- c("Most meals off-campus",
"Most meals on-campus")
```
```{r EatingNumericalSummaryHT}
EatingNumericalSummary <- array( dim = c(3, 3))
EatingNumericalSummary[1, ] <- c(format( round(UniS[1,1]/UniS[1,2], 4), nsmall = 3),
round(UniS[1,1]/sum(UniS[1,]) * 100, 1),
sum(UniS[1,]) )
EatingNumericalSummary[2, ] <- c(round(UniS[2,1]/UniS[2,2], 4),
round(UniS[2,1]/sum(UniS[2,]) * 100, 1),
sum(UniS[2,]) )
EatingNumericalSummary[3, ] <- c(round( (UniS[1, 1] / UniS[1, 2] ) / (UniS[2, 1] / UniS[2, 2]), 3),
"",
"")
rownames(EatingNumericalSummary) <- c("Living with parents",
"Not living with parents",
"Odds ratio")
if( knitr::is_latex_output() ) {
kable(EatingNumericalSummary,
format = "latex",
longtable = FALSE,
booktabs = TRUE,
align = "c",
col.names = c("most meals off-campus",
"most meals off-campus",
"size"),
caption = "The odds and percentage of university students eating most meals off-campus"
) %>%
row_spec(3, italic = TRUE) %>%
row_spec(0, bold = TRUE) %>%
add_header_above( c(" ", "Odds of having" = 1,
"Percentage having" = 1,
"Sample" = 1),
line = FALSE,
bold = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
kable(EatingNumericalSummary,
format = "html",
longtable = FALSE,
booktabs = TRUE,
align = c("r", "r", "r"),
col.names = c("Odds of having most\n meals off-campus",
"Percentage having most\n meals off-campus",
"Sample size"),
caption = "The odds and percentage of university students eating most meals off-campus"
) %>%
kable_styling(full_width = FALSE)
}
```
The parameter is the population OR, comparing the odds of eating most meals *off*-campus, for students living with their parents, to students *not* living with their parents.
::: {.softwareBox .software data-latex="{iconmonstr-laptop-4-240.png}"}
Understanding how software computes the odds ratio is important for understanding the output.
In a two-by-two table, jamovi and SPSS output can be interpreted in *either* of these ways (i.e., both are correct):
* The *odds* compare Row 1 counts to Row 2 counts, for both columns.
Then the odds ratio compares the odds for Column 1 to the odds for Column 2.
* The *odds* compare Column 1 counts to Column 2 counts.
Then the odds ratio compares the odds for Row 1 to the odds for Row 2.
Odds and odds ratios are computed with the **last row** and **last column** values on the *bottom* of the fraction.
:::
:::{.example name="Odds and odds ratio in software"}
For the data in Table \@ref(tab:MealsDataTableHT), the software output can be interpreted in *either* of these ways (i.e., both are correct):
* The *odds* are the odds of eating most meals *off-campus* (Row 1) compared to *on-campus* (Row 2; on the bottom of the fraction)
* for students living with their parents (Column 1): $52/2 = 26$;
* for students not living with their parents (Column 2): $105/24 = 4.375$.
So the OR is $26/4.375 = 5.943$ (Column 2 on bottom of the fraction), as in the output (jamovi: Fig. \@ref(fig:UniMealsTestOutputHTjamovi); SPSS: Fig. \@ref(fig:UniMealsTestOutputHTSPSS)).
* The *odds* are the odds of living with parents (Column 1) compared to not living with parents (Column 2; on the bottom of the fraction):
* for those eating most meals off-campus: $52/105 = 0.49524$;
* for those eating most meals on-campus: and $2/24 = 0.083333$.
So the OR is $0.49524/0.083333 = 5.943$ (Row2 on bottom of the fraction), as in the output (jamovi: Fig. \@ref(fig:UniMealsTestOutputHTjamovi); SPSS: Fig. \@ref(fig:UniMealsTestOutputHTSPSS)).
In other words, the odds and odds ratios use the last row or last column on the bottom of the fraction.
:::
The RQ can be written in terms of comparing proportions, odds, or odds ratios.
Importantly, means are not appropriate (the data contain two *qualitative* variables.)
Usually the odds ratio (OR) is used as the parameter; one reason is that software produces output related to testing the OR.
Using the OR, the RQ could be written as
> Is the *population odds ratio* of eating most meals off-campus, comparing students who live *with their* parents to students *not living with* their parents, equal to one?
Alternatively, but probably easier to understand, is to write the RQ in terms of comparing the odds in the two groups explicitly:
> Are the *population odds* of students eating most meals off-campus the same for students *living with* their parents and for students *not living with* their parents?
The RQ can also be worded as comparing the percentage (or proportion) of students eating meals off-campus in each group.
This is equivalent to the RQs above, but is not directly related to the software output (which works with odds ratios).
Another alternative, which sounds less direct but is useful for two-way tables larger than $2\times 2$ (see Sect. \@ref(ORTestDumping)), is worded in terms of *relationships* or *associations* between the variables:
> Is there a relationship (or association) between where students eat most of their meals and whether or not the student lives with their parents?
All of these are equivalent.
Usually, for $2 \times2$ tables, working with *odds* or *odds ratios* is best, because most software (including jamovi and SPSS) readily produce CIs for the odds ratio.
## Statistical hypotheses and notation
For two-way tables of counts, the *parameter* is the population odds ratio.
As usual, the null hypothesis is the 'no difference, no change, no relationship' position. So, in this context:
* $H_0$: The *population* OR is one; or (equivalently): The *population* odds are the same in each group.
This hypothesis proposes that the *sample* odds are not the same due to sampling variation.
This is the initial *assumption*.
The alternative hypothesis is
* $H_1$: The *population* OR is not one; or (equivalently): The *population* odds are *not* the same in each group.
The alternative hypothesis is *always* two-tailed for analysing two-way tables of counts.
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
For analysing two-way tables of counts, the alternative hypotheses *are always two-tailed*.
:::
The hypotheses can also be written in terms of differences in percentages (or proportions), though the software output is usually expressed in terms of odds.
The hypotheses can also be written in terms of associations:
* $H_0$: In the *population*, there is *no association* between the two variables
* $H_1$: In the *population*, there is *an association* between the two variables
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
The RQ and hypotheses only need to be given in *one* of these ways.
The RQ and hypotheses should be consistent; for example, if the RQ is written in terms of odds, the hypotheses should be written in terms of odds.
:::
As usual, the [decision-making process](#DecisionMaking) starts by *assuming* that the null hypothesis is true: that the *population* odds ratio is one.
## Finding expected values {#ExpectedValues}
Assuming that the odds of having most meals off-campus is the same for both groups (that is, the population OR is one), how would the sample OR be *expected* to vary from sample to sample just because of *sampling variation*?
If the null hypothesis is true, the odds are the same in both groups (and the percentages are the same in both groups).
That is, the percentage of students eating most meals off-campus is the same for students *living with* and *not living with* their parents.
Let's consider the implication.
From Table \@ref(tab:MealsDataTableHT), 157 students out of 183 ate most meals off-campus, so that
\[
\frac{157}{183} \times 100 = 85.79\%
\]
of the students in the entire sample ate most of their meals off-campus.
If the percentage of students who eat most of their meals off-campus is the *same* for those who live with their parents and those who don't, then we'd **expect** 85.79% of students in *both* groups to be eating most meals off-campus.
That is, we would *expect*:
* 85.79% of the 54 students who *live with their parents* (i.e., 46.33) to eat most meals off-campus; and
* 85.79% of the 129 students who *don't live with their parents* (i.e., 110.67) to eat most meals off-campus.
In other words, the percentage (and hence the odds) is the same in each group.
Those are the *expected* numbers if the percentage was exactly the same in each group (Table \@ref(tab:MealsDataTableHTExpected)), if the null hypothesis (the assumption) was true.
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
Consider the expected counts in Table \@ref(tab:MealsDataTableHTExpected).
Confirm that the *odds* of having most meals off-campus is the same for students living with their parents, and for students not living with their parents.\label{thinkBox:ExpectedOddsSame}
`r if (knitr::is_latex_output()) '<!--'`
`r webexercises::hide()`
* Living with parents: 46.333/7.667 = 6.043$.
* Not living with parents: 110.667/18.333 = 6.036$.
The odds are the same (the small difference is because the expected counts are only given to three decimal places).
`r webexercises::unhide()`
`r if (knitr::is_latex_output()) '-->'`
:::
How do those *expected values* (Table \@ref(tab:MealsDataTableHTExpected)) compare to what was *observed* (Table \@ref(tab:MealsDataTableHT))?
* 46.333 of the 54 students who *live with their parents* are *expected* to eat most meals off-campus; yet we observed 52.
* 110.667 of the 129 students who *don't live with their parents* are *expected* to eat most meals off-campus; yet we observed 105.
The observed and expected counts are similar, but not the exactly same.
The difference between the observed and expected counts *may* be explained by sampling variation (that is, the null hypothesis explanation).
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
You **do not** have to compute the expected values when you answer one of these types of RQs (software does it in the background).
However, seeing how the decision-making process works in this context is helpful.
:::
In previous hypothesis tests, the *sampling distribution* of the sample statistic was described, as having an approximate normal distribution (whose standard deviation is called the *standard error*).
However, the sampling distribution of the odds ratio is more complicated^[For those interested: The *logarithm* of the sample ORs have an approximate normal distribution, and a *standard error*.] so will not be presented.
```{r MealsDataTableHTExpected}
Eating.tab.ExpCounts <- chisq.test(Eating.tab[1:2, 1:2])$expected
Eating.tab.ExpCounts <- cbind( Eating.tab.ExpCounts,
"Total" = round( rowSums(Eating.tab.ExpCounts)) )
Eating.tab.ExpCounts <- rbind( Eating.tab.ExpCounts,
"Total" = round( colSums(Eating.tab.ExpCounts)) )
if( knitr::is_latex_output() ) {
kable(Eating.tab.ExpCounts,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
digits = 3,
align = "r",
caption = "Where university students live and eat: Expected counts"
) %>%
column_spec(4, bold = TRUE) %>%
row_spec(3, bold = TRUE) %>%
row_spec(0, bold = TRUE) %>%
row_spec(2, hline_after = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
out <- kable(Eating.tab.ExpCounts,
format = "html",
booktabs = TRUE,
longtable = FALSE,
digits = 3,
align = "r",
caption = "Where university students live and eat: Expected counts"
) %>%
column_spec(4, bold = TRUE) %>%
row_spec(3, bold = TRUE)
out
}
```
## Computing the test statistic: comparing odds {#TestStatObs}
The [decision-making process](#DecisionMaking) compares what is *expected* if the null hypothesis about the parameter is true (Table \@ref(tab:MealsDataTableHTExpected)) to what is **observed** in the sample (Table \@ref(tab:MealsDataTableHT)).
Previously, when the summary statistics were means, $t$-tests were used as the test statistic.
However, the data here are not summarised by means, and a different test statistic (related to a normal distribution) is needed.
Here, the test-statistic is a 'chi-squared' statistic, written $\chi^2$.
A $\chi^2$ statistic measures the overall size of the differences between the expected counts and observed counts, over the entire table.
:::: {.pronounceBox .pronounce data-latex="{iconmonstr-microphone-7-240.png}"}
::: {style="display: flex;"}
The Greek letter $\chi$ is pronounced 'ki', as in **ki**te (**not** "chi" as in **Chi**na).
The test statistic $\chi^2$ is pronounced as 'chi-squared'.
:::
::: {}
```{r}
htmltools::tags$video(src = "./Movies/chi.mp4",
width = "121",
loop = "FALSE",
controls = "controls",
loop = "loop",
style = "padding:5px; border: 2px solid gray;")
```
:::
::::
From the software (jamovi: Fig. \@ref(fig:UniMealsTestOutputHTjamovi); SPSS: Fig. \@ref(fig:UniMealsTestOutputHTSPSS)), $\chi^2 = 6.934$.
In a $2\times 2$ table of counts (when the 'degrees of freedom', or `df`, is equal to 1, as in the computer output), the *square root* of the $\chi^2$ value is approximately equivalent to a $z$-score.
So here, the equivalent $z$-score is about $\sqrt{6.934} = 2.63$, which is fairly large for a $z$-score: a small $P$-value is expected.
More generally, for two-way tables of any size, $\sqrt{\chi^2 \div \text{df}}$ is like a $z$-score, where df is the 'degrees of freedom' (related to the size of the table^[For those interested: the degrees of freedom in a two-way table is the number of rows of data less one, times the number of columns of data less one. So, for a $2\times 2$ table, $\text{df} = (2 - 1) \times (2 - 1) = 1$.]), as shown in the software output.
This allows a $P$-value to be estimated using the 68--95--99.7 rule from the value of the $\chi^2$ statistic.
```{r UniMealsTestOutputHTjamovi, fig.show="hold", fig.cap="The jamovi output for computing a CI and conducting a test", fig.align="center", out.width="50%"}
knitr::include_graphics( "jamovi/UniStudents/UniStudents-Chisq-All.png")
```
```{r UniMealsTestOutputHTSPSS, fig.show="hold", fig.cap="The SPSS output for computing a CI and conducting a test", fig.align="center", out.width="75%"}
knitr::include_graphics( "SPSS/UniStudents/UniStudents-Chisq-CI.png")
```
::: {.tipBox .tip data-latex="{iconmonstr-info-6-240.png}"}
In a chi-squared test, with a given number of 'degrees of freedom' (`df` in the software output), the value of
\[
\sqrt{ \chi^2 \div {\text{df}}}
\]
is like a $z$-score.
This allows the $P$-value to be estimated using the [68--95--99.7 rule](#def:EmpiricalRule).
:::
## Determining $P$-values
The differences between the observed sample statistic (the sample OR) and the hypothesised population parameter (the population OR of one) is summarised by $\chi^2 = 6.934$, approximately equivalent to $z = 2.63$.
Using the [68--95--99.7 rule](#def:EmpiricalRule), a small $P$-value is expected.
The two-tailed $P$-value reported by jamovi (Fig. \@ref(fig:UniMealsTestOutputHTjamovi), under the `p` column) and SPSS (Fig. \@ref(fig:UniMealsTestOutputHTSPSS), in the `Asymptotic Significance (2-sided)` column and `Pearson Chi-Square` row) is very small: $0.008$ to three decimals.
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
Recall that, for two-way tables of counts, the alternative hypotheses *are always two-tailed*, so a two-tailed $P$-value is always reported.
:::
<iframe src="https://learningapps.org/watch?v=ptw49fp0322" style="border:0px;width:100%;height:600px" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>
`r if (knitr::is_latex_output()) '<!--'`
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
`r if (knitr::is_html_output()){
'Click on the hotspots in the following image, and describe what the jamovi output tells us.'
}`
<iframe src="https://learningapps.org/watch?v=p54msvghc22" style="border:0px;width:100%;height:800px" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>
:::
`r if (knitr::is_latex_output()) '-->'`
## Writing conclusions
As usual, a very small $P$-value ($0.008$ to three decimals) means [very strong evidence](#tab:PvaluesInterpretation) exists to supporting $H_1$: the evidence suggests a difference in the *population* odds in the two groups.
We write:
> The *sample* provides strong evidence ($\chi^2 = 6.934$; two-tailed $P = 0.008$) that the odds in the *population* of having most meals off-campus is different for students living with their parents (odds: 26) and students *not* living with their parents (odds: 4.375; OR: $5.94$; 95% CI from $1.35$ to $26.1$).
Again, as seen in Sect. \@ref(WordingConclusion), the conclusion includes three components:
(a) The *answer to the RQ*; (b) the *evidence* used to reach that conclusion ('$\chi^2 = 6.934$; two-tailed $P = 0.008$'); and (c) some *sample summary statistics* (including the 95% CI for the odds ratio).
The conclusion also makes clear what the odds and the odds ratio *mean*.
The odds are describing as the 'odds... of having most meals off-campus', and the OR as then comparing these odds between 'students living with their parents... and students *not* living with their parents'.
::: {.importantBox .important data-latex="{iconmonstr-warning-8-240.png}"}
For two-way tables, RQs are best framed in terms of ORs or odds (but can be framed in terms of proportions or percentages, or associations or relationships).
\smallskip
For consistency: if the RQ is about the odds ratio, the hypotheses and conclusion should be about the odds ratio; if the RQ is about odds, the hypotheses and conclusion should be about the odds; and so on.
:::
<!-- ## Standardised residuals -->
<!-- The $\chi^2$ value, and hence the $P$-value, tells us -->
<!-- *if* there is evidence that a difference exists. -->
<!-- It does not tell us *where* the difference lies, or *what* the difference is. -->
<!-- (That is, it doesn't tell us if students who live with their parents -->
<!-- are more likely to eat meals *on-* or *off-*campus.) -->
<!-- In $2\times2$ tables, -->
<!-- this is rarely hard to determine, -->
<!-- but in other size two-way table (such as a $4\times 3$ table, for example) it can be more challenging. -->
<!-- To help determine where the difference are located, -->
<!-- we can ask SPSS^[Using `Analyze> Descriptive Statistics> Crosstabs...`, and then in the `Cells` tab select `Residuals> Standardized`.] to produce -->
<!-- *standardized residuals* -->
<!-- (Table \@ref(fig:UniMealsTestSPSSStdRes)). -->
<!-- ```{r UniMealsTestSPSSStdRes, echo=FALSE, fig.cap="The standardized residuals from SPSS for the two-way table for the uni-students eating data", fig.align="center", out.width="60%"} -->
<!-- knitr::include_graphics("SPSS/UniStudents/UniStudentsStdRes.png") -->
<!-- ``` -->
<!-- Standardised residuals are like $z$-scores, -->
<!-- so that cells in the table with a standardized residual larger than about $2$ -->
<!-- mean that the observed counts were *higher* than we would have expected, -->
<!-- and -->
<!-- that cells in the table with a standardized residual smaller than about $-2$ -->
<!-- mean that the observed counts were *smaller* than we would have expected. -->
<!-- So for the uni-student data -->
<!-- (Table \@ref(fig:UniMealsTestSPSSStdRes)), -->
<!-- we can find the largest and smallest standardized residuals: -->
<!-- * $-2.0$: Students *living with their parents* are *less likely* (because the residual is *negative*) to eat most meals on-campus -->
<!-- (compared to what we'd expect by chance). -->
<!-- * $1.3$: Students *not living with their parents* are *more likely* (because the residual is *positive*) to eat mostmeals on-campus -->
<!-- (compared to what we'd expect by chance); -->
<!-- So while the $\chi^2$-square suggests there is a difference, -->
<!-- the standardised residuals tells us *how* they are different: -->
<!-- students living *with* their parents are -->
<!-- *less* likely to eat most meals on-campus. -->
<!-- Again, -->
<!-- standardized residuals may not be needed here to reach these conclusions, -->
<!-- but they can be used in larger two-way tables -->
<!-- (for example, -->
<!-- see Sect. \@ref(ORTestDumping)). -->
## Statistical validity conditions {#Validity-Test-ChiSq}
As usual, these results hold [under certain conditions](#exm:StatisticalValidityAnalogy).
The test above is statistically valid if:
* All *expected* counts are at least five.
Some books may give other (but similar) conditions.
The statistical validity condition refers to the *expected* (not the *observed*) counts.
SPSS tells us if this condition is not satisfied, underneath the *first* output table in Fig. \@ref(fig:UniMealsTestOutputHTSPSS).
In jamovi, the *expected* counts must be explicitly requested to see if this condition is satisfied (Fig. \@ref(fig:UniMealsTestExpectedjamovi)).
```{r UniMealsTestExpectedjamovi, fig.cap="The expected values, as computed in jamovi", fig.align="center", out.width="70%"}
knitr::include_graphics("jamovi/UniStudents/UniStudents-Expected.png")
```
For the student-eating data, the smallest *observed* count is 2 (living with parents; most meals off-campus), but the smallest *expected* count is 7.67, which is greater than five.
The size of the *expected* counts is important for the statistical validity condition.
::: {.example #StatisticalValidityEatingHT name="Statistical validity"}
For the university-student eating data, *all* the cells have an expected count of at least five so the statistical validity condition is satisfied.
:::
```{r}
PB <- structure(list(LC = structure(c(1L, 1L, 2L, 2L), .Label = c("Adults with lung cancer",
"Adults without lung cancer"), class = "factor"), Pets = structure(c(1L,
2L, 1L, 2L), .Label = c("Kept pet birds", "Did not keep pet birds"
), class = "factor"), Counts = c(98, 141, 101, 328)), .Names = c("LC",
"Pets", "Counts"), row.names = c(NA, -4L), class = "data.frame", variable.labels = structure(character(0), .Names = character(0)), codepage = 28591L)
PB2 <- xtabs( Counts ~ Pets + LC, data=PB)
PB2.exp <- chisq.test(PB2)$expected
```
## Example: pet birds {#ExampleHTPetBirds}
<div style="float:right; width: 222x; border: 1px; padding:10px">
<img src="Illustrations/pexels-andre-lisatchok-2226006.jpg" width="200px"/>
</div>
A study examined people with lung cancer, and a matched set of similar controls who did not have lung cancer, and compared the proportion in each group that had pet birds [@data:Kohlmeier1992:BirdsCancer].
These data were studied in Sect. \@ref(PetBirdsOR); the data are shown again in Table \@ref(tab:BirdsData2), and the numerical summary in Table \@ref(tab:BirdsDataSummary) (the computations are in Sect. \@ref(PetBirdsOR)).
```{r BirdsData2}
PB2T <- cbind( PB2,
"Total" = rowSums(PB2))
PB2T <- rbind( PB2T,
"Total" = colSums(PB2T))
if( knitr::is_latex_output() ) {
kable(PB2T,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
caption = "The pet bird data") %>%
column_spec(4, bold = TRUE) %>%
row_spec(3, bold = TRUE) %>%
row_spec(0, bold = TRUE) %>%
row_spec(2, hline_after = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
kable(PB2T,
format = "html",
booktabs = TRUE,
longtable = FALSE,
caption = "The pet bird data") %>%
column_spec(4, bold = TRUE)
}
```
Consider this RQ:
> Are the **odds** of having a pet bird the same for people *with* lung cancer (cases) and for people *without* lung cancer (controls)?
The parameter is the population OR, comparing the odds of keeping a pet bird, for adults with lung cancer to adults who do not have lung cancer.
```{r BirdsDataSummary}
PBsummary <- array( dim = c(3, 3) )
colnames(PBsummary) <- c( "Odds of keeping pet bird",
"Percentage keeping pet bird",
"Sample size")
rownames(PBsummary) <- c("With lung cancer:",
"Without lung cancer:",
"Odds ratio:")
PBsummary[1, ] <- c("0.6950",
"41.0%",
"239")
PBsummary[2, ] <- c("0.3079",
"25.5%",
"429")
PBsummary[3, ] <- c("2.26",
"",
"")
if( knitr::is_latex_output() ) {
kable(PBsummary,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
#align=c("p{28mm}", "p{28mm}", "c"),
caption = "The odds and percentage of subjects keeping pet birds") %>%
row_spec(0, bold = TRUE) %>%
row_spec(3, italic = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
kable(PBsummary,
format = "html",
booktabs = TRUE,
longtable = FALSE,
align = c("l", "r", "c"),
caption = "The odds and percentage of subjects keeping pet birds")
}
```
::: {.tipBox .tip data-latex="{iconmonstr-info-6-240.png}"}
The RQ could also be written in terms of comparing the *percentage* in each groups; in terms of the *odds ratio* being one; or in terms of a *relationship* between the two variabes
:::
From this RQ (written in terms of *odds*), the hypotheses could be written as:
* $H_0$: The *odds* of having a pet bird is *the same* for people *with* lung cancer (cases) and for people *without* lung cancer (controls).
* $H_1$: The *odds* of having a pet bird is *not the same* for people *with* lung cancer (cases) and for people *without* lung cancer (controls).
::: {.tipBox .tip data-latex="{iconmonstr-info-6-240.png}"}
The null hypothesis could also be written as:
* The **percentage** of people having a pet bird is *the same* for people *with* lung cancer (cases) and for people *without* lung cancer (controls).
* The **odds ratio** of people having a pet bird, comparing people *with* lung cancer (cases) and for people *without* lung cancer (controls), is equal to one.
* There is **no relationship** between having a pet bird and having lung cancer.
:::
Begin *assuming* the null hypothesis is true: no difference exists between the odds in the *population*.
Based on this assumption, the *expected* counts can be found (though, in practice, you do not have to compute these).
From the data (Table \@ref(tab:BirdsData2)), overall $199\div 668 = 29.79$% of people own a pet bird.
If there really was no difference in the odds (or the percentages) of owning a pet bird between those with and without lung cancer, about $29.79$% of the people in *both* lung cancer groups would be *expected* to own a pet bird.
About 29.79% of the 239 lung-cancer cases (or 71.20 people) would be expected to have a pet bird, and about 29.79% of the 429 non-lung-cancer cases (or 127.80 people) would be expected to have a pet bird.
A table of these *expected counts* (Table \@ref(tab:PetBirdsExpected)) shows that all are greater than five.
In practice, software compues these expected counts automatically.
```{r PetBirdsExpected}
PBExp <- PB2T
PBExp[1, ] <- c(71.20,
127.80,
199)
PBExp[2, ] <- c(167.80,
301.20,
469)
if( knitr::is_latex_output() ) {
kable(PBExp,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
caption = "The expected counts for the pet bird data, if the proportion owning pet birds was the same for lung cancer cases and non-lung-cancer cases") %>%
column_spec(4, bold = TRUE) %>%
row_spec(3, bold = TRUE) %>%
row_spec(2, hline_after = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
kable(PBExp,
format = "html",
booktabs = TRUE,
longtable = FALSE,
caption = "The expected counts for the pet bird data, if the proportion owning pet birds was the same for lung cancer cases, and non-lung-cancer cases") %>%
column_spec(4, bold = TRUE) %>%
row_spec(3, bold = TRUE)
}
```
The counts in Table \@ref(tab:PetBirdsExpected) are what are *expected*, *if* the percentage of people owning a pet bird is the same for lung cancer and non-lung cancer cases.
How close are the expected and observed counts (Table \@ref(tab:BirdsData2))?
To compare the sample statistic (what we *observed*) with the hypothesised population parameter, software computes the $\chi^2$ value (jamovi: Fig. \@ref(fig:PetBirdsjamovi); SPSS: Fig. \@ref(fig:PetBirdsSPSS)): $\chi^2 = 22.374$, approximately equivalent to a $z$-score of $\sqrt{22.374/1} = 4.730$, which is very large.
Hence, a small $P$-value is expected.
The software shows the $P$-value is very small indeed ($P < 0.001$).
As usual, this means that [very strong evidence](#tab:PvaluesInterpretation) exists to support $H_1$, if $H_0$ is assumed true.
That is, the evidence suggests a *difference* exists between the two odds in the *population*.
We write:
> The *sample* provides very strong evidence ($\chi^2 = 22.374$; two-tailed $P < 0.001$) that the odds in the *population* of having a pet bird is not the same for people with lung cancer (odds: 0.695) and for people without lung cancer (odds: 0.308; OR: $2.26$; 95% CI from $1.6$ to $3.2$).
```{r PetBirdsjamovi, fig.show="hold", fig.cap="jamovi output for the pet-birds data", fig.align="center", out.width="50%"}
knitr::include_graphics("jamovi/PetBirds/Pets-All.png")
```
```{r PetBirdsSPSS, fig.show="hold", fig.cap="SPSS output for the pet-birds data", fig.align="center", out.width="75%"}
knitr::include_graphics("SPSS/PetBirds/Pets-Chisq-OR.png")
```
::: {.thinkBox .think data-latex="{iconmonstr-light-bulb-2-240.png}"}
This doesn't imply that owning a pet bird *causes* lung cancer.
Why not?\label{thinkBox:NotCauseCancer}
`r if (knitr::is_latex_output()) '<!--'`
`r webexercises::hide()`
Because the study *observational*.
Confounders may explain the relationship (can you think of one?).
In addition, maybe having lung cancer means that people seek companionship in the form of a pet.
`r webexercises::unhide()`
`r if (knitr::is_latex_output()) '-->'`
:::
## Example: B12 deficiency {#B12Deficiency}
<div style="float:right; width: 222x; border: 1px; padding:10px">
<img src="Illustrations/pexels-vegan-liftz-2377164.jpg" width="200px"/>
</div>
A study in New Zealand [@data:Gammon2012:B12] asked:
> Among a certain group of women, are the odds of being vitamin B12 deficient different for women on a vegetarian diet compared to women on a non-vegetarian diet?
The population was 'predominantly overweight/obese women of South Asian origin living in Auckland'.
The RQ could be worded in terms of odds ratios or proportions, too.
The statistical hypotheses are:
* $H_0$: $\text{population odds for vegetarians} = \text{population odds for non-vegetarians}$:
The odds of B12 deficiency are the same in both groups.
* $H_1$: $\text{population odds for vegetarians} \ne \text{population odds for non-vegetarians}$:
The odds of B12 deficiency are *not* the same in both groups.
The parameter is the population OR, comparing the odds of being B12 deficient, for vegetarians to non-vegetarians.
```{block2, type="extraInfo"}
Again (see Sect. \@ref(ExampleHTPetBirds)), the RQ and the hypotheses could be written in terms of comparing the *percentages*, in terms of the *odds ratio* being equal to one, or in terms of *relationships* between the variables.
```
Here, the odds refer to the odds of a woman being B12 deficient.
The data are shown in Table \@ref(tab:B12Data), and the numerical summary in Table \@ref(tab:B12DataSummary).
Since the RQ is about odds, a side-by-side bar chart is produced (Fig. \@ref(fig:B12Barcharts)) as the graphical summary.
```{r B12Data}
B12Data <- array( dim = c(3, 3) )
rownames(B12Data) <- c("Vegetarians",
"Non-vegetarians",
"Total")
colnames(B12Data) <- c("B12 deficient",
"Not B12 deficient",
"Total")
B12Data[1, ] <- c(8, 26, 34)
B12Data[2, ] <- c(8, 82, 90)
B12Data[3, ] <- c(16, 108, 124)
if( knitr::is_latex_output() ) {
kable(B12Data,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
align = c("r", "r", "r"),
caption = "The number of vegetarian and non-vegetarian women who are (and are not) B12 deficient") %>%
row_spec(0, bold = TRUE) %>%
row_spec(3, bold = TRUE) %>%
column_spec(4, bold = TRUE) %>%
row_spec(2, hline_after = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
kable(B12Data,
format = "html",
booktabs = TRUE,
longtable = FALSE,
align = c("r","r", "r"),
caption = "The number of vegetarian and non-vegetarian women who are (and are not) B12 deficient") %>%
row_spec(0, bold = TRUE) %>%
row_spec(3, bold = TRUE) %>%
column_spec(4, bold = TRUE)
}
```
```{r B12DataSummary}
B12summary <- array( dim = c(3, 3) )
colnames(B12summary) <- c( "Odds B12 deficient",
"Percentage B12 deficient",
"Sample size")
rownames(B12summary) <- c("Vegetarians:",
"Non-vegetarians:",
"Odds ratio:")
B12summary[1, ] <- c("0.3077",
"23.5%",
"34")
B12summary[2, ] <- c("0.0976",
"8.9%",
"90")
B12summary[3, ] <- c("3.15",
"",
"")
if( knitr::is_latex_output() ) {
kable(B12summary,
format = "latex",
booktabs = TRUE,
longtable = FALSE,
#align=c("p{20mm}", "p{25mm}", "c"),
caption = "The odds and percentage of subjects that are B12 deficient") %>%
row_spec(0, bold = TRUE) %>%
row_spec(3, italic = TRUE) %>%
kable_styling(font_size = 10)
}
if( knitr::is_html_output() ) {
kable(B12summary,
format = "html",
booktabs = TRUE,
longtable = FALSE,
align = c("l", "r", "c"),
caption = "The odds and percentage of subjects that are B12 deficient")
}
```
```{r B12Barcharts, fig.cap="A side-by-side barchart comparing the number of women B12 deficient", fig.align="center", fig.width=4.5, fig.height=3.5}
### B12 example
counts <- matrix( c(8, 26, 8, 82),
byrow = TRUE,
nrow = 2)
rownames(counts) <- c("Veg.",
"Non-veg.")
colnames(counts) <- c("B12 def.",
"Not B12 def.")
mp <- barplot(t(counts),
las = 1,
ylab = "Number of women",
xlab = "Diet",
col = c(BlockColour, ResponseColour),
legend.text = TRUE,
ylim = c(0, 100),
args.legend = list(x = "topleft",
bty = "n"),
main = "Number of women who are\nand who are not B12 deficient",
beside = TRUE)
box()
```
The software output (jamovi: Fig. \@ref(fig:B12jamoviOutputHT); SPSS: Fig. \@ref(fig:B12SPSSOutputHT)) gives the OR (and 95% CI) as $3.154$ ($1.077$ to $9.238$).
The chi-square value is $4.707$, approximately equivalent to $z$-score of $\sqrt{ {4.707}\div{1}} = 2.17$; a small $P$-value is expected using the [68--95--99.7 rule](#def:EmpiricalRule).
Software output shows that the two-tailed $P$-value is $0.030$, which is indeed 'small'.
We conclude:
> The sample provides *moderate evidence* ($\chi^2 = 4.707$; $P = 0.030$) that the odds in the population of being vitamin B12 deficient is different for vegetarian women (odds: 0.3077) compared to non-vegetarian women (odds: 0.0976; OR: $3.2$; 95% CI: $1.1$ to $9.2$).
```{r B12jamoviOutputHT, fig.show="hold", fig.cap="jamovi output for the B12 data", fig.align="center", out.width="70%"}
knitr::include_graphics( "jamovi/B12/B12-All.png")
```
```{r B12SPSSOutputHT, fig.show="hold", fig.cap="SPSS output for the B12 data", fig.align="center", out.width="80%"}
knitr::include_graphics( "SPSS/B12/B12-Chisq-OR.png")
```
The statistically valid should be checked.
The jamovi output (Fig. \@ref(fig:B12jamoviOutputHT)) shows that the smallest expected count is 4.39.
The text under the *first* table of SPSS output in Fig. \@ref(fig:B12SPSSOutputHT) shows similar information.
Since the smallest expected count is *smaller* than five, the results may be statistically invalid.
Nonetheless, only *one* cell has an expected count less than five, and only *just* under 5, so we shouldn't be too concerned (but it should be noted).
## Example: kerbside dumping {#ORTestDumping}
<div style="float:right; width: 222x; border: 1px; padding:10px">
<img src="Illustrations/karl-bewick-FlBuD_jS2Kk-unsplash.jpg" width="200px"/>
</div>
A study of dumping households goods on the kerbside in Brisbane [@comerford2018motivations] asked people their opinions on the dumping.
All participants were from Brisbane suburbs where a high level of kerbside dumping occurred.
The data (Table \@ref(tab:DumpingTable)) are given in a $2\times 3$ table of counts.
```{r DumpingTable}
DumpTab <- array( dim = c(2, 3))
DumpTab[1, ] <- c(22, 15, 18)
DumpTab[2, ] <- c(6, 1, 36)
colnames(DumpTab) <- c("Acceptable",
"Conditionally acceptable",
"Not acceptable")
rownames(DumpTab) <- c("Reuseable",
"Non-reuseable")
if( knitr::is_latex_output() ) {
kable(DumpTab,
format = "latex",
longtable = FALSE,
caption = "The opinion of Brisbane residents about kerbside dumping",
booktabs = TRUE) %>%
kable_styling(font_size = 10) %>%
row_spec(1, bold = TRUE) %>%
column_spec(1, bold = TRUE)
}
if( knitr::is_html_output() ) {
kable(DumpTab,
format = "html",
longtable = FALSE,
caption = "The opinion of Brisbane residents about kerbside dumping",
booktabs = TRUE)
}
```
The software output is shown in Fig. \@ref(fig:KerbsideChisqjamovi) (for jamovi), and Fig. \@ref(fig:KerbsideChisqSPSS) (for SPSS); a graphical summary in Fig. \@ref(fig:KerbsideSidebysideBar).
Most of the numerical summary must be produced manually (Table \@ref(tab:KerbsideHTNumerical)), since software only produces odds ratios for $2\times 2$ tables.
```{r KerbsideChisqjamovi, fig.show="hold", fig.cap="jamovi output for the kerbside-dumping data", fig.align="center", out.width="80%"}
knitr::include_graphics( "jamovi/Kerbside/Kerbside-All.png")
```
```{r KerbsideChisqSPSS, fig.show="hold", fig.cap="SPSS output for the kerbside-dumping data", fig.align="center", out.width="60%"}
knitr::include_graphics( "SPSS/Kerbside/Kerbside-Chisq.png")
```
```{r KerbsideSidebysideBar, fig.cap="A side-by-side bar chart for the kerbside-dumping data", fig.align="center", out.width="75%", fig.height=4, fig.width=7}
barplot(t(DumpTab),
beside = TRUE,
las = 1,
ylab = "Counts",
xlab = "Type of rubbish",
main = "Side-by-side bar chart\n for kerbside-dumping data",
legend.text = TRUE,
args.legend = list( bty = "n",
ncol = 2,
x = "top"))
#knitr::include_graphics( "SPSS/Kerbside/Kerbside-SidebysideBar.png")
```
```{r KerbsideHTNumerical}
DumpSummary <- array( dim = c(3, 4) )
colnames(DumpSummary) <- c( "Odds",
"Odds ratio",
"Percentage",
"Sample size")
rownames(DumpSummary) <- c("Acceptable",
"Conditionally acceptable",
"Not acceptable")
DumpSummary[1, ] <- c( 3.667,
"7.333",
"78.6%",
28)
DumpSummary[2, ] <- c( 0.500,
"30.0",
"33.3%",
54)
DumpSummary[3, ] <- c(15.000,
"Reference level",
"93.4%",