-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11-multinomial-regression.qmd
2126 lines (1613 loc) · 63 KB
/
11-multinomial-regression.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
# Multinomial and ordinal logistic regression {#sec-chap11}
```{r}
#| label: setup
#| include: false
options(warn = 0) # default value: change for debugging. See: ?warning
base::source(file = "R/helper.R")
ggplot2::theme_set(ggplot2::theme_bw())
```
## Achievements to unlock
::: {#obj-chap11}
::: my-objectives
::: my-objectives-header
Objectives for chapter 11
:::
::: my-objectives-container
**SwR Achievements**
- **Achievement 1**: Using exploratory data analysis for multinomial
logistic regression (@sec-chap11-achievement1)
- **Achievement 2**: Estimating and interpreting a multinomial
logistic regression model (@sec-chap11-achievement2)
- **Achievement 3**: Checking assumptions for multinomial logistic
regression (@sec-chap11-achievement3)
- **Achievement 4**: Using exploratory data analysis for ordinal
logistic regression (@sec-chap11-achievement4)
- **Achievement 5**: Estimating and interpreting an ordinal logistic
regression models (@sec-chap11-achievement5)
- **Achievement 6**: Checking assumptions for ordinal logistic
regression (@sec-chap11-achievement6)
:::
:::
Achievements for chapter 11
:::
## The diversity dilemma in STEM
There is a lack of diversity in the science, technology, engineering,
and math (STEM) fields and specifically about the lack of women. There
are fewer women college graduates in computer science and math jobs now
compared to 15 years ago.
There are three main reasons cited for fewer women in STEM:
- beliefs about natural ability,
- societal and cultural norms,
- and institutional barriers.
One thing that appeared to encourage women in STEM is the visibility of
other women in STEM careers.
## Resources & Chapter Outline
### Data, codebook, and R packages {#sec-chap04-data-codebook-packages}
::: my-resource
::: my-resource-header
Data, codebook, and R packages for learning about descriptive statistics
:::
::: my-resource-container
**Data**
Three options for accessing the data:
1. Download and save the original SAS file `stem-nsf-2017-ch11.xpt`
from <https://edge.sagepub.com/harris1e> and run the code in the
first code chunk to clean the data.
2. Download and save the original SAS file `stem-nsf-2017-ch11.xpt`
from <https://edge.sagepub.com/harris1e> and follow the steps in Box
11.1 to clean the data.
3. Download and save the original 2017 National Survey of College
Graduates data from the National Science Foundation’s SESTAT Data
Tool (https://ncsesdata.nsf.gov/datadownload/) and follow Box 11.1
to clean the data.
As there is nothing new for me in the recoding procedures I will go for
the first option.
**Codebook**
Two options for accessing the codebook:
- Download the `stem-nsf-2017-ch11-codebook.pdf` from
<https://edge.sagepub.com/harris1e>
- Use the version that comes when downloading the raw data file from
the National Science Foundation’s SESTAT Data Tool
(https://ncsesdata.nsf.gov/datadownload/)
**Packages**
1. Packages used with the book (sorted alphabetically)
- {**Hmsic**}: @sec-Hmisc (Frank Harrell)
- {**MASS**}: @sec-MASS (Brian Ripley)
- {**mlogit**}: @sec-mlogit (Yves Croissant)
- {**nnet**}: @sec-nnet (Brian Ripley)
- {**ordinal**} @sec-ordinal (Rune Haubo Bojesen Christensen)
- {**scales**} @sec-scales (Thomas Lin Pedersen) (not mentioned in the book)
- {**tableone**} @sec-tableone (Kazuki Yoshida)
- {**tidyverse**}: @sec-tidyverse (Hadley Wickham)
2. My additional packages (sorted alphabetically)
- {**dfidx**}: @sec-dfidx (Yves Croissant)
- {**glue**}: @sec-glue (Jennifer Bryan)
- {**haven**}: @sec-haven (Hadley Wickham)
- {**skimr**}: @sec-skimr (Elin Waring)
:::
:::
### Get & recode data
::: my-r-code
::: my-r-code-header
::: {#cnj-chap11-get-data}
: Get and recode data for chapter 11
:::
:::
::: my-r-code-container
::: {#lst-chap11-get-data}
```{r}
#| label: get-data
#| eval: false
## using zip file because of GitHub file limit of 100 MB
tbl11 <- utils::unzip(
zipfile = "data/chap11/stem-nsf-2017-ch11.xpt.zip",
files = "stem-nsf-2017-ch11.xpt"
) |>
Hmisc::sasxport.get()
# function to recode the satisfaction variables
RecSatis <- function(x){
return(forcats::fct_recode(x,
"Very satisfied" = "1" ,
"Somewhat satisfied" = "2",
"Somewhat dissatisfied" = "3",
"Very dissatisfied" = "4",
NULL = "L")
)
}
# recode and rename
tbl11.1 <- tbl11 |>
dplyr::select(n2ocprmg, satadv, satsal, satsoc, gender, age) |>
dplyr::mutate(job_cat = forcats::as_factor(
forcats::fct_recode(.f = n2ocprmg,
"CS, Math, Eng" = "1",
"Other Sciences" = "2",
"Other Sciences" = "3",
"Other Sciences" = "4",
"CS, Math, Eng" = "5",
NULL = "6",
"Nonscience" = "7",
NULL = "8"
)
)
) |>
dplyr::mutate(satis_advance = RecSatis(x = satadv)) |>
dplyr::mutate(satis_salary = RecSatis(x = satsal)) |>
dplyr::mutate(satis_contrib = RecSatis(x = satsoc)) |>
dplyr::mutate(sex = dplyr::recode(.x = gender, "M" = "Male", "F"= "Female")) |>
dplyr::mutate(sex = forcats::fct_relevel(.f = sex, c("Male", "Female"))) |>
dplyr::mutate(age = as.numeric(x = age)) |>
dplyr::select(-n2ocprmg, -satadv, -satsal, -satsoc, -gender) |>
haven::zap_label()
# # make sure the reordering worked
# # re-order to have male first for ref group
# print(levels(x = tbl11.1$sex))
save_data_file("chap11", tbl11.1, "tbl11.1.rds")
```
Get and recode data for chapter 11
:::
(*For this R code chunk is no output available*)
:::
:::
------------------------------------------------------------------------
At first I thought that there are no new things in recoding the data for
chapter 11. But it turned out that there are some issues to report:
1. **Using `haven::read_xpt()` instead of `Hmisc::sasxport.get()`**
This was an error in two respects:
- The variable names were not converted to lower case. So I had to
change all variable names in the following recoding.
- The {**haven**} function was *extremely* slow! In contrast to
`sasxport.get()` with 3.94 seconds the file export took 104.12
second, e.g. more than 26 times longer!
I therefore returned to the much fast solution with
`Hmisc::sasxport.get()`.
------------------------------------------------------------------------
2. **Labelled data**
I got with the export of a SAS transport file a labelled data frame with
very long labels. After the recoding I lost many of these labels except
of two columns. Therefore I used `haven::zap_label()` to remove all
variable labels.
------------------------------------------------------------------------
3. **The original data file is too big for GitHub**
After I committed to GitHub I got an error, because the file
`stem-nsf-2017-ch11.xpt` was too large. I compressed it as `.zip`-file
and changed the import code slightly to adapt this change. After testing
that it worked I deleted the uncompressed file.
------------------------------------------------------------------------
4. **Using the {forcats} package**
I changed the factor levels in the `RecSatis()` function with the
{**forcats**} package.
### Show raw data
::: my-example
::: my-example-header
::: {#exm-chap11-show-data}
: Show summary of recoded data for chapter 11
:::
:::
::: my-example-container
::: panel-tabset
###### tbl11.1
::: my-r-code
::: my-r-code-header
::: {#cnj-chap11-show-tbl11.1}
: Show recoded data for chapter 11 (`tbl11.1`)
:::
:::
::: my-r-code-container
::: {#lst-chap11-show-tbl11.1}
```{r}
#| label: show-tbl11.1
#| results: hold
tbl11.1 <- base::readRDS("data/chap11/tbl11.1.rds")
glue::glue("********** Summarizing with base:summary() **************")
base::summary(tbl11.1)
glue::glue(" ")
glue::glue(" ")
glue::glue("********** Summarizing with skimr::skim() **************")
glue::glue(" ")
skimr::skim(tbl11.1)
```
Show recoded data for chapter 11 (`tbl11.1`)
:::
------------------------------------------------------------------------
- **job_cat**: Job caktegory of current job. `n2ocprmg` was the
original variable name. Recoded into three categories:
- CS, Math, Eng = Computer science, math, and engineering fields
- Other sciences = Other science fields
- Nonscience = Not a science field
- **satis_advance**: Satisfaction with advancement opportunity.
`satadv` was the original variable name. 4-point Likert scale from 4
= very dissatisfied to 1 = very satisfied.
- `satis_salary`: Satisfaction with salary. `satsal` was the original
variable name. 4-point Likert scale from 4 = very dissatisfied to 1
= very satisfied.
- **satis.contrib**: Satisfaction with contribution to society.
`satsoc` was the original variable name. 4-point Likert scale from 4
= very dissatisfied to 1 = very satisfied
- **sex**: gender was the original variable name. Two categories:
Female, Male
- **age**: Age in years, not recoded or renamed
:::
:::
###### sample
::: my-r-code
::: my-r-code-header
::: {#cnj-chap11-sample-by-group}
: Sample 1500 cases: 500 from each job category
:::
:::
::: my-r-code-container
::: {#lst-chap11-sample-by-group}
```{r}
#| label: sample-by-group
#| results: hold
tbl11.1 <- base::readRDS("data/chap11/tbl11.1.rds")
base::set.seed(seed = 143)
# take a sample of 1500 cases
# 500 from each job.cat category
tbl11.2 <- tbl11.1 |>
tidyr::drop_na(job_cat) |>
dplyr::group_by(job_cat) |>
dplyr::slice_sample(n = 500)
save_data_file("chap11", tbl11.2, "tbl11.2.rds")
glue::glue("********** Summarizing with base:summary() **************")
base::summary(tbl11.2)
glue::glue(" ")
glue::glue(" ")
glue::glue("********** Summarizing with skimr::skim() **************")
glue::glue(" ")
skimr::skim(tbl11.2)
```
Show sampled data: 500 from each job category
:::
:::
:::
:::
:::
:::
## Achievement 1: EDA for multinomial logistic regression {#sec-chap11-achievement1}
### Visualizing employment
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap11-eda-employment}
: Visualizing employment in computer science, math, and engineering by sex and age
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### sex-jobs
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-sex-wihtin-jobtype}
: Plotting distribution of sex within job type
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-sex-wihtin-jobtype}
```{r}
#| label: eda-sex-wihtin-jobtype
tbl11.2 <- base::readRDS("data/chap11/tbl11.2.rds")
# plotting distribution of sex within job type (Figure 11.3)
tbl11.2 |>
ggplot2::ggplot(
ggplot2::aes(
x = sex,
group = job_cat,
y = ggplot2::after_stat(prop)
)
) +
ggplot2::geom_bar(fill = "#7463AC") +
ggplot2::labs(
y = "Percent within job category",
x = "Sex"
) +
# ggplot2::facet_grid(cols = ggplot2::vars(job_cat)) +
# using another, more simple facet_grid() function:
ggplot2::facet_grid(~ job_cat) +
ggplot2::scale_y_continuous(labels = scales::percent)
```
Distribution of sex within job type among 1,500 college graduates in 2017
:::
***
`ggplot2::after_stat()` replaces the old approach surrounding the variable names with .., e.g. `..prop..`. {**ggplot2**} throws a warning:
> #> Warning: The dot-dot notation (`..prop..`) was deprecated in ggplot2 3.4.0.
>
> #> ℹ Please use `after_stat(prop)` instead.
At first I had problems, because I used `y = ggplot2::after_stat(count/sum(count))` inside the `ggplot2::aes()` function. This calculated the percentage over all different categories and not within each job category. The I learned with **The 'computed variables' section in each stat lists which variables are available to access.** that {**ggplot2**} computes with the `ggplot2::stat_count()` function for bar charts also groupwise proportion with `ggplot2::after_stat(prop)`.
::::
:::::
:::::{.my-resource}
:::{.my-resource-header}
:::::: {#lem-chap11-using-ggplot2-after-stat}
: How to use ggplot2::after_stat()?
::::::
:::
::::{.my-resource-container}
To learn how to use the `ggplot2::after_stat()` function:
- Read the help page to understand the differences between the different stages of mapping (direct input, `after_stat()` and `after_scale()`). Very important is the sentence: **The 'computed variables' section in each stat lists which variables are available to access.**
- Read the short article [Using after_stat() in {**ggplot2**}](https://rstudio-pubs-static.s3.amazonaws.com/789869_e4500f2be0ba45279290b1753d8358bc.html) to use `after_stat()` to show percentages in the bar chart.
- The first article of the very extensive series of articles going into many technical detail working --- at least for me --- as an eye opener how {**ggplot2**} works [Demystifying delayed aesthetic evaluation: Part 1](https://yjunechoe.github.io/posts/2022-03-10-ggplot2-delayed-aes-1/).
- Hadley Wickham is currently preparing online the third edition of [ggplot2: Elegant Graphics for Data Analysis](https://ggplot2-book.org/) which also has many details about the `after_stat()` function, for instance in [13 Build a plot layer by layer](https://ggplot2-book.org/layers.html#sec-stat).
::::
:::::
###### jobs by sex
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-jobtype-sex}
: Distribution of job type by sex
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-jobtype-sex}
```{r}
#| label: eda-jobtype-sex
# plotting distribution of job type by sex (Figure 11.4)
tbl11.2 |>
ggplot2::ggplot(
ggplot2::aes(
x = job_cat,
group = sex,
y = ggplot2::after_stat(prop)
)
) +
ggplot2::geom_bar(fill = "#7463AC") +
ggplot2::labs(
y = "Percent within sex category",
x = "Job category"
) +
ggplot2::facet_grid(cols = ggplot2::vars(sex)) +
ggplot2::scale_y_continuous(labels = scales::percent)
```
Distribution of job type by sex
:::
::::
:::::
###### jobs by age
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-jobtype-age}
: Distribution of job type and age
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-jobtype-age}
```{r}
#| label: eda-jobtype-age
# plotting distribution of job type and age (Figure 11.5)
tbl11.2 |>
ggplot2::ggplot(
ggplot2::aes(
y = age,
x = job_cat
)
) +
ggplot2::geom_jitter(
ggplot2::aes(
color = job_cat
),
alpha = .6
) +
ggplot2::geom_boxplot(
ggplot2::aes(
fill = job_cat
),
alpha = .4
) +
ggplot2::scale_fill_manual(
values = c("dodgerblue2","#7463AC", "gray40"),
guide = "none") +
ggplot2::scale_color_manual(values = c("dodgerblue2","#7463AC", "gray40"),
guide = "none") +
ggplot2::labs(
x = "Job type",
y = "Age in years"
)
```
Distribution of job type and age
:::
::::
:::::
###### jobs, age & sex
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-jobtype-age-sex}
: Distribution of jobtype by age and sex
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-jobtype-age-sex}
```{r}
#| label: eda-jobtype-age-sex
# plotting distribution of job type, age, and sex (Figure 11.6)
tbl11.2 |>
ggplot2::ggplot(
ggplot2::aes(
y = age,
x = job_cat,
fill = sex)
) +
ggplot2::geom_jitter(
ggplot2::aes(
color = sex
),
alpha = .6
) +
ggplot2::geom_boxplot(
ggplot2::aes(
fill = sex
),
alpha = .4) +
ggplot2::scale_fill_manual(
values = c("gray", "#7463AC"),
name = "Sex"
) +
ggplot2::scale_color_manual(
values = c("gray", "#7463AC"),
guide = "none") +
ggplot2::labs(
x = "Job type",
y = "Age in years"
)
```
Distribution of job type by age and sex
:::
::::
:::::
###### jobs by sex & age
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-jobtype-sex-age}
: Distribution by job type sex and age
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-jobtype-sex-age}
```{r}
#| label: eda-jobtype-sex-age
# plotting distribution of job type, sex, and age (Figure 11.7)
tbl11.2 |>
ggplot2::ggplot(
ggplot2::aes(
y = age,
x = job_cat)
) +
ggplot2::geom_jitter(
ggplot2::aes(
color = sex
),
alpha = .6
) +
ggplot2::geom_boxplot(
ggplot2::aes(
fill = sex
),
alpha = .4
) +
ggplot2::scale_fill_manual(
values = c("gray", "#7463AC"),
guide = "none"
) +
ggplot2::scale_color_manual(
values = c("gray", "#7463AC"),
guide = "none"
) +
ggplot2::labs(
x = "Job type",
y = "Age in years"
) +
ggplot2::facet_grid(cols = ggplot2::vars(sex))
```
Distribution by job type sex and age
:::
::::
:::::
:::
::::
:::::
***
::: {.callout #rep-chap11-visualizing-employment}
##### Summary of the several plots about employment
1. @lst-chap11-eda-sex-wihtin-jobtype: Computer science, math, and engineering have about a third as many females as males, other sciences and non-science were slightly more male than female.
2. @lst-chap11-eda-jobtype-sex: Computer science, math, and engineering jobs were the least common for females while this category was the largest for males.
3. @lst-chap11-eda-jobtype-age: While the age range for all the data appeared similar across the three job types, the computer science, math, and engineering field employed the youngest people on average.
4. @lst-chap11-eda-jobtype-age-sex: In all three fields, the distribution of age showed that males have an older median age than females, and in the two science fields, the range of age is wider for males than females.
5. @lst-chap11-eda-jobtype-sex-age: The lowest median age for females is in computer science, math, and engineering and higher in other sciences and non-science. The age distribution for males showed a similar pattern across the three job types. Computer science, math, and engineering has the youngest median age for both sexes.
:::
### Checking bivariate statistical associations
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap11-eda-bivariate-associations}
: Checking bivariate statistical associations between job type, sex, and age
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### age distribution
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-age-distribution}
: Age distribution by job type among 1,500 college graduates in 2017
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-age-distribution}
```{r}
#| label: eda-age-distribution
# plotting distribution of age (Figure 11.8)
tbl11.2 |>
ggplot2::ggplot(
ggplot2::aes(x = age)
) +
ggplot2::geom_histogram(
bins = 30,
fill = "#7463AC",
color = "white"
) +
ggplot2::labs(
x = "Age in years",
y = "Number of observations"
) +
ggplot2::facet_grid(cols = ggplot2::vars(job_cat))
```
Age distribution by job type among 1,500 college graduates in 2017
:::
***
The histograms were not normally distributed for any of the three groups.
::::
:::::
###### statistics
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-eda-statistics}
: Table of statistics to examine `job_cat`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-eda-statistics}
```{r}
#| label: eda-statistics
# make a table of statistics to examine job.cat
table_desc <- tableone::CreateTableOne(
data = tbl11.2,
strata = 'job_cat',
vars = c('sex', 'age')
)
base::print(table_desc,
showAllLevels = TRUE,
nonnormal = 'age'
)
```
Table of statistics to examine `job_cat`
:::
***
The visual differences in the graphs corresponded to statistically significant differences from the `r glossary("chi-squared")` and `r glossary("Kruskal-Wallis")` tests. The median age for college graduates in computer science, math, or engineering was 3 years lower than the median age in other sciences and 6 years younger than the median age in non-science careers. Computer science, math, and engineering has more than three times as many males as females.
::::
:::::
:::
::::
:::::
## Achievement 2: Estimating a multinomial logistic regression model {#sec-chap11-achievement2}
### Introduction
:::{.my-bulletbox}
:::: {.my-bulletbox-header}
::::: {.my-bulletbox-icon}
:::::
:::::: {#bul-chapp1-model-reporting}
::::::
: Important to report with every model
::::
:::: {.my-bulletbox-body}
- **Model significance**: Is the model significantly better than some baseline at explaining the outcome?
- **Model fit:** How well does the model capture the relationships in the underlying data?
- **Predictor values and significance**: What is the size, direction, and significance of the relationship between each predictor and the outcome?
- **Checking model assumptions**: Are the model assumptions met?
::::
:::
### Check reference groups
Before starting with the computation for the multinomial logistic regression it is practicable to check the reference groups with `base::levels()`. The results are easier to interpret if the reference groups (= the first level) is consistent with what one is interested in. Otherwise use `stats::relevel()` or one of the many functions in {**forcats**}, for instance `fct_recode()` or `fct_relevel()`.
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-check-levels}
: Check reference groups for regression
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-check-levels}
```{r}
#| label: check-levels
#| results: hold
base::levels(tbl11.2$job_cat)
base::levels(tbl11.2$sex)
```
Reference group for `job_cat` (= "CS, Math, Eng") and `sex` (= "Male")
:::
***
The reference group are fine; no change is necessary.
::::
:::::
### NHST Step 1
Write the null and alternate hypotheses:
::: {.callout-note}
- **H0**: A multinomial model including sex and age is not useful in explaining or predicting job type for college graduates.
- **HA**: A multinomial model including sex and age is useful in explaining or predicting job type for college graduates.
:::
### NHST Step 2
A Google search revealed the most of the R tutorials use the {**nnet**} package recommended also by `r glossary("SwR")`. A newer approach uses the meta-package {**tidymodel**} (similar to **tidyverse**) which collects 22 packages for modeling, containing {**parsnip**} with the `multinom_reg()` function that ca fit different classification models, including {**nnet**} as default package.
:::::: {#tdo-chap11-learn-tidymodels}
:::::{.my-checklist}
:::{.my-checklist-header}
TODO: Learn {**tidymodels**}
:::
::::{.my-checklist-container}
I already learned from the {**tidymodels**} approach three-four years ago. But at that time I thought that it is too advanced for my skill level. This has changed now. I have worked through all of the three pre-requisites mentioned on the [start page of tidymodels](https://www.tidymodels.org/start/). And now --- coming to the end of `r glossary("SwR")` --- I understand why this unification project is important.
::::
:::::
Learn [{**tidymodels**}](https://www.tidymodels.org/)
:::
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap11-multinom-computation}
: Computing a multinomial logical regression
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### model
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-estimate-multinomial-model}
: Estimate model and print summary
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-estimate-multinomial-model}
```{r}
#| label: estimate-multinomial-model
# estimate the model and print its summary
mnm11.1 <- nnet::multinom(
formula = job_cat ~ age + sex + age*sex,
data = tbl11.2,
model = TRUE)
save_data_file("chap11", mnm11.1, "mnm11.1.rds")
summary(object = mnm11.1)
```
Computing a multinomial regression model for job types by age and sex with interaction
:::
::::
:::::
###### null model
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-estimate-multinomial-null-model}
: Estimate null model
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-estimate-multinomial-null-model}
```{r}
#| label: estimate-multinomial-null-model
# multinomial null model
mnm11.0 <- nnet::multinom(
formula = job_cat ~ 1,
data = tbl11.2,
model = TRUE)
summary(object = mnm11.0)
```
Multinomial null model
:::
::::
:::::
###### test statistics
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-mnm-test-statistics}
: Compute test statistics for the multinomial model `mnm11.1`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-mnm-test-statistics}
```{r}
#| label: mnm-test-statistics
# get the job model chi-squared
job_chisq <- mnm11.0$deviance - mnm11.1$deviance
# get the degrees of freedom for chi-squared
job_df <- length(x = summary(object = mnm11.1)$coefficients) -
length(x = summary(object = mnm11.0)$coefficients)
# get the p-value for chi-squared
job_p <- stats::pchisq(
q = job_chisq,
df = job_df,
lower.tail = FALSE
)
# put together into a vector and round to 3 decimal places
model_sig <- base::round(x = c(job_chisq, job_df, job_p), 3)
# add names to the vector
base::names(x = model_sig) <- c("Chi-squared", "df", "p")
# print the vector
model_sig
```
Test statistics for the multinomial model
:::
::::
:::::
:::
::::
:::::
**Finishing step 2 of the NHST procedure:**
Compute the test statistics.
The test statistic is a chi-squared of 124.77 with 6 degrees of freedom.
### NHST Step 3
Review and interpret the test statistics:
Calculate the probability that your test statistic is at least as big as it is if there is no relationship (i.e., the null is true).
The probability computed for the chi-squared was < .001.
### NHST Step 4
Conclude and write report.
::: {.callout #rep-chap11-mnm11.1}
##### Report the conclusion of the interpretation of the multinomial model `mnm11.1`
We have to reject the null hypothesis and conclude that a model including age, sex, and age*sex explained job type statistically significantly better [$χ^2(6) = 124.77; p < .001$] than a null model with no predictors.
:::
### Multinomial model fit
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap11-mnm-fit}
: Multinomial model fit
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### fit & predict
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap11-show-fit-predict-values}
: Show `fitted.values` and `predict()` results
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap11-show-fit-predict-values}
```{r}
#| label: show-fit-predict-values
#| results: hold
df1 <- my_glance_data(data.frame(mnm11.1$fitted.values))
df2 <- my_glance_data(data.frame(predicted = stats::predict(mnm11.1)))
dplyr::full_join(df1, df2, by = dplyr::join_by(obs))
```
Random example rows of `fitted.values` to compare with the results from the `predict()` function