-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path29-tc-lta.Rmd
More file actions
2575 lines (2138 loc) · 85 KB
/
Copy path29-tc-lta.Rmd
File metadata and controls
2575 lines (2138 loc) · 85 KB
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
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
warning = FALSE,
message = FALSE) #Here, I have made it so that when you knit your .rmd, warnings and messages will not show up in the html markdown.
```
# The Importance of Early Attitudes Toward Mathematics and Science (Ing & Nylund-Gibson, 2017)
------------------------------------------------------------------------
This document presents a replication of the latent transition analysis (LTA) conducted by Ing and Nylund-Gibson, (2017), which investigated how students’ attitudes toward mathematics and science evolve over time and how those attitudinal trajectories relate to later academic outcomes. Using nationally representative longitudinal data from the LSAY study, we follow students from Grade 7 to Grade 12, classifying them into latent attitudinal profiles at each wave and modeling transitions between those profiles across time. This replication reproduces the authors’ manual 3-step LTA approach, including: (1) estimating an invariant unconditional model to identify latent profiles across grades; (2) using fixed logits to classify students into profiles at each wave; and (3) examining how class membership and transitions relate to distal outcomes and demographic covariates. Where applicable, we extend the original analysis by visualizing transition patterns, computing subgroup differences using z-tests, and formatting outputs for clear interpretability.
Citation: [Ing,M., & Nylund-Gibson, K. (2017). The importance of early attitudes toward mathematics and science. *Teachers College Record: The Voice of Scholarship in Education*, *119*(5), 1-32.](https://doi.org/10.1177/016146811711900507)
------------------------------------------------------------------------
## Load Packages
```{r}
library(tidyverse)
library(haven)
library(glue)
library(MplusAutomation)
library(here)
library(janitor)
library(gt)
library(cowplot)
library(DiagrammeR)
library(webshot2)
library(stringr)
library(flextable)
library(officer)
library(dplyr)
library(tidyr)
library(haven)
library(psych)
library(ggrepel)
library(PNWColors)
library(multcompView)
library(showtext)
showtext_auto()
```
------------------------------------------------------------------------
## Prepare Data
```{r}
lsay_data <- read_sav(here("tc_lta", "data", "Dataset_Jul9_Mplus.sav"))
# Filter to follow-up sample (target ~1824 rows)
lsay_data <- lsay_data %>% filter(RSTEMM %in% c(0, 1))
# Define survey questions
all_questions <- c(
"AB39A", "AB39H", "AB39I", "AB39K", "AB39L", "AB39M", "AB39T", "AB39U", "AB39W", "AB39X", # 7th grade
"GA32A", "GA32H", "GA32I", "GA32K", "GA32L", "GA33A", "GA33H", "GA33I", "GA33K", "GA33L", # 10th grade
"KA46A", "KA46H", "KA46I", "KA46K", "KA46L", "KA47A", "KA47H", "KA47I", "KA47K", "KA47L" # 12th grade
)
# Rename variables >8 characters
lsay_data <- lsay_data %>%
rename(
SCIG8 = ScienceG8,
SCIG11 = ScienceG11
)
# Recode 9999 to NA (missing)
lsay_data <- lsay_data %>%
mutate(across(all_of(all_questions), ~if_else(. == 9999, NA_real_, .)))
names(lsay_data) <- toupper(names(lsay_data))
```
------------------------------------------------------------------------
## Descriptive Statistics
### Create Table 1
This table provides the overall mean and standard deviation for each attitudinal item at Grades 7, 10, and 12. These values summarize general trends in the full sample and serve as a foundation for the latent class models that follow.
```{r}
# Function to compute stats (count, mean, SD)
compute_stats <- function(data, question, grade, question_name) {
data %>%
summarise(
Grade = grade,
Count = sum(!is.na(.data[[question]])),
Mean = mean(.data[[question]], na.rm = TRUE),
SD = sd(.data[[question]], na.rm = TRUE)
) %>%
mutate(Question = question_name)
}
# Define question names and mappings
table_setup <- tibble(
question_code = all_questions,
grade = rep(c(7, 10, 12), each = 10),
question_name = rep(
c(
"I enjoy math",
"Math is useful in everyday problems",
"Math helps a person think logically",
"It is important to know math to get a good job",
"I will use math in many ways as an adult",
"I enjoy science",
"Science is useful in everyday problems",
"Science helps a person think logically",
"It is important to know science to get a good job",
"I will use science in many ways as an adult"
),
times = 3
)
)
# Compute stats for all questions
table1_data <- pmap_dfr(
list(table_setup$question_code, table_setup$grade, table_setup$question_name),
~compute_stats(lsay_data, ..1, ..2, ..3)
) %>%
mutate(
Mean = round(Mean, 2),
SD = round(SD, 2)
) %>%
arrange(match(Question, table_setup$question_name), Grade) %>%
select(Question, Grade, Count, Mean, SD)
# Build table
table1_gt <- table1_data %>%
gt(groupname_col = "Question") %>%
tab_header(
title = "Table 1. Descriptive Statistics for Mathematics and Science Attitudinal Survey Items Included In Analyses"
) %>%
cols_label(
Grade = "Grade",
Count = "N",
Mean = "M",
SD = "SD"
) %>%
fmt_number(
columns = c(Mean, SD),
decimals = 2
)
# Show table
table1_gt
```
Save Table 1
```{r, eval = FALSE}
# Save table as PNG
gtsave(table1_gt, here("figures", "table1.png"))
```
------------------------------------------------------------------------
### Create Table 2
This table presents model fit statistics for latent profile enumeration at Grades 7, 10, and 12. For each grade, models with 1 through 6 profiles were estimated and evaluated using the commonly used information criteria (AIC, BIC, SSA-BIC), entropy, and likelihood ratio tests (LMR, BLRT). These values help determine the most appropriate number of latent profiles to retain at each grade.
```{r}
# Coerce to numeric just in case
lsay_data <- lsay_data %>%
mutate(
MATHG12 = as.numeric(MATHG12),
SCIG11 = as.numeric(SCIG11),
STEMSUP = as.numeric(STEMSUP)
)
# Build the summary table
table2_data <- tibble::tibble(
`Outcome Variable` = c(
"12th Grade Mathematics Achievement",
"11th Grade Science Achievement",
"STEM Career Attainmentᵃ"
),
N = c(
sum(lsay_data$MATHG12 != 9999 & !is.na(lsay_data$MATHG12)),
sum(lsay_data$SCIG11 != 9999 & !is.na(lsay_data$SCIG11)),
sum(lsay_data$STEMSUP != 9999 & !is.na(lsay_data$STEMSUP))
),
M = c(
round(mean(lsay_data$MATHG12[lsay_data$MATHG12 != 9999 & !is.na(lsay_data$MATHG12)]), 2),
round(mean(lsay_data$SCIG11[lsay_data$SCIG11 != 9999 & !is.na(lsay_data$SCIG11)]), 2),
round(mean(lsay_data$STEMSUP[lsay_data$STEMSUP != 9999 & !is.na(lsay_data$STEMSUP)]), 2)
),
SD = c(
round(sd(lsay_data$MATHG12[lsay_data$MATHG12 != 9999 & !is.na(lsay_data$MATHG12)]), 2),
round(sd(lsay_data$SCIG11[lsay_data$SCIG11 != 9999 & !is.na(lsay_data$SCIG11)]), 2),
NA
)
)
# Render the gt table
table2_gt <- table2_data %>%
gt() %>%
tab_header(
title = md("**Table 2. Descriptive Statistics for Distal Outcome Variables**")
) %>%
cols_label(
`Outcome Variable` = "Outcome Variable",
N = "N",
M = "M",
SD = "SD"
) %>%
sub_missing(columns = everything(), missing_text = "") %>%
tab_footnote(
footnote = "Binary indicator coded 1 = STEM occupation in mid-30s follow-up.",
locations = cells_body(rows = 3, columns = "Outcome Variable")
)
table2_gt
```
Save Table 2
```{r, eval = FALSE}
gtsave(
data = table2_gt,
filename = here("tc_lta","figures", "table2_distal_outcomes.png")
)
```
------------------------------------------------------------------------
## Run Independent LCAs for Each Timepoint
### Prepare Data for MPlusAutomation
To determine the appropriate number and structure of attitudinal profiles at each timepoint, we first estimate separate latent class models for Grades 7, 10, and 12. This step involves preparing the data in wide format and running independent LCAs using `MplusAutomation`. The goal is to identify the optimal number of latent profiles per grade based on model fit before moving to the longitudinal transition model.
### Run LCA on 7th Grade Items
```{r, eval = FALSE}
lca_belonging <- lapply(1:8, function(k) {
lca_enum <- mplusObject(
TITLE = glue("{k}-Class LCA for LSAY 7th Grade"),
VARIABLE = glue(
"categorical = AB39A AB39H AB39I AB39K AB39L AB39M AB39T AB39U AB39W AB39X;
usevar = AB39A AB39H AB39I AB39K AB39L AB39M AB39T AB39U AB39W AB39X;
missing = all(9999);
classes = c({k});"
),
ANALYSIS = "
estimator = mlr;
type = mixture;
starts = 500 10;
processors = 10;",
OUTPUT = "sampstat; residual; tech11; tech14;",
PLOT = "
type = plot3;
series = AB39A AB39H AB39I AB39K AB39L AB39M
AB39T AB39U AB39W AB39X(*);",
rdata = lsay_data
)
lca_enum_fit <- mplusModeler(
lca_enum,
dataout = glue(here("tc_lta","g7_enum", "lsay_g7.dat")),
modelout = glue(here("tc_lta","g7_enum", "c{k}_g7.inp")),
check = TRUE,
run = TRUE,
hashfilename = FALSE
)
})
```
### Run LCA on 10th Grade
```{r, eval = FALSE}
lca_belonging <- lapply(1:8, function(k) {
lca_enum <- mplusObject(
TITLE = glue("{k}-Class LCA for LCA 10th Grade"),
VARIABLE = glue(
"categorical = GA32A GA32H GA32I GA32K GA32L GA33A GA33H GA33I GA33K GA33L;
usevar = GA32A GA32H GA32I GA32K GA32L GA33A GA33H GA33I GA33K GA33L;
missing = all(9999);
classes = c({k});"
),
ANALYSIS = "
estimator = mlr;
type = mixture;
starts = 500 10;
processors = 10;",
OUTPUT = "sampstat; residual; tech11; tech14;",
PLOT = "
type = plot3;
series = GA32A GA32H GA32I GA32K GA32L GA33A
GA33H GA33I GA33K GA33L (*);",
rdata = lsay_data
)
lca_enum_fit <- mplusModeler(
lca_enum,
dataout = glue(here("tc_lta","g10_enum", "lsay_g10.dat")),
modelout = glue(here("tc_lta","g10_enum", "c{k}_g10.inp")),
check = TRUE,
run = TRUE,
hashfilename = FALSE
)
})
```
### Run LCA for 12th Grade
```{r, eval = FALSE}
lca_belonging <- lapply(1:8, function(k) {
lca_enum <- mplusObject(
TITLE = glue("{k}-Class LCA for LCA 12th Grade"),
VARIABLE = glue(
"categorical = KA46A KA46H KA46I KA46K KA46L KA47A KA47H KA47I KA47K KA47L;
usevar = KA46A KA46H KA46I KA46K KA46L KA47A KA47H KA47I KA47K KA47L;
missing = all(9999);
classes = c({k});"
),
ANALYSIS = "
estimator = mlr;
type = mixture;
starts = 500 10;
processors = 10;",
OUTPUT = "sampstat; residual; tech11; tech14;",
PLOT = "
type = plot3;
series = KA46A KA46H KA46I KA46K KA46L KA47A
KA47H KA47I KA47K KA47L (*);",
rdata = lsay_data
)
lca_enum_fit <- mplusModeler(
lca_enum,
dataout = glue(here("tc_lta","g12_enum", "lsay_g12.dat")),
modelout = glue(here("tc_lta","g12_enum", "c{k}_g12.inp")),
check = TRUE,
run = TRUE,
hashfilename = FALSE
)
})
```
Extract Mplus Information
```{r}
# LCA Extraction
source(here("tc_lta","functions", "extract_mplus_info.R"))
output_dir_lca <- here("tc_lta","enum")
output_files_lca <- list.files(output_dir_lca, pattern = "\\.out$", full.names = TRUE)
final_data_lca <- map_dfr(output_files_lca, extract_mplus_info_extended) %>%
mutate(Model_Type = "LCA")
```
------------------------------------------------------------------------
## Screen Output for Warnings, Errors, and Loglikelihood Replication
After estimating each LCA model, we examine the Mplus output files for warnings, estimation errors, and loglikelihood replication issues. This quality check helps ensure that solutions are trustworthy and that selected models are not based on local maxima or convergence failures. In this step, we flag any estimation concerns and verify that the best loglikelihood value is replicated consistently across random starts.
------------------------------------------------------------------------
Extract Warnings from Output Files
```{r}
source(here("tc_lta","functions", "extract_mplus_info.R"))
# Extract 7th grade LCAs
output_dir_g7 <- here("tc_lta","g7_enum")
output_files_g7 <- list.files(output_dir_g7, pattern = "\\.out$", full.names = TRUE)
final_data_g7 <- map_dfr(output_files_g7, extract_mplus_info_extended) %>%
mutate(Model_Type = "LCA", Grade = "7th")
# Extract 10th grade LCAs
output_dir_g10 <- here("tc_lta","g10_enum")
output_files_g10 <- list.files(output_dir_g10, pattern = "\\.out$", full.names = TRUE)
final_data_g10 <- map_dfr(output_files_g10, extract_mplus_info_extended) %>%
mutate(Model_Type = "LCA", Grade = "10th")
# Extract 12th grade LCAs
output_dir_g12 <- here("tc_lta","g12_enum")
output_files_g12 <- list.files(output_dir_g12, pattern = "\\.out$", full.names = TRUE)
final_data_g12 <- map_dfr(output_files_g12, extract_mplus_info_extended) %>%
mutate(Model_Type = "LCA", Grade = "12th")
```
### Examine Output Warnings
```{r}
source(here("tc_lta","functions", "extract_warnings.R"))
# ---- 7th Grade ----
warnings_g7 <- extract_warnings(final_data_g7) %>%
left_join(select(final_data_g7, File_Name), by = "File_Name")
warnings_table_g7 <- warnings_g7 %>%
gt() %>%
tab_header(title = md("**Model Warnings — 7th Grade LCA**")) %>%
cols_label(
File_Name = "Output File",
Warning_Summary = "# of Warnings",
Warnings = "Warning Message(s)"
) %>%
cols_align(align = "left", columns = everything()) %>%
cols_width(
File_Name ~ px(150),
Warning_Summary ~ px(150),
Warnings ~ px(400)
) %>%
tab_options(table.width = pct(100))
# ---- 10th Grade ----
warnings_g10 <- extract_warnings(final_data_g10) %>%
left_join(select(final_data_g10, File_Name), by = "File_Name")
warnings_table_g10 <- warnings_g10 %>%
gt() %>%
tab_header(title = md("**Model Warnings — 10th Grade LCA**")) %>%
cols_label(
File_Name = "Output File",
Warning_Summary = "# of Warnings",
Warnings = "Warning Message(s)"
) %>%
cols_align(align = "left", columns = everything()) %>%
cols_width(
File_Name ~ px(150),
Warning_Summary ~ px(150),
Warnings ~ px(400)
) %>%
tab_options(table.width = pct(100))
# ---- 12th Grade ----
warnings_g12 <- extract_warnings(final_data_g12) %>%
left_join(select(final_data_g12, File_Name), by = "File_Name")
warnings_table_g12 <- warnings_g12 %>%
gt() %>%
tab_header(title = md("**Model Warnings — 12th Grade LCA**")) %>%
cols_label(
File_Name = "Output File",
Warning_Summary = "# of Warnings",
Warnings = "Warning Message(s)"
) %>%
cols_align(align = "left", columns = everything()) %>%
cols_width(
File_Name ~ px(150),
Warning_Summary ~ px(150),
Warnings ~ px(400)
) %>%
tab_options(table.width = pct(100))
# Print all three
warnings_table_g7
warnings_table_g10
warnings_table_g12
```
Save Warning Tables
```{r, eval = FALSE}
gtsave(warnings_table_g7, filename = here("tc_lta","figures", "warnings_g7_lca.png"))
gtsave(warnings_table_g10, filename = here("tc_lta","figures", "warnings_g10_lca.png"))
gtsave(warnings_table_g12, filename = here("tc_lta","figures", "warnings_g12_lca.png"))
```
Extract Errors from Output Files
```{r}
source(here("tc_lta","functions", "error_visualization.R"))
# ---- 7th Grade Errors ----
error_table_g7 <- process_error_data(final_data_g7)
# ---- 10th Grade Errors ----
error_table_g10 <- process_error_data(final_data_g10)
# ---- 12th Grade Errors ----
error_table_g12 <- process_error_data(final_data_g12)
```
### Examine Errors
```{r}
# Helper to conditionally render or notify
render_error_table <- function(error_df, grade_label) {
if (nrow(error_df) > 0) {
error_df %>%
gt() %>%
tab_header(title = md(glue("**Model Estimation Errors — {grade_label} Grade**"))) %>%
cols_label(
File_Name = "Output File",
Class_Model = "Model Type",
Error_Message = "Error Message"
) %>%
cols_align(align = "left", columns = everything()) %>%
cols_width(
File_Name ~ px(150),
Class_Model ~ px(100),
Error_Message ~ px(400)
) %>%
tab_options(table.width = px(600)) %>%
fmt(
columns = "Error_Message",
fns = function(x) gsub("\n", "<br>", x)
)
} else {
cat(glue("✅ No errors detected for {grade_label} Grade.\n"))
}
}
# Print or notify for each grade
render_error_table(error_table_g7, "7th")
render_error_table(error_table_g10, "10th")
render_error_table(error_table_g12, "12th")
```
Save Error Tables
```{r, eval = FALSE}
if (exists("error_table_g7") && nrow(error_table_g7) > 0) {
gtsave(render_error_table(error_table_g7, "7th"), here("tc_lta","figures", "errors_g7_lca.png"))
}
if (exists("error_table_g10") && nrow(error_table_g10) > 0) {
gtsave(render_error_table(error_table_g10, "10th"), here("tc_lta","figures", "errors_g10_lca.png"))
}
if (exists("error_table_g12") && nrow(error_table_g12) > 0) {
gtsave(render_error_table(error_table_g12, "12th"), here("tc_lta","figures", "errors_g12_lca.png"))
}
```
### Examine Convergence Information
```{r, results='asis', out.width="95%"}
# Load function
source(here("tc_lta","functions", "summary_table.R"))
# Helper: clean + prep for each dataset
prepare_convergence_table <- function(data_object, grade_label) {
sample_size <- data_object$Sample_Size[1]
data_flat <- data_object %>%
select(-LogLikelihoods, -Errors, -Warnings) %>%
mutate(across(
c(
Best_LogLikelihood,
Perc_Convergence,
Replicated_LL_Perc,
Smallest_Class_Perc,
Condition_Number
),
~ as.numeric(gsub(",", "", .))
))
tbl <- create_flextable(data_flat, sample_size)
# Get actual number of columns in the flextable object
n_cols <- length(tbl$body$col_keys)
# Title string
title_text <- glue("LCA Convergence Table — {grade_label} Grade (N = {sample_size})")
# This is the correct call: title as one string, colwidth = full span
tbl <- add_header_row(
tbl,
values = title_text,
colwidths = n_cols
) %>%
align(i = 1, align = "center", part = "header") %>%
fontsize(i = 1, size = 12, part = "header") %>%
bg(i = 1, bg = "#ffffff", part = "header")
return(tbl)
}
# Create tables
summary_table_g7 <- prepare_convergence_table(final_data_g7, "7th")
summary_table_g10 <- prepare_convergence_table(final_data_g10, "10th")
summary_table_g12 <- prepare_convergence_table(final_data_g12, "12th")
summary_table_g7
summary_table_g10
summary_table_g12
```
Save Convergence Tables
```{r, eval = FALSE}
# Save convergence tables as PNGs
invisible(save_as_image(summary_table_g7, path = here("tc_lta","figures", "convergence_g7_lca.png")))
invisible(save_as_image(summary_table_g10, path = here("tc_lta","figures", "convergence_g10_lca.png")))
invisible(save_as_image(summary_table_g12, path = here("tc_lta","figures", "convergence_g12_lca.png")))
```
Scrape Replication Data
```{r}
# Load the function file containing generate_ll_replication_plots and create_ll_replication_table_all
source(here("tc_lta","functions", "ll_replication_plots.R"))
# Load the second function from ll_replication_processing.R
source(here("tc_lta","functions", "ll_replication_processing.R"))
```
### Examine Loglikelihood Replication Information
```{r}
# Generate replication plots (invisible, for diagnostic use)
ll_replication_tables_g7 <- generate_ll_replication_plots(final_data_g7)
ll_replication_tables_g10 <- generate_ll_replication_plots(final_data_g10)
ll_replication_tables_g12 <- generate_ll_replication_plots(final_data_g12)
# Create replication tables
ll_replication_table_g7 <- create_ll_replication_table_all(final_data_g7)
ll_replication_table_g10 <- create_ll_replication_table_all(final_data_g10)
ll_replication_table_g12 <- create_ll_replication_table_all(final_data_g12)
# Add visible title row to each table
ll_replication_table_g7 <- add_header_row(
ll_replication_table_g7,
values = "Log-Likelihood Replication Table — 7th Grade LCA",
colwidths = ncol(ll_replication_table_g7$body$dataset)
) %>%
align(i = 1, align = "center", part = "header") %>%
fontsize(i = 1, size = 12, part = "header") %>%
bg(i = 1, bg = "#ffffff", part = "header")
ll_replication_table_g10 <- add_header_row(
ll_replication_table_g10,
values = "Log-Likelihood Replication Table — 10th Grade LCA",
colwidths = ncol(ll_replication_table_g10$body$dataset)
) %>%
align(i = 1, align = "center", part = "header") %>%
fontsize(i = 1, size = 12, part = "header") %>%
bg(i = 1, bg = "#ffffff", part = "header")
ll_replication_table_g12 <- add_header_row(
ll_replication_table_g12,
values = "Log-Likelihood Replication Table — 12th Grade LCA",
colwidths = ncol(ll_replication_table_g12$body$dataset)
) %>%
align(i = 1, align = "center", part = "header") %>%
fontsize(i = 1, size = 12, part = "header") %>%
bg(i = 1, bg = "#ffffff", part = "header")
# Display the three titled tables
ll_replication_table_g7
ll_replication_table_g10
ll_replication_table_g12
```
Save LL Replication Tables
```{r, eval = FALSE}
invisible({
flextable::save_as_image(ll_replication_table_g7, path = here::here("tc_lta","figures", "ll_replication_table_g7.png"))
flextable::save_as_image(ll_replication_table_g10, path = here::here("tc_lta","figures", "ll_replication_table_g10.png"))
flextable::save_as_image(ll_replication_table_g12, path = here::here("tc_lta","figures", "ll_replication_table_g12.png"))
})
```
------------------------------------------------------------------------
## Examine Model Fit for Optimal Solution
We evaluate model fit for each grade-level LCA to identify the optimal number of latent profiles. Fit statistics such as BIC, entropy, and likelihood ratio tests (LMR and BLRT) are compared across models. The goal is to select the most parsimonious solution that provides clear separation between classes and replicates reliably. These selections will form the basis for the longitudinal model in the next stage.
------------------------------------------------------------------------
Extract fit statistics
```{r}
# Define grade-specific folders and data
grades <- c("g7", "g10", "g12")
folder_paths <- c(
g7 = here("tc_lta","g7_enum"),
g10 = here("tc_lta","g10_enum"),
g12 = here("tc_lta","g12_enum")
)
final_data_list <- list(
g7 = final_data_g7,
g10 = final_data_g10,
g12 = final_data_g12
)
# Initialize storage
output_models_all <- list()
allFit_list <- list()
# Process each grade
for (grade in grades) {
# Get all .out files (1-8 classes)
out_files <- list.files(folder_paths[grade], pattern = "^c[1-8]_g\\d+\\.out$", full.names = TRUE)
# Read Mplus output files
output_models <- list()
for (file in out_files) {
model <- readModels(file, quiet = TRUE)
if (!is.null(model) && length(model) > 0) {
output_models[[basename(file)]] <- model
}
}
# Store models
output_models_all[[grade]] <- output_models
# Extract summary table
model_extract <- LatexSummaryTable(
output_models,
keepCols = c("Title", "Parameters", "LL", "BIC", "aBIC", "T11_VLMR_PValue", "BLRT_PValue", "Observations", "Entropy"),
sortBy = "Title"
)
# Compute additional fit indices
allFit <- model_extract %>%
mutate(
Title = str_trim(Title),
Grade = toupper(grade),
Classes = as.integer(str_extract(Title, "\\d+")), # Extract class number
File_Name = names(output_models),
CAIC = -2 * LL + Parameters * (log(Observations) + 1),
AWE = -2 * LL + 2 * Parameters * (log(Observations) + 1.5),
SIC = -0.5 * BIC,
expSIC = exp(SIC - max(SIC, na.rm = TRUE)),
BF = if_else(is.na(lead(SIC)), NA_real_, exp(SIC - lead(SIC))),
cmPk = expSIC / sum(expSIC, na.rm = TRUE)
) %>%
arrange(Classes)
# Clean Class_Model for joining
final_data_clean <- final_data_list[[grade]] %>%
mutate(
Classes = as.integer(str_extract(Class_Model, "\\d+"))
) %>%
select(Class_Model, Classes, Perc_Convergence, Replicated_LL_Perc, Smallest_Class, Smallest_Class_Perc)
# Merge with final_data
allFit <- allFit %>%
left_join(
final_data_clean,
by = "Classes"
) %>%
mutate(
Smallest_Class_Combined = paste0(Smallest_Class, "\u00A0(", Smallest_Class_Perc, "%)")
) %>%
relocate(Grade, Classes, Parameters, LL, Perc_Convergence, Replicated_LL_Perc, .before = BIC) %>%
select(
Grade, Classes, Parameters, LL, Perc_Convergence, Replicated_LL_Perc,
BIC, aBIC, CAIC, AWE, T11_VLMR_PValue, BLRT_PValue, Entropy, Smallest_Class_Combined, BF, cmPk
)
# Store fit data
allFit_list[[grade]] <- allFit
}
# Combine fit data
allFit_combined <- bind_rows(allFit_list) %>%
arrange(Grade, Classes)
```
### Examine Fit Statistics
```{r, results='asis', out.width="95%"}
# Initialize list to store tables
fit_tables <- list()
# Create and render table for each grade
for (grade in grades) {
# Filter data for current grade
allFit_grade <- allFit_combined %>%
filter(Grade == toupper(grade)) %>%
select(-Perc_Convergence, -Replicated_LL_Perc) # Exclude convergence columns
# Create table
fit_table <- allFit_grade %>%
gt() %>%
tab_header(title = md(sprintf("**Model Fit Summary Table for %s Grade**", toupper(grade)))) %>%
tab_spanner(label = "Model Fit Indices", columns = c(BIC, aBIC, CAIC, AWE)) %>%
tab_spanner(label = "LRTs", columns = c(T11_VLMR_PValue, BLRT_PValue)) %>%
tab_spanner(label = md("Smallest\u00A0Class"), columns = c(Smallest_Class_Combined)) %>%
cols_label(
Grade = "Grade",
Classes = "Classes",
Parameters = md("npar"),
LL = md("*LL*"),
# Perc_Convergence = "% Converged", # Commented out
# Replicated_LL_Perc = "% Replicated", # Commented out
BIC = "BIC",
aBIC = "aBIC",
CAIC = "CAIC",
AWE = "AWE",
T11_VLMR_PValue = "VLMR",
BLRT_PValue = "BLRT",
Entropy = "Entropy",
Smallest_Class_Combined = "n (%)",
BF = "BF",
cmPk = "cmPk"
) %>%
tab_footnote(
footnote = md(
"*Note.* npar = Parameters; *LL* = model log likelihood;
BIC = Bayesian information criterion;
aBIC = sample size adjusted BIC; CAIC = consistent Akaike information criterion;
AWE = approximate weight of evidence criterion;
BLRT = bootstrapped likelihood ratio test p-value;
VLMR = Vuong-Lo-Mendell-Rubin adjusted likelihood ratio test p-value;
Smallest n (%) = Number of cases in the smallest class."
),
locations = cells_title()
) %>%
tab_options(column_labels.font.weight = "bold") %>%
fmt_number(
columns = c(LL, BIC, aBIC, CAIC, AWE, Entropy, BF, cmPk),
decimals = 2
) %>%
fmt(
columns = c(T11_VLMR_PValue, BLRT_PValue),
fns = function(x) ifelse(is.na(x), "—", ifelse(x < 0.001, "<.001", scales::number(x, accuracy = .01)))
) %>%
cols_align(align = "center", columns = everything()) %>%
tab_style(
style = list(cell_text(weight = "bold")),
locations = list(
cells_body(columns = BIC, rows = BIC == min(BIC)),
cells_body(columns = aBIC, rows = aBIC == min(aBIC)),
cells_body(columns = CAIC, rows = CAIC == min(CAIC)),
cells_body(columns = AWE, rows = AWE == min(AWE)),
cells_body(
columns = T11_VLMR_PValue,
rows = T11_VLMR_PValue < .05 & lead(T11_VLMR_PValue, default = 1) > .05
),
cells_body(
columns = BLRT_PValue,
rows = BLRT_PValue < .05 & lead(BLRT_PValue, default = 1) > .05
)
)
)
# Store table
fit_tables[[grade]] <- fit_table
# Render table without markdown header
# cat(sprintf("\n### LCA Fit Table for %s Grade\n", toupper(grade))) # Commented out to avoid markdown headers
print(fit_table)
}
```
Save Fit Tables
```{r, eval = FALSE}
# Save tables as PNG files
gtsave(fit_tables[["g7"]], filename = here("tc_lta","figures", "fit_table_lca_g7.png"))
gtsave(fit_tables[["g10"]], filename = here("tc_lta","figures", "fit_table_lca_g10.png"))
gtsave(fit_tables[["g12"]], filename = here("tc_lta","figures", "fit_table_lca_g12.png"))
```
------------------------------------------------------------------------
## Create and Examine Probability Plots for Four Class Solution
To aid in interpretation, we visualize the conditional response probabilities for the selected four-class solution at each grade. These plots show the probability of endorsing each response category within each latent profile and help clarify how the classes
```{r, results='asis', out.width="95%"}
# Source plot_lca function
source(here("tc_lta","functions", "plot_lca.txt"))
# Define grades and folders
grades <- c("g7", "g10", "g12")
folder_paths <- c(
g7 = here("tc_lta","g7_enum"),
g10 = here("tc_lta","g10_enum"),
g12 = here("tc_lta","g12_enum")
)
# Generate plot for each grade
for (grade in grades) {
# Read 4-class model
model_file <- file.path(folder_paths[grade], paste0("c4_", grade, ".out"))
model <- readModels(model_file, quiet = TRUE)
# Base plot
base_plot <- plot_lca(model_name = model)
# Get class sizes and round to 1 decimal
c_size <- round(model$class_counts$modelEstimated$proportion * 100, 1)
# Customize plot with generic class labels
final_plot <- base_plot +
scale_colour_discrete(labels = c(
glue("Class 1 ({c_size[1]}%)"),
glue("Class 2 ({c_size[2]}%)"),
glue("Class 3 ({c_size[3]}%)"),
glue("Class 4 ({c_size[4]}%)")
)) +
scale_shape_discrete(labels = c(
glue("Class 1 ({c_size[1]}%)"),
glue("Class 2 ({c_size[2]}%)"),
glue("Class 3 ({c_size[3]}%)"),
glue("Class 4 ({c_size[4]}%)")
)) +
scale_linetype_discrete(labels = c(
glue("Class 1 ({c_size[1]}%)"),
glue("Class 2 ({c_size[2]}%)"),
glue("Class 3 ({c_size[3]}%)"),
glue("Class 4 ({c_size[4]}%)")
)) +
labs(title = glue("4-Class LCA Item Probability Plot for Grade {toupper(grade)}"))
# Display plot
print(final_plot)
}
```
------------------------------------------------------------------------
## Conduct step 1: Invariant Latent Transition Analysis
In Step 1 of the latent transition analysis (LTA), we estimate an unconditional longitudinal model with measurement invariance across timepoints. This means that item-response thresholds are constrained to be equal across Grades 7, 10, and 12, allowing us to interpret latent class transitions over time on a consistent measurement scale. This step provides the foundation for the 3-step approach by establishing a stable class structure across waves.
```{r, eval = FALSE}
# Define LTA model
lta_model <- mplusObject(
TITLE = "4-Class LTA for G7, G10, G12",
VARIABLE = glue(
"categorical = AB39A AB39H AB39I AB39K AB39L AB39M AB39T AB39U AB39W AB39X
GA32A GA32H GA32I GA32K GA32L GA33A GA33H GA33I GA33K GA33L
KA46A KA46H KA46I KA46K KA46L KA47A KA47H KA47I KA47K KA47L;
usevar = AB39A AB39H AB39I AB39K AB39L AB39M AB39T AB39U AB39W AB39X
GA32A GA32H GA32I GA32K GA32L GA33A GA33H GA33I GA33K GA33L
KA46A KA46H KA46I KA46K KA46L KA47A KA47H KA47I KA47K KA47L
FEMALE MINORITY STEM STEMSUP ENGINEER MATHG8 SCIG8 MATHG11 SCIG11
MATHG7 MATHG10 MATHG12;
auxiliary = FEMALE MINORITY STEM STEMSUP ENGINEER MATHG8 SCIG8 MATHG11 SCIG11
MATHG7 MATHG10 MATHG12;
missing = all(9999);
classes = c1(4) c2(4) c3(4);
auxiliary = stem;"
),
ANALYSIS = "
estimator = mlr;
type = mixture;
starts = 500 10;
processors = 4;",
MODEL = glue(
"%overall%
c2 on c1;
c3 on c2;
MODEL c1:
%c1#1%
[AB39A$1-AB39X$1] (1-10);