-
Notifications
You must be signed in to change notification settings - Fork 0
/
05-chi-squared.qmd
2993 lines (2226 loc) · 88.6 KB
/
05-chi-squared.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
# Chi-squared Test {#sec-chap05}
```{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_chi_squared_residuals <-
pkgs_dl(c("janitor", "questionr", "rstatix", "descr"))
save_data_file("chap05", cranlogs_chi_squared_residuals, "cranlogs_chi_squared_residuals.rds")
cranlogs_cramers_v <- pkgs_dl(c("lsr", "rcompanion", "rstatix", "DescTools",
"confintr", "sjstats", "collinear"))
save_data_file("chap05", cranlogs_cramers_v, "cranlogs_cramers_v.rds")
```
## Achievements to unlock
::: {#obj-chap05}
::: {.my-objectives}
::: {.my-objectives-header}
Objectives for chapter 05
:::
::: {.my-objectives-container}
**SwR Achievements**
- **Achievement 1**: Understanding the relationship between two
categorical variables using bar charts, frequencies, and percentages (@sec-chap05-achievement1)
- **Achievement 2**: Computing and comparing observed and expected
values for the groups (@sec-chap05-achievement2)
- **Achievement 3**: Calculating the chi-squared statistic for the
test of independence (@sec-chap05-achievement3)
- **Achievement 4**: Interpreting the chi-squared statistic and making
a conclusion about whether or not there is a relationship (@sec-chap05-achievement4)
- **Achievement 5**: Using Null Hypothesis Significance Testing to
organize statistical testing (@sec-chap05-achievement5)
- **Achievement 6**: Using standardized residuals to understand which
groups contributed to significant relationships (@sec-chap05-achievement6)
- **Achievement 7**: Computing and interpreting effect sizes to
understand the strength of a significant chi-squared relationship (@sec-chap05-achievement7)
- **Achievement 8**: Understanding the options for failed chi-squared
assumptions (@sec-chap05-achievement8)
:::
:::
Achievements for chapter 05
:::
## The voter fraud problem
Information from studies suggests that voter fraud does happen but it
is rare. In contrast to these studies a great minority of people (20-30%) in
the US believe that voter fraud is a big problem. Many states are
building barriers to vote, and other states make voting more easily, for
instance with automatic voter registration bills.
## Resources & Chapter Outline
### Data, codebook, and R packages {#sec-chap05-data-codebook-packages}
::: {.my-resource}
::: {.my-resource-header}
:::::: {#lem-chap05-resources}
: Data, codebook, and R packages for learning about descriptive statistics
::::::
:::
::: {.my-resource-container}
**Data**
Two options for assessing the data:
1. Download the data set `pew_apr_19-23_2017_weekly_ch5.sav` from
<https://edge.sagepub.com/harris1e>
2. Download the data set from the `r glossary("Pew Research Center")`
website
(<https://www.people-press.org/2017/06/28/public-supports-aimof-making-it-easy-for-all-citizens-to-vote/>)
**Codebook**
Two options for assessing the documentation:
1. Download the documentation files `pew_voting_april_2017_ch5.pdf`,
`pew_voting_demographics_april_2017_ch5.docx`, and
`pew_chap5_readme.txt` from <https://edge.sagepub.com/harris1e>
2. Download the data set from the [Pew Research Center website](https://www.pewresearch.org/download-datasets/) and the
documentation will be included with the zipped file.
**Packages**
1. Packages used with the book (sorted alphabetically)
- {**desc**}: @pak-descr (Jakson Alves de Aquino)
- {**fmsb**}: @pak-fmsb (Minato Nakazawa)
- {**haven**}: @pak-haven (Hadley Wickham)
- {**lsr**}: @pak-lsr (Danielle Navarro[^05-chi-squared-1])
- {**tidyverse**}: @pak-tidyverse (Hadley Wickham)
2. My additional packages (sorted alphabetically)
:::
:::
[^05-chi-squared-1]: Not Daniel Navarro as mentioned in the book.
Danielle has changed her gender.
### Get data
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-get-pew-data}
: Get pew data about public support for making it easy to vote
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: get-pew-data
#| eval: false
## run only once manually #########
vote <- haven::read_sav("data/chap05/pew_apr_19-23_2017_weekly_ch5.sav")
vote <- vote |>
labelled::remove_labels()
save_data_file("chap05", vote, "vote.rds")
```
***
(*For this R code chunk is no output available*)
:::::{.my-remark}
:::{.my-remark-header}
Removing labels
:::
::::{.my-remark-container}
`haven::zap_labels()` as used in the book removes value labels and not variable labels. The correct function would be `haven::zap_label()`. I have used the {**labelled**} package where you can use `labelled::remove_labels()` to delete both (variable & value labels).
::::
:::::
::::
:::::
:::::{.my-watch-out}
:::{.my-watch-out-header}
Error message with labelled data
:::
::::{.my-watch-out-container}
I have removed the labelled data immediately, because I got an error message caused by summary statistics (e.g., `base::summary()`, `skimr::skim()`, `dplyr::summarize()`) whenever I rendered the file (but not when I compiled the code chunk.)
I didn't have time to look into this issue --- and I had to remove the labels anyway.
What follows is the error message:
```
Quitting from lines 180-186 [show-pew-raw-data] (05-chi-squared.qmd)
Error in `dplyr::summarize()`:
ℹ In argument: `skimmed = purrr::map2(...)`.
Caused by error in `purrr::map2()`:
ℹ In index: 1.
ℹ With name: character.
Caused by error in `dplyr::summarize()`:
ℹ In argument: `dplyr::across(tidyselect::any_of(variable_names),
mangled_skimmers$funs)`.
Caused by error in `across()`:
! Can't compute column `state_~!@#$%^&*()-+character.empty`.
Caused by error in `as.character()`:
! Can't convert `x` <haven_labelled> to <character>.
Backtrace:
1. skimr::skim(vote)
28. skimr (local) `<fn>`(state)
29. x %in% empty_strings
31. base::mtfrm.default(`<hvn_lbll>`)
33. vctrs:::as.character.vctrs_vctr(x)
```
::::
:::::
### Show raw data
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-show-pew-raw-data}
: Get pew data about public support for making it easy to vote
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: show-pew-raw-data
#| results: hold
#| cache: true
vote <- base::readRDS("data/chap05/vote.rds")
skimr::skim(vote)
```
::::
:::::
### Recode data for chapter 5
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-recode-pew-data}
: Select some columns from the pew data set
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: recode-pew-data
#| results: hold
vote <- base::readRDS("data/chap05/vote.rds")
## create vote_clean #############
vote_clean <- vote |>
dplyr::select(pew1a, pew1b, race, sex,
mstatus, ownhome, employ, polparty) |>
labelled::remove_labels() |>
dplyr::mutate(dplyr::across(1:8, forcats::as_factor)) |>
naniar::replace_with_na(replace = list(
pew1a = c(5, 9),
pew1b = c(5, 9),
race = 99,
ownhome = c(8, 9)
)) |>
dplyr::mutate(pew1a = forcats::fct_recode(pew1a,
"Register to vote" = "1",
"Make easy to vote" = "2",
)) |>
dplyr::mutate(pew1b = forcats::fct_recode(pew1b,
"Require to vote" = "1",
"Choose to vote" = "2",
)) |>
dplyr::mutate(race = forcats::fct_recode(race,
"White non-Hispanic" = "1",
"Black non-Hispanic" = "2",
)) |>
dplyr::mutate(race = forcats::fct_collapse(race,
"Hispanic" = c("3", "4", "5"),
"Other" = c("6", "7", "8", "9", "10")
)) |>
dplyr::mutate(sex = forcats::fct_recode(sex,
"Male" = "1",
"Female" = "2",
)) |>
dplyr::mutate(ownhome = forcats::fct_recode(ownhome,
"Owned" = "1",
"Rented" = "2",
)) |>
dplyr::mutate(dplyr::across(1:8, forcats::fct_drop)) |>
dplyr::rename(ease_vote = "pew1a",
require_vote = "pew1b")
save_data_file("chap05", vote_clean, "vote_clean.rds")
skimr::skim(vote_clean)
```
***
I have used in this recoding R chunk several functions for the first time:
- I turned all character columns into factor variables with just one line of code using `dplyr::across()` in combination with `forcats::as_factor()`.
- I replaced missing values (NAs) with the `replace_with_na()` function of the {**naniar**} package (see @pak-naniar).
- I combined several levels with `forcats::fct_collapse()`.
- And finally I dropped all unused levels in the whole data.frame using `dplyr::across()` in conjunction with `forcats::fct_drop()`.
::::
:::::
## Achievement 1: Relationship of two categorical variables {#sec-chap05-achievement1}
### Descriptive statistics
For better display I have reversed the order of the variables: Instead of grouping y ease of vote I will group by race/ethnicity. This will give a smaller table with only two columns instead of four that will not fit on the screen without horizontal scrolling.
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap05-stats-voting-data}
: Frequencies between two categorical variables
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### summarize()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-summarize-ease-voting}
: Summarize relationship ease of vote and race/ethnicity
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: summarize-ease-voting
#| results: hold
#| cache: true
## load vote_clean ##########
vote_clean <- base::readRDS("data/chap05/vote_clean.rds")
ease_vote_sum <- vote_clean |>
tidyr::drop_na(ease_vote) |>
tidyr::drop_na(race) |>
dplyr::group_by(race, ease_vote) |>
## either summarize
dplyr::summarize(n = dplyr::n(),
.groups = "keep")
## or count the observation in each group
# dplyr::count()
ease_vote_sum
```
***
Here I used "standard" tidyverse code to count frequencies. Instead of the somewhat complex last code line I could have used just `dplyr::count()` with the same result.
::::
:::::
:::::{.my-watch-out}
:::{.my-watch-out-header}
WATCH OUT! Prevent warning with `.groups` argument
:::
::::{.my-watch-out-container}
By using two variables inside `dplyr::group_by()` I got a warning message:
> `summarise()` has grouped output by 'ease_vote'.
> You can override using the `.groups` argument.
At first I had to set the chunk option `warning: false` to turn off this warning. But finally I managed to prevent the warning with R code. See the [summarize help page](https://dplyr.tidyverse.org/reference/summarise.html) under arguments `.groups`. Another option to suppress the warning would have been `options(dplyr.summarise.inform = FALSE)`. See also the two [comments in StackOverflow](https://stackoverflow.com/questions/71914704/override-using-groups-argument) and [r-stats-tips](https://rstats-tips.net/2020/07/31/get-rid-of-info-of-dplyr-when-grouping-summarise-regrouping-output-by-species-override-with-groups-argument/).
::::
:::::
###### pivot_wider()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-pivot-wider-ease-voting}
: Summarize by converting data from long to wide with `pivot_wider()` from {**tidyr**}
::::::
:::
::::{.my-r-code-container}
:::{#lst-chap05-pivot-wider-ease-voting}
```{r}
#| label: pivot-wider-ease-voting
#| cache: true
ease_vote_wider <- vote_clean |>
tidyr::drop_na(ease_vote) |>
tidyr::drop_na(race) |>
dplyr::group_by(race, ease_vote) |>
dplyr::summarize(
n = dplyr::n(),
.groups = "keep") |>
tidyr::pivot_wider(
names_from = ease_vote,
values_from = n
)
ease_vote_wider
```
Summarizing and converting data from long to wide with `pivot_wider()` from {**tidyr**}
:::
***
We get with `dplyr::pivot_wider()` a more neatly arranged table.
::::
:::::
###### table()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-base-table-ease-voting}
: Summarize with `base::table()`
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: base-table-ease-voting
#| results: hold
ease_vote_table <- base::table(
vote_clean$race,
vote_clean$ease_vote,
dnn = c("Race", "Ease of voting")
)
ease_vote_table
```
***
Note that NA's are automatically excluded from the table.
::::
:::::
With the simple `base::table()` we will get a very similar result as in the more complex `dplyr::pivot_wider()` code variant in @lst-chap05-pivot-wider-ease-voting.
But I prefer in any case the tidyverse version for several reasons:
:::::{.my-remark}
:::{.my-remark-header}
Some deficiencies of `base::table()`
:::
::::{.my-remark-container}
- `table()` does not accept data.frame as input and you can't therefore chain several commands together with the ` |> ` pipe.
- `table()` does not output data.frames
- `table()` is very difficult to format and to make it print ready.
::::
:::::
###### xtabs()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-base-xtabs-ease-voting}
: Summarize with a `stats::xtabs()`
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: base-xtabs-ease-voting
ease_vote_xtabs <- stats::xtabs(n ~ race + ease_vote, data = ease_vote_sum)
ease_vote_xtabs
```
::::
:::::
###### tabyl()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-tabyl-voting-data}
: Frequencies with `tabyl()` from {**janitor**}
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: tabyl-voting-data
#| results: hold
ease_vote_tabyl <- vote_clean |>
janitor::tabyl(race, ease_vote, show_na = FALSE)
ease_vote_tabyl
```
***
`janitor::tabyl()` prevents the weaknesses of the `base::table()` function. It works with data.frames, is tidyverse compatible and has many `adorn_*` functions (`adorn_` stands for "adornment") to format the output values.
::::
:::::
###### prop.table()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-contingency-prop-table-voting-data}
: Summarize with a base R proportion contingency table
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: prop-contingency-table-voting-data
#| results: hold
base::prop.table(
base::table(`Race / Ethnicity` = vote_clean$race,
`Ease of voting` = vote_clean$ease_vote), margin = 1)
```
***
All was I said about flaws for `base::table()` is of course valid for the `base::prop.table()` function as well.
::::
:::::
###### tabyl() formatted
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-janitor-voting-data}
: Frequencies with `tabyl()` from {**janitor**} formatted
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: janitor-voting-data
#| results: hold
vote_clean |>
janitor::tabyl(race, ease_vote, show_na = FALSE) |>
janitor::adorn_percentages("row") |>
janitor::adorn_pct_formatting(digits = 2) |>
janitor::adorn_ns() |>
janitor::adorn_title(row_name = "Race / Ethnicity",
col_name = "Ease of voting")
```
***
In this example you can see the power of the {**janitor**} package. The main purpose of the {**janitor**} is data cleaning, but because counting is such a fundamental part of data cleaning and exploration the `tabyl()` and `adorn_*()` has been included in this package.
::::
:::::
###### Ease of voting
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-ease-voting-data}
: Ease of voting by race / ethnicity
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap05-ease-voting}
```{r}
#| label: ease-voting-data
#| results: hold
vote_clean |>
janitor::tabyl(race, ease_vote, show_na = FALSE) |>
janitor::adorn_percentages("row") |>
janitor::adorn_pct_formatting(digits = 2) |>
janitor::adorn_ns() |>
janitor::adorn_title(row_name = "Race / Ethnicity",
col_name = "Ease of voting")
```
Ease of voting by race / ethnicity
:::
***
::: {.callout-tip}
The voting registration policy a person favors differed by race/ethnicity.
- White non-Hispanic participants were fairly evenly divided between those who thought people should register if they want to vote and those who thought voting should be made as easy as possible.
- The other three race-ethnicity groups had larger percentages in favor of making it as easy as possible to vote.
- Black non-Hispanic participants have the highest percentage (77.78%) in favor of making it easy to vote.
:::
::::
:::::
###### Require to vote
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-require-voting-data}
: Voting as requirement or free choice by race /ethnicity
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap05-require-voting}
```{r}
#| label: require-voting-data
#| results: hold
vote_clean |>
janitor::tabyl(race, require_vote, show_na = FALSE) |>
janitor::adorn_percentages("row") |>
janitor::adorn_pct_formatting(digits = 2) |>
janitor::adorn_ns() |>
janitor::adorn_title(row_name = "Race / Ethnicity",
col_name = "Voting as citizen duty or as a free choice?")
```
Voting as requirement or free choice by race /ethnicity
:::
***
::: {.callout-tip}
Different ethnicities have distinct opinions about the character of voting.
- About one-third of Black non-Hispanic and Hispanic believe that voting should be a requirement. But this means on the other hand, that at least two-third of both groups see voting as a free choice.
- In contrast to this proportion are white non-Hispanic and other non-Hispanic ethnicities: In those groups more than 80% favor voting as a free choice.
:::
::::
:::::
:::
::::
:::::
:::::{.my-resource}
:::{.my-resource-header}
:::::: {#lem-chap05-cross-tabulation}
Cross-Tabulation
::::::
:::
::::{.my-resource-container}
- [Working with Tables in R](https://bookdown.org/kdonovan125/ibis_data_analysis_r4/working-with-tables-in-r.html) in [@donovan2019a].
- [Cross-Tabulation in R](https://www.marsja.se/cross-tabulation-in-r-creating-interpreting-contingency-tables/): Creating & Interpreting Contingency Tables [@marsja2023].
- [Tables in R](https://cran.r-project.org/web/packages/DescTools/vignettes/TablesInR.pdf): A Quick Practical Overview [@signorell2021], see also [@pak-DescTools].
- [Introduction to Crosstable](https://cran.r-project.org/web/packages/crosstable/vignettes/crosstable.html) [@chalthiel2023], see also [@pak-crosstable].
::::
:::::
### Graphs
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap05-descriptive-graphs}
: Descriptive graphs
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### geom_col()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-pew-voting-geom-col-graph}
: Visualizing opinions about ease of voting by race / ethnicity
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-pew-voting-geom-col-graph
#| fig-cap: "Opinion on ease of voting by race / ethnicity from a study of the Pew Research Center 2017 (n = 1,028)"
p_ease_vote <- vote_clean |>
## prepare data
tidyr::drop_na(ease_vote) |>
tidyr::drop_na(race) |>
dplyr::group_by(race, ease_vote) |>
dplyr::count() |>
dplyr::group_by(race) |>
dplyr::mutate(perc = n / base::sum(n)) |>
## draw graph
ggplot2::ggplot(
ggplot2::aes(
x = race,
y = perc,
fill = ease_vote)
) +
ggplot2::geom_col(position = "dodge") +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::labs(
x = "Race / Ethnicity",
y = "Percent"
) +
ggplot2::scale_fill_viridis_d(
name = "Ease of voting",
alpha = .8, # here alpha works!!
begin = .25,
end = .75,
direction = -1,
option = "viridis"
)
p_ease_vote
```
***
I had several difficulties by drawing this graph:
1. Most important: I did not know that the second variable `ease_vote` has to be included by the `fill` argument. That seems not logical but together with `position = dodge` it make sense.
2. I didn't know that I have to group by race again (the line after `dplyr::count()`)
3. I thought that I could calculate the percentages with `ggplot2::after_stat()`. The solution was more trivial: Creating a new column with the calculated percentages and using `geom_col()` instead of `geom_bar()`.
Instead of the last line I could have used with the same result: `ggplot2::geom_bar(position = "dodge", stat = "identity")`. `geom_bar()` uses as standard option `ggplot2::stat_count()`. It is however possible to override the default value as was done in the book code. But it easier here to use `geom_col()` because it uses as default `stat_identity()` e.g., it leaves the data as is.
::: {.callout-note #nte-chap05-changes}
**Two additional remarks**:
1. I have used here the percent scale from the {**scales**} package to get percent signs on the y-axis.
2. I practiced my learnings from @sec-chap03 about adding a color-friendly palette (see @sec-chap03-practice-test). (See also my color test in @cnj-chap05-color-test-bw.)
:::
::::
:::::
###### geom_bar()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-pew-voting-geom-bar-graph}
: Visualizing opinions about ease of voting by race / ethnicity
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-pew-voting-geom-bar-graph
#| fig-cap: "Opinion on ease of voting by race / ethnicity from a study of the Pew Research Center 2017 (n = 1,028)"
vote_clean |>
tidyr::drop_na(ease_vote) |>
tidyr::drop_na(race) |>
ggplot2::ggplot(
ggplot2::aes(
x = race,
fill = ease_vote
)
) +
ggplot2::geom_bar(position = "dodge",
ggplot2::aes(
y = ggplot2::after_stat(count / base::sum(count))
)) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::labs(
x = "Race / Ethnicity",
y = "Percent"
) +
ggplot2::scale_fill_viridis_d(
name = "Ease of voting",
alpha = .8, # here alpha works!!
begin = .25,
end = .75,
direction = -1,
option = "viridis"
)
```
***
Here I have used `geom_bar()` with the `after_stat()` calculation. It turned out that the function computes the percentages of the different race categories for the two `ease_vote` values. This was not was I had intended.
I tried for several hours to use `after_stat()` with the same result as in @cnj-chap05-pew-voting-geom-col-graph, but I didn't succeed. I do not know if the reason is my missing knowledge (for instance to generate another structure of the data.frame) or if you can't do that in general.
::::
:::::
###### geom_col() with labels
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-pew-voting-geom-col-label-graph}
: Visualizing opinions about ease of voting by race / ethnicity
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-pew-voting-geom-col-label-graph
#| fig-cap: "Opinion on ease of voting by race / ethnicity from a study of the Pew Research Center 2017 (n = 1,028)"
vote_clean |>
tidyr::drop_na(ease_vote) |>
tidyr::drop_na(race) |>
dplyr::group_by(race, ease_vote) |>
dplyr::count() |>
dplyr::group_by(race) |>
dplyr::mutate(perc = n / base::sum(n)) |>
ggplot2::ggplot(
ggplot2::aes(
x = race,
y = perc,
fill = ease_vote)
) +
ggplot2::geom_col(position = "dodge") +
ggplot2::geom_label(
ggplot2::aes(
x = race,
y = perc,
label = paste0(round(100 * perc, 1),"%"),
vjust = 1.5, hjust = -.035
),
color = "white"
) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::labs(
x = "Race / Ethnicity",
y = "Percent"
) +
ggplot2::scale_fill_viridis_d(
name = "Ease of voting",
alpha = .8, # here alpha works!!
begin = .25,
end = .75,
direction = -1,
option = "viridis"
)
```
***
Here I have experimented with labels. It seems that with the argument `position = dodge` the labels can't appear on each of the appropriate bars.
::::
:::::
###### requirements
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-pew-voting-requirements-by-race}
: Visualizing opinions about requirements of voting by race / ethnicity
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-pew-voting-requirements-by-race
#| fig-cap: "Opinion on voting requirements by race / ethnicity from a study of the Pew Research Center 2017 (n = 1,028)"
p_require_vote <- vote_clean |>
## prepare data
tidyr::drop_na(require_vote) |>
tidyr::drop_na(race) |>
dplyr::group_by(race, require_vote) |>
dplyr::count() |>
dplyr::group_by(race) |>
dplyr::mutate(perc = n / base::sum(n)) |>
## draw graph
ggplot2::ggplot(
ggplot2::aes(
x = race,
y = perc,
fill = require_vote)
) +
ggplot2::geom_col(position = "dodge") +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::labs(
x = "Race / Ethnicity",
y = "Percent"
) +
ggplot2::scale_fill_viridis_d(
name = "Requirements of voting",
alpha = .8, # here alpha works!!
begin = .25,
end = .75,
direction = -1,
option = "viridis"
)
p_require_vote
```
::::
:::::
###### Voting by race
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-voting-opinions-by-race}
: Visualizing opinions about voting by race / ethnicity
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: fig-pew-voting-by-race
#| fig-cap: "Opinion on ease of voting and voting requirements by race / ethnicity from a study of the Pew Research Center 2017 (n = 1,028)"
#| fig-height: 6
#| warning: false
p_ease <- p_ease_vote +
ggplot2::labs(
x = "",
y = "Percent within group"
) +
ggplot2::scale_fill_viridis_d(
name = "Opinion on\nvoter registration",
alpha = .8,
begin = .25,
end = .75,
direction = -1,
option = "viridis"
) +
ggplot2::theme(axis.text.x = ggplot2::element_blank())
p_require <- p_require_vote +
ggplot2::labs(y = "Percent within group") +
ggplot2::scale_fill_viridis_d(
name = "Opinion on\nvoting",
alpha = .8,
begin = .25,
end = .75,
direction = -1,
option = "viridis"
)
gridExtra::grid.arrange(p_ease, p_require, ncol = 1)
```
::::
:::::
###### Color test
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap05-color-test-bw}
: Test how the colors used for the graph race by ease of voting look for printing in black & white
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap05-color-test-bw}
```{r}
#| label: fig-color-test-bw
#| fig-cap: "Test if used colors of my graph race by ease of voting look are also readable for black & white printing"
#| fig-height: 3
#| results: hold
pal_data <- list(names = c("Normal", "desaturated"),
color = list(scales::viridis_pal(
alpha = .8,
begin = .25,
end = .75,
direction = -1,
option = "viridis")(2),
colorspace::desaturate(scales::viridis_pal(
alpha = .8,
begin = .25,
end = .75,
direction = -1,
option = "viridis")(2)))
)
list_plotter(pal_data$color, pal_data$names,
"Colors and black & white of graph race by ease of voting")
```
Test how the colors I have used for my graphs about race by ease of voting look in black & white
:::
::::
:::::
:::
::::
:::::
## Achievement 2: Comparing groups {#sec-chap05-achievement2}
The `r glossary("chi-squared")` test is useful for testing to see if there may be a statistical relationship between two categorical variables. The chi-squared test is based on the observed values, and the values expected to occur if there were no relationship between the variables.
### Observed values
We will use the observed values from @lst-chap05-ease-voting and @lst-chap05-require-voting.
### Expected values