/
bruceR-stats_5_advance.R
2256 lines (2151 loc) 路 80.7 KB
/
bruceR-stats_5_advance.R
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
#### PROCESS Macro (GLM and HLM) ####
interaction_F_test = function(model, data=NULL, data.name="data") {
Run("{data.name} = data")
df2 = df.residual(model)
interms = attr(terms(model), "term.labels")
interms = interms[grepl(":", interms)]
interms.form = as.formula(paste("~", paste(interms, collapse=" + ")))
interms.drop = as.formula(paste(". ~ . -", paste(interms, collapse=" - ")))
if(inherits(model, "lm")) {
dp1 = drop1(model, scope=interms.form, test="F")
dp1 = dp1[!is.na(dp1$Df), c("Df", "F value", "Pr(>F)")]
aov = anova(update(model, interms.drop), model)
if(df2!=aov[2, "Res.Df"]) warning("Error!", call.=TRUE)
aov.table = data.frame(
`F` = c(dp1[[2]], aov[2, "F"]),
df1 = c(dp1[[1]], aov[2, "Df"]),
df2 = df2,
pval = c(dp1[[3]], aov[2, "Pr(>F)"]))
row.names(aov.table) = c(gsub(":", " * ", row.names(dp1)),
"(All Interactions)")
} else {
# dp1 = drop1(model, scope=interms, test="F")
dp1 = anova(model)[interms,]
aov.table = data.frame(
`F` = dp1[,"F value"],
df1 = dp1[,"NumDF"],
df2 = dp1[,"DenDF"],
pval = dp1[,"Pr(>F)"])
row.names(aov.table) = gsub(":", " * ", row.names(dp1))
}
return(aov.table)
}
interaction_Chi2_test = function(model, data=NULL, data.name="data") {
Run("{data.name} = data")
interms = attr(terms(model), "term.labels")
interms = interms[grepl(":", interms)]
interms.form = as.formula(paste("~", paste(interms, collapse=" + ")))
interms.drop = as.formula(paste(". ~ . -", paste(interms, collapse=" - ")))
if(inherits(model, "glm")) {
dp1 = drop1(model, scope=interms.form, test="Chisq")
dp1 = dp1[!is.na(dp1$Df), c("Df", "LRT", "Pr(>Chi)")]
chi = anova(update(model, interms.drop), model, test="Chisq")
chi.table = data.frame(
`Chisq` = c(dp1[[2]], chi[2, "Deviance"]),
df = c(dp1[[1]], chi[2, "Df"]),
pval = c(dp1[[3]], chi[2, "Pr(>Chi)"]))
row.names(chi.table) = c(gsub(":", " * ", row.names(dp1)),
"(All Interactions)")
} else {
dp1 = drop1(model, scope=interms.form, test="Chisq")
dp1 = dp1[!is.na(dp1$npar), c("npar", "LRT", "Pr(Chi)")]
chi.table = data.frame(
Chisq = dp1[,"LRT"],
df = dp1[,"npar"],
pval = dp1[,"Pr(Chi)"])
row.names(chi.table) = gsub(":", " * ", row.names(dp1))
}
return(chi.table)
}
interaction_test = function(model, data=NULL, data.name="data") {
if(inherits(model, c("glm", "glmerMod"))) {
table = interaction_Chi2_test(model, data=data, data.name=data.name)
} else {
table = interaction_F_test(model, data=data, data.name=data.name)
}
return(table)
}
lav_med_modeler = function(y, x,
meds=c(),
covs=c(),
med.type=c("parallel", "serial"),
cov.path=c("y", "m", "both")) {
ids = 1:length(meds)
if(length(med.type)>1) med.type = "parallel"
if(length(meds)==1) {
fm = meds %^% " ~ a*" %^% x
fy = y %^% " ~ c.*"%^% x %^% " + " %^% "b*" %^% meds
pars = paste(
"Indirect := a*b",
"Direct := c.",
"Total := c. + a*b",
sep="\n")
} else {
if(grepl("p", med.type)) {
x.all = "a" %^% ids %^% "*" %^% x
meds.all = paste("b" %^% ids %^% "*" %^% meds, collapse=" + ")
ind = "Indirect_X_M" %^% ids %^% "_Y := " %^% "a" %^% ids %^% "*" %^% "b" %^% ids
fm = meds %^% " ~ " %^% x.all
fy = y %^% " ~ c.*"%^% x %^% " + " %^% meds.all
ind.all = paste("a" %^% ids %^% "*" %^% "b" %^% ids, collapse=" + ")
pars = paste(
"Indirect_All := " %^% ind.all,
paste(ind, collapse="\n"),
"Direct := c.",
"Total := c. + " %^% ind.all,
sep="\n")
}
if(grepl("s", med.type)) {
x.all = "a" %^% 1:length(meds) %^% "*" %^% x
meds.all = paste("b" %^% ids %^% "*" %^% meds, collapse=" + ")
fm = meds %^% " ~ " %^% x.all
for(mi in 2:length(meds)) {
fm[mi] = fm[mi] %^% " + " %^%
paste("d" %^% ids[1:(mi-1)] %^% ids[mi] %^% "*" %^%
meds[1:(mi-1)], collapse=" + ")
}
fy = y %^% " ~ c.*"%^% x %^% " + " %^% meds.all
if(length(meds)==2) {
ind.all = "a1*b1 + a2*b2 + a1*d12*b2"
pars = Glue("
Indirect_All := {ind.all}
Ind_X_M1_Y := a1*b1
Ind_X_M2_Y := a2*b2
Ind_X_M1_M2_Y := a1*d12*b2
Direct := c.
Total := c. + {ind.all}
")
}
if(length(meds)==3) {
ind.all = paste(
"a1*b1",
"a2*b2",
"a3*b3",
"a1*d12*b2",
"a1*d13*b3",
"a2*d23*b3",
"a1*d12*d23*b3",
sep=" + ")
pars=Glue("
Indirect_All := {ind.all}
Ind_X_M1_Y := a1*b1
Ind_X_M2_Y := a2*b2
Ind_X_M3_Y := a3*b3
Ind_X_M1_M2_Y := a1*d12*b2
Ind_X_M1_M3_Y := a1*d13*b3
Ind_X_M2_M3_Y := a2*d23*b3
Ind_X_M1_M2_M3_Y := a1*d12*d23*b3
Direct := c.
Total := c. + {ind.all}
")
}
if(length(meds)==4) {
ind.all = paste(
"a1*b1",
"a2*b2",
"a3*b3",
"a4*b4",
"a1*d12*b2",
"a1*d13*b3",
"a1*d14*b4",
"a2*d23*b3",
"a2*d24*b4",
"a3*d34*b4",
"a1*d12*d23*b3",
"a1*d12*d24*b4",
"a1*d13*d34*b4",
"a2*d23*d34*b4",
"a1*d12*d23*d34*b4",
sep=" + ")
pars=Glue("
Indirect_All := {ind.all}
Ind_X_M1_Y := a1*b1
Ind_X_M2_Y := a2*b2
Ind_X_M3_Y := a3*b3
Ind_X_M4_Y := a4*b4
Ind_X_M1_M2_Y := a1*d12*b2
Ind_X_M1_M3_Y := a1*d13*b3
Ind_X_M1_M4_Y := a1*d14*b4
Ind_X_M2_M3_Y := a2*d23*b3
Ind_X_M2_M4_Y := a2*d24*b4
Ind_X_M3_M4_Y := a3*d34*b4
Ind_X_M1_M2_M3_Y := a1*d12*d23*b3
Ind_X_M1_M2_M4_Y := a1*d12*d24*b4
Ind_X_M1_M3_M4_Y := a1*d13*d34*b4
Ind_X_M2_M3_M4_Y := a2*d23*d34*b4
Ind_X_M1_M2_M3_M4_Y := a1*d12*d23*d34*b4
Direct := c.
Total := c. + {ind.all}
")
}
}
}
if(length(covs)>0)
covs.all = " " %^% paste(covs, collapse=" + ") %^% " +"
else
covs.all = ""
if("m" %in% cov.path)
fm = str_replace(fm, "~", "~" %^% covs.all)
if("y" %in% cov.path)
fy = str_replace(fy, "~", "~" %^% covs.all)
model = paste(paste(fm, collapse="\n"),
fy, pars,
sep="\n")
return(model)
}
# edit(mediation::mediate)
# edit(boot::boot.ci)
# edit(boot:::perc.ci)
# edit(boot:::bca.ci)
boot_ci = function(boot,
type=c("boot", "bc.boot", "bca.boot", "mcmc"),
true=NULL,
conf=0.95) {
low = (1 - conf) / 2
high = 1 - low
if(length(type)>1) type = "boot"
if(type %in% c("boot", "mcmc")) {
ci = quantile(boot, c(low, high), na.rm=TRUE) # percentile
} else {
if(is.null(true)) boot0 = mean(boot) else boot0 = true
p0 = length(boot[boot<boot0]) / length(boot)
z0 = qnorm(p0)
z.l = qnorm(low)
z.h = qnorm(high)
if(type=="bca.boot") {
U = (length(boot) - 1) * (boot0 - boot)
a = sum(U^3) / (6 * (sum(U^2))^1.5) # accelerated bias-corrected
} else {
a = 0 # bias-corrected
}
lower.bc = pnorm(z0 + (z0+z.l) / (1 - a*(z0+z.l)))
upper.bc = pnorm(z0 + (z0+z.h) / (1 - a*(z0+z.h)))
ci = quantile(boot, c(lower.bc, upper.bc), na.rm=TRUE)
}
return(ci)
}
#' PROCESS for mediation and/or moderation analyses.
#'
#' @description
#' To perform mediation, moderation, and conditional process (moderated mediation) analyses,
#' people may use software like
#' \href{http://www.statmodel.com/index.shtml}{Mplus},
#' \href{https://www.processmacro.org/index.html}{SPSS "PROCESS" macro},
#' and \href{https://njrockwood.com/mlmed/}{SPSS "MLmed" macro}.
#' Some R packages can also perform such analyses separately and in a complex way, including
#' \link[mediation:mediate]{R package "mediation"},
#' \link[interactions:sim_slopes]{R package "interactions"},
#' and \link[lavaan:lavaan-class]{R package "lavaan"}.
#' Some other R packages or scripts/modules have been further developed to improve the convenience, including
#' \href{https://jamovi-amm.github.io/}{jamovi module "jAMM"} (by \emph{Marcello Gallucci}, based on the \code{lavaan} package),
#' \href{https://CRAN.R-project.org/package=processR}{R package "processR"} (by \emph{Keon-Woong Moon}, not official, also based on the \code{lavaan} package),
#' and \href{https://www.processmacro.org/download.html}{R script file "process.R"}
#' (the official PROCESS R code by \emph{Andrew F. Hayes}, but it is not yet an R package and has some bugs and limitations).
#'
#' Here, the \code{\link[bruceR:PROCESS]{bruceR::PROCESS()}} function provides
#' an alternative to performing mediation/moderation analyses in R.
#' This function supports a total of \strong{24} kinds of SPSS PROCESS models (Hayes, 2018)
#' and also supports multilevel mediation/moderation analyses.
#' Overall, it supports the most frequently used types of mediation, moderation,
#' moderated moderation (3-way interaction), and moderated mediation (conditional indirect effect) analyses
#' for \strong{(generalized) linear or linear mixed models}.
#'
#' Specifically, the \code{\link[bruceR:PROCESS]{bruceR::PROCESS()}} function
#' fits regression models based on the data, variable names, and a few other arguments
#' that users input (with \strong{no need to} specify the PROCESS model number and \strong{no need to} manually mean-center the variables).
#' The function can automatically judge the model number/type and also conduct grand-mean centering before model building
#' (using the \code{\link[bruceR:grand_mean_center]{bruceR::grand_mean_center()}} function).
#'
#' This automatic grand-mean centering can be turned off by setting \code{center=FALSE}.
#'
#' Note that this automatic grand-mean centering
#' (1) makes the results of main effects accurate for interpretation;
#' (2) does not change any results of model fit (it only affects the interpretation of main effects);
#' (3) is only conducted in "PART 1" (for an accurate estimate of main effects) but not in "PART 2" because
#' it is more intuitive and interpretable to use the raw values of variables for the simple-slope tests in "PART 2";
#' (4) is not optional to users because mean-centering should always be done when there is an interaction;
#' (5) is not conflicted with group-mean centering because after group-mean centering the grand mean of a variable will also be 0,
#' such that the automatic grand-mean centering (with mean = 0) will not change any values of the variable.
#'
#' If you need to do group-mean centering, please do this before using PROCESS.
#' \code{\link[bruceR:group_mean_center]{bruceR::group_mean_center()}} is a useful function of group-mean centering.
#' Remember that the automatic grand-mean centering in PROCESS never affects the values of a group-mean centered variable, which already has a grand mean of 0.
#'
#' The \code{\link[bruceR:PROCESS]{bruceR::PROCESS()}} function uses:
#' \enumerate{
#' \item the \code{\link[interactions:sim_slopes]{interactions::sim_slopes()}} function to
#' estimate simple slopes (and conditional direct effects) in moderation, moderated moderation, and moderated mediation models
#' (PROCESS Models 1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 58, 59, 72, 73, 75, 76).
#' \item the \code{\link[mediation:mediate]{mediation::mediate()}} function to
#' estimate (conditional) indirect effects in (moderated) mediation models
#' (PROCESS Models 4, 5, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 58, 59, 72, 73, 75, 76).
#' \item the \code{\link[lavaan:sem]{lavaan::sem()}} function to perform serial multiple mediation analysis (PROCESS Model 6).
#' }
#' If you use this function in your research and report its results in your paper, please cite not only \code{bruceR} but also
#' the other R packages it uses internally (\code{mediation}, \code{interactions}, and/or \code{lavaan}).
#'
#' Two parts of results are printed:
#'
#' PART 1. Regression model summary (using \code{\link[bruceR:model_summary]{bruceR::model_summary()}} to summarize the models)
#'
#' PART 2. Mediation/moderation effect estimates (using one or a combination of the above packages and functions to estimate the effects)
#'
#' To organize the PART 2 output, the results of \strong{Simple Slopes} are titled in \strong{green},
#' whereas the results of \strong{Indirect Path} are titled in \strong{blue}.
#'
#' \strong{\emph{Disclaimer}:}
#' Although this function is named after \code{PROCESS}, Andrew F. Hayes has no role in its design, and
#' its development is independent from the official SPSS PROCESS macro and "process.R" script.
#' Any error or limitation should be attributed to the three R packages/functions that \code{bruceR::PROCESS()} uses internally.
#' Moreover, as mediation analyses include \emph{random processes} (i.e., bootstrap resampling or Monte Carlo simulation),
#' the results of mediation analyses are \emph{unlikely} to be exactly the same across different software
#' (even if you set the same random seed in different software).
#'
#' @param data Data frame.
#' @param y,x Variable name of outcome (Y) and predictor (X).
#'
#' It supports both continuous (numeric) and dichotomous (factor) variables.
#' @param meds Variable name(s) of mediator(s) (M).
#' Use \code{c()} to combine multiple mediators.
#'
#' It supports both continuous (numeric) and dichotomous (factor) variables.
#'
#' It allows an infinite number of mediators in parallel
#' or 2~4 mediators in serial.
#'
#' * Order matters when \code{med.type="serial"}
#' (PROCESS Model 6: serial mediation).
#' @param mods Variable name(s) of 0~2 moderator(s) (W).
#' Use \code{c()} to combine multiple moderators.
#'
#' It supports all types of variables:
#' continuous (numeric), dichotomous (factor), and multicategorical (factor).
#'
#' * Order matters when \code{mod.type="3-way"}
#' (PROCESS Models 3, 5.3, 11, 12, 18, 19, 72, and 73).
#'
#' ** Do not set this argument when \code{med.type="serial"}
#' (PROCESS Model 6).
#' @param covs Variable name(s) of covariate(s) (i.e., control variables).
#' Use \code{c()} to combine multiple covariates.
#' It supports all types of (and an infinite number of) variables.
#' @param clusters HLM (multilevel) cluster(s):
#' e.g., \code{"School"}, \code{c("Prov", "City")}, \code{c("Sub", "Item")}.
#' @param hlm.re.m,hlm.re.y HLM (multilevel) random effect term of M model and Y model.
#' By default, it converts \code{clusters} to \code{\link[lme4:lme4-package]{lme4}} syntax of random intercepts:
#' e.g., \code{"(1 | School)"} or \code{"(1 | Sub) + (1 | Item)"}.
#'
#' You may specify these arguments to include more complex terms:
#' e.g., random slopes \code{"(X | School)"}, or 3-level random effects \code{"(1 | Prov/City)"}.
#' @param hlm.type HLM (multilevel) mediation type (levels of "X-M-Y"):
#' \code{"1-1-1"} (default),
#' \code{"2-1-1"} (indeed the same as \code{"1-1-1"} in a mixed model),
#' or \code{"2-2-1"} (currently \emph{not fully supported}, as limited by the \code{\link[mediation:mediate]{mediation}} package).
#' In most cases, no need to set this argument.
#' @param med.type Type of mediator:
#' \code{"parallel"} (default) or \code{"serial"}
#' (only relevant to PROCESS Model 6).
#' Partial matches of \code{"p"} or \code{"s"} also work.
#' In most cases, no need to set this argument.
#' @param mod.type Type of moderator:
#' \code{"2-way"} (default) or \code{"3-way"}
#' (relevant to PROCESS Models 3, 5.3, 11, 12, 18, 19, 72, and 73).
#' Partial matches of \code{"2"} or \code{"3"} also work.
#' @param mod.path Which path(s) do the moderator(s) influence?
#' \code{"x-y"}, \code{"x-m"}, \code{"m-y"}, or any combination of them
#' (use \code{c()} to combine), or \code{"all"} (i.e., all of them).
#' No default value.
#' @param cov.path Which path(s) do the control variable(s) influence?
#' \code{"y"}, \code{"m"}, or \code{"both"} (default).
#' @param mod1.val,mod2.val By default (\code{NULL}), it uses
#' \strong{Mean +/- SD} of a continuous moderator (numeric) or
#' \strong{all levels} of a dichotomous/multicategorical moderator (factor) to
#' perform simple slope analyses and/or conditional mediation analyses.
#' You may manually specify a vector of certain values: e.g.,
#' \code{mod1.val=c(1, 3, 5)} or \code{mod1.val=c("A", "B", "C")}.
#' @param ci Method for estimating the standard error (SE) and
#' 95\% confidence interval (CI) of indirect effect(s).
#' Defaults to \code{"boot"} for (generalized) linear models or
#' \code{"mcmc"} for (generalized) linear mixed models (i.e., multilevel models).
#' \describe{
#' \item{\code{"boot"}}{Percentile Bootstrap}
#' \item{\code{"bc.boot"}}{Bias-Corrected Percentile Bootstrap}
#' \item{\code{"bca.boot"}}{Bias-Corrected and Accelerated (BCa) Percentile Bootstrap}
#' \item{\code{"mcmc"}}{Markov Chain Monte Carlo (Quasi-Bayesian)}
#' }
#' * Note that these methods \emph{never} apply to the estimates of simple slopes.
#' You \emph{should not} report the 95\% CIs of simple slopes as Bootstrap or Monte Carlo CIs,
#' because they are just standard CIs without any resampling method.
#' @param nsim Number of simulation samples (bootstrap resampling or Monte Carlo simulation)
#' for estimating SE and 95\% CI. Defaults to \code{100} for running examples faster.
#' In formal analyses, however, \strong{\code{nsim=1000} (or larger)} is strongly suggested!
#' @param seed Random seed for obtaining reproducible results.
#' Defaults to \code{NULL}.
#' You may set to any number you prefer
#' (e.g., \code{seed=1234}, just an uncountable number).
#'
#' * Note that all mediation models include random processes
#' (i.e., bootstrap resampling or Monte Carlo simulation).
#' To get exactly the same results between runs, you need to set a random seed.
#' However, even if you set the same seed number, it is unlikely to
#' get exactly the same results across different R packages
#' (e.g., \code{\link[lavaan:lavaan-class]{lavaan}} vs. \code{\link[mediation:mediate]{mediation}})
#' and software (e.g., SPSS, Mplus, R, jamovi).
#' @param center Centering numeric (continuous) predictors? Defaults to \code{TRUE} (suggested).
#' @param std Standardizing variables to get standardized coefficients? Defaults to \code{FALSE}.
#' If \code{TRUE}, it will standardize all numeric (continuous) variables
#' before building regression models.
#' However, it is \emph{not suggested} to set \code{std=TRUE} for \emph{generalized} linear (mixed) models.
#' @param digits Number of decimal places of output. Defaults to \code{3}.
#' @param file File name of MS Word (\code{.doc}).
#' Currently, only regression model summary can be saved.
#'
#' @return
#' Invisibly return a list of results:
#' \describe{
#' \item{\code{process.id}}{PROCESS model number.}
#' \item{\code{process.type}}{PROCESS model type.}
#' \item{\code{model.m}}{"Mediator" (M) models (a list of multiple models).}
#' \item{\code{model.y}}{"Outcome" (Y) model.}
#' \item{\code{results}}{Effect estimates and other results (unnamed list object).}
#' }
#'
#' @details
#' For more details and illustrations, see
#' \href{https://github.com/psychbruce/bruceR/tree/master/note}{PROCESS-bruceR-SPSS} (PDF and Markdown files).
#'
#' @seealso
#' \code{\link{lavaan_summary}}
#'
#' \code{\link{model_summary}}
#'
#' \code{\link{med_summary}}
#'
#' @references
#' Hayes, A. F. (2018). \emph{Introduction to mediation, moderation,
#' and conditional process analysis (second edition):
#' A regression-based approach}. Guilford Press.
#'
#' Yzerbyt, V., Muller, D., Batailler, C., & Judd, C. M. (2018).
#' New recommendations for testing indirect effects in mediational models:
#' The need to report and test component paths.
#' \emph{Journal of Personality and Social Psychology, 115}(6), 929--943.
#'
#' @examples
#' \donttest{#### NOTE ####
#' ## In the following examples, I set nsim=100 to save time.
#' ## In formal analyses, nsim=1000 (or larger) is suggested!
#'
#' #### Demo Data ####
#' # ?mediation::student
#' data = mediation::student %>%
#' dplyr::select(SCH_ID, free, smorale, pared, income,
#' gender, work, attachment, fight, late, score)
#' names(data)[2:3] = c("SCH_free", "SCH_morale")
#' names(data)[4:7] = c("parent_edu", "family_inc", "gender", "partjob")
#' data$gender01 = 1 - data$gender # 0 = female, 1 = male
#' # dichotomous X: as.factor()
#' data$gender = factor(data$gender01, levels=0:1, labels=c("Female", "Male"))
#' # dichotomous Y: as.factor()
#' data$pass = as.factor(ifelse(data$score>=50, 1, 0))
#'
#' #### Descriptive Statistics and Correlation Analyses ####
#' Freq(data$gender)
#' Freq(data$pass)
#' Describe(data) # file="xxx.doc"
#' Corr(data[,4:11]) # file="xxx.doc"
#'
#' #### PROCESS Analyses ####
#'
#' ## Model 1 ##
#' PROCESS(data, y="score", x="late", mods="gender") # continuous Y
#' PROCESS(data, y="pass", x="late", mods="gender") # dichotomous Y
#'
#' # (multilevel moderation)
#' PROCESS(data, y="score", x="late", mods="gender", # continuous Y (LMM)
#' clusters="SCH_ID")
#' PROCESS(data, y="pass", x="late", mods="gender", # dichotomous Y (GLMM)
#' clusters="SCH_ID")
#'
#' # (Johnson-Neyman (J-N) interval and plot)
#' PROCESS(data, y="score", x="gender", mods="late") -> P
#' P$results[[1]]$jn[[1]] # Johnson-Neyman interval
#' P$results[[1]]$jn[[1]]$plot # Johnson-Neyman plot (ggplot object)
#' GLM_summary(P$model.y) # detailed results of regression
#'
#' # (allows multicategorical moderator)
#' d = airquality
#' d$Month = as.factor(d$Month) # moderator: factor with levels "5"~"9"
#' PROCESS(d, y="Temp", x="Solar.R", mods="Month")
#'
#' ## Model 2 ##
#' PROCESS(data, y="score", x="late",
#' mods=c("gender", "family_inc"),
#' mod.type="2-way") # or omit "mod.type", default is "2-way"
#'
#' ## Model 3 ##
#' PROCESS(data, y="score", x="late",
#' mods=c("gender", "family_inc"),
#' mod.type="3-way")
#' PROCESS(data, y="pass", x="gender",
#' mods=c("late", "family_inc"),
#' mod1.val=c(1, 3, 5), # moderator 1: late
#' mod2.val=seq(1, 15, 2), # moderator 2: family_inc
#' mod.type="3-way")
#'
#' ## Model 4 ##
#' PROCESS(data, y="score", x="parent_edu",
#' meds="family_inc", covs="gender",
#' ci="boot", nsim=100, seed=1)
#'
#' # (allows an infinite number of multiple mediators in parallel)
#' PROCESS(data, y="score", x="parent_edu",
#' meds=c("family_inc", "late"),
#' covs=c("gender", "partjob"),
#' ci="boot", nsim=100, seed=1)
#'
#' # (multilevel mediation)
#' PROCESS(data, y="score", x="SCH_free",
#' meds="late", clusters="SCH_ID",
#' ci="mcmc", nsim=100, seed=1)
#'
#' ## Model 6 ##
#' PROCESS(data, y="score", x="parent_edu",
#' meds=c("family_inc", "late"),
#' covs=c("gender", "partjob"),
#' med.type="serial",
#' ci="boot", nsim=100, seed=1)
#'
#' ## Model 8 ##
#' PROCESS(data, y="score", x="fight",
#' meds="late",
#' mods="gender",
#' mod.path=c("x-m", "x-y"),
#' ci="boot", nsim=100, seed=1)
#'
#' ## For more examples and details, see the "note" subfolder at:
#' ## https://github.com/psychbruce/bruceR/tree/main/note
#' }
#' @export
PROCESS = function(
data,
y="",
x="",
meds=c(),
mods=c(),
covs=c(),
clusters=c(),
hlm.re.m="",
hlm.re.y="",
hlm.type=c("1-1-1", "2-1-1", "2-2-1"),
med.type=c("parallel", "serial"), # "p"*, "s"
mod.type=c("2-way", "3-way"), # "2"*, "3"
mod.path=c("x-y", "x-m", "m-y", "all"),
cov.path=c("y", "m", "both"),
mod1.val=NULL,
mod2.val=NULL,
ci=c("boot", "bc.boot", "bca.boot", "mcmc"),
nsim=100,
seed=NULL,
center=TRUE,
std=FALSE,
digits=3,
file=NULL
) {
## Default Setting
warning.y.class = "\"y\" should be a numeric variable or a factor variable with only 2 levels."
warning.x.class = "\"x\" should be a numeric variable or a factor variable with only 2 levels."
warning.m.class = "\"meds\" should be numeric variable(s) or factor variable(s) with only 2 levels."
warning.mod.path = "Please also specify \"mod.path\":\n \"all\" or any combination of c(\"x-y\", \"x-m\", \"m-y\")"
if(x=="" | y=="") stop("Please specify both \"x\" and \"y\".", call.=TRUE)
if(length(meds)>0 & length(mods)>0 & length(mod.path)>3)
stop(warning.mod.path, call.=TRUE)
if("all" %in% mod.path)
mod.path = c("x-y", "x-m", "m-y")
if("both" %in% cov.path)
cov.path = c("y", "m")
if(length(mods)>0) mod1 = mods[1] else mod1 = NULL
if(length(mods)>1) mod2 = mods[2] else mod2 = NULL
if(length(mods)>2) stop("The number of moderators (\"mods\") should be no more than 2.", call.=TRUE)
if(length(med.type)>1) med.type = "parallel" # default
if(length(mod.type)>1) mod.type = "2-way" # default
if(grepl("p", med.type)) med.type = "parallel"
if(grepl("s", med.type)) med.type = "serial"
if(grepl("2", mod.type)) mod.type = "2-way"
if(grepl("3", mod.type)) mod.type = "3-way"
if(grepl("p|s", med.type)==FALSE)
stop("\"med.type\" should be \"parallel\" or \"serial\".", call.=TRUE)
if(grepl("2|3", mod.type)==FALSE)
stop("\"mod.type\" should be \"2-way\" or \"3-way\".", call.=TRUE)
if(length(meds)>0) {
if(length(mods)>0 & "m-y" %in% mod.path) {
if(mod.type=="2-way")
meds.all = " + " %^% paste(rep(meds, each=length(mods)) %^% "*" %^% mods, collapse=" + ")
if(mod.type=="3-way")
meds.all = " + " %^% paste(meds %^% "*" %^% paste(mods, collapse="*"), collapse=" + ")
} else {
meds.all = " + " %^% paste(meds, collapse=" + ")
}
}
if(length(covs)>0)
covs.all = " " %^% paste(covs, collapse=" + ") %^% " +"
else
covs.all = ""
if(length(ci)>1) ci = "boot" # default: percentile bootstrap
if(grepl("p", ci) | ci=="boot") ci = "boot"
if(ci %in% c("bc", "bc.boot")) ci = "bc.boot"
if(grepl("bca", ci)) ci = "bca.boot"
if(grepl("m", ci)) ci = "mcmc"
if(ci %notin% c("boot", "bc.boot", "bca.boot", "mcmc"))
stop("Please choose \"boot\", \"bc.boot\", \"bca.boot\", or \"mcmc\" for ci.", call.=TRUE)
nsim.type = ifelse(grepl("boot", ci), "Bootstrap", "Monte Carlo")
if(length(clusters)>0) HLM = TRUE else HLM = FALSE
if(length(hlm.type)>1) hlm.type = "1-1-1" # default; same as "2-1-1"
if(hlm.type %notin% c("1-1-1", "2-1-1", "2-2-1"))
stop("\"hlm.type\" should be \"1-1-1\", \"2-1-1\", or \"2-2-1\".", call.=TRUE)
if(HLM) {
if(hlm.re.m=="") # default: random intercept
hlm.re.m = paste("(1 | " %^% clusters %^% ")", collapse=" + ")
hlm.re.m = " + " %^% hlm.re.m
if(hlm.re.y=="") # default: random intercept
hlm.re.y = paste("(1 | " %^% clusters %^% ")", collapse=" + ")
hlm.re.y = " + " %^% hlm.re.y
if(length(meds)>0 & ci!="mcmc")
message("\nNOTE: \nci has been reset to \"mcmc\" because bootstrap method is not applicable to multilevel models.")
ci = "mcmc"
}
## Data Centering and Recoding
data = as.data.frame(data)
data.v = na.omit(data[c(y, x, meds, mods, covs, clusters)])
if(inherits(data.v[[y]], c("factor", "character", "logical"))) {
if(length(unique(data.v[[y]]))==2) {
data.v[[y]] = as.numeric(as.factor(data.v[[y]])) - 1 # 0, 1
Y01 = TRUE
} else {
stop(warning.y.class, call.=TRUE)
}
} else {
Y01 = FALSE
}
M01 = c()
for(med in meds) {
if(inherits(data.v[[med]], c("factor", "character", "logical"))) {
if(length(unique(data.v[[med]]))==2) {
data.v[[med]] = as.numeric(as.factor(data.v[[med]])) - 1 # 0, 1
M01 = c(M01, TRUE)
} else {
stop(warning.m.class, call.=TRUE)
}
} else {
M01=c(M01, FALSE)
}
}
if(inherits(data.v[[x]], c("factor", "character", "logical"))) {
if(length(unique(data.v[[x]]))==2) {
x.levels = levels(as.factor(data.v[[x]]))
data.v[[x]] = as.numeric(as.factor(data.v[[x]])) - 1 # 0, 1
x.trans.info = " (recoded: " %^% paste(x.levels, 0:1, sep="=", collapse=", ") %^% ")"
} else {
stop(warning.x.class, call.=TRUE)
}
} else {
x.trans.info = ""
}
if(HLM & length(meds)>0 & hlm.type=="2-2-1") {
if(length(clusters)>1) stop("The number of clusters should be 1.", call.=TRUE)
dt = data.v[c(x, meds, mods, covs, clusters)]
Run("dt1 = dplyr::summarise(dplyr::group_by(dt, {clusters}), dplyr::across(where(is.numeric), mean))",
"dt2 = dplyr::summarise(dplyr::group_by(dt, {clusters}), dplyr::across(where(is.factor), mean))",
"dt = dplyr::left_join(dt1, dt2, by=\"{clusters}\")")
data.meds.L2 = as.data.frame(dt)[c(clusters, x, meds, mods, covs)]
rm(dt)
}
if(std) {
# caution !!!
if(Y01)
data.v = data.c = data.c.NOmed =
grand_mean_center(data.v, vars=c(x, meds, mods, covs), std=TRUE)
else
data.v = data.c = data.c.NOmed =
grand_mean_center(data.v, vars=c(y, x, meds, mods, covs), std=TRUE)
} else if(center) {
data.c.NOmed = grand_mean_center(data.v, vars=c(x, mods, covs), std=FALSE)
data.c = grand_mean_center(data.v, vars=c(x, meds, mods, covs), std=FALSE)
} else {
data.c = data.c.NOmed = data.v
}
nmis = nrow(data) - nrow(data.v)
## File Opening
# if(!is.null(file)) {
# file = str_replace(file, "\\.docx$", ".doc")
# FILE = file(file, "a", encoding="UTF-8")
# }
## Formula Building
ft = Glue("{y} ~ {x}")
if(length(meds)==0) {
# (moderated) moderation
fm = c()
if(length(mods)==0) {
stop("Please specify \"meds\" (mediators) and/or \"mods\" (moderators).", call.=TRUE)
} else if(length(mods)==1) {
pid = 1
ptype = "Simple Moderation"
fy = Glue("{y} ~ {x}*{mod1}")
} else if(length(mods)==2) {
if(mod.type=="2-way") {
pid = 2
ptype = "Parallel Moderation (2 mods; 2-way)"
fy = Glue("{y} ~ {x}*{mod1} + {x}*{mod2}")
}
if(mod.type=="3-way") {
pid = 3
ptype = "Moderated Moderation (2 mods; 3-way)"
fy = Glue("{y} ~ {x}*{mod1}*{mod2}")
}
}
}
else if(length(meds)==1 | med.type=="parallel") {
# single/parallel (moderated) mediation
if(length(mods)==0) {
pid = 4
ptype = ifelse(
length(meds)==1,
"Simple Mediation",
Glue("Parallel Multiple Mediation ({length(meds)} meds)"))
fm = meds %^% Glue(" ~ {x}")
fy = Glue("{y} ~ {x}") %^% meds.all
}
if(length(mods)==1) {
ptype = ifelse(
length(meds)==1,
"Moderated Mediation",
Glue("Parallel Multiple Moderated Mediation ({length(meds)} meds)"))
if("x-y" %in% mod.path) {
fy = Glue("{y} ~ {x}*{mod1}") %^% meds.all
if("x-m" %in% mod.path) {
pid = ifelse("m-y" %in% mod.path, 59, 8)
fm = meds %^% Glue(" ~ {x}*{mod1}")
} else {
pid = ifelse("m-y" %in% mod.path, 15, 5)
if(pid==5) ptype = Glue("Mediation and Moderation ({length(meds)} meds and 1 mods)")
fm = meds %^% Glue(" ~ {x}")
}
} else {
fy = Glue("{y} ~ {x}") %^% meds.all
if("x-m" %in% mod.path) {
pid = ifelse("m-y" %in% mod.path, 58, 7)
fm = meds %^% Glue(" ~ {x}*{mod1}")
} else {
pid = ifelse("m-y" %in% mod.path, 14, -1)
fm = meds %^% Glue(" ~ {x}")
}
}
}
if(length(mods)==2 & mod.type=="2-way") {
ptype = ifelse(
length(meds)==1,
"Moderated Mediation (2 mods; 2-way)",
Glue("Parallel Multiple Moderated Mediation ({length(meds)} meds and 2 mods; 2-way)"))
if("x-y" %in% mod.path) {
fy = Glue("{y} ~ {x}*{mod1} + {x}*{mod2}") %^% meds.all
if("x-m" %in% mod.path) {
pid = ifelse("m-y" %in% mod.path, 76, 10)
fm = meds %^% Glue(" ~ {x}*{mod1} + {x}*{mod2}")
} else {
pid = ifelse("m-y" %in% mod.path, 17, 5.2)
if(pid==5.2) ptype = Glue("Mediation and Parallel Moderation ({length(meds)} meds and 2 mods; 2-way)")
fm = meds %^% Glue(" ~ {x}")
}
} else {
fy = Glue("{y} ~ {x}") %^% meds.all
if("x-m" %in% mod.path) {
pid = ifelse("m-y" %in% mod.path, 75, 9)
fm = meds %^% Glue(" ~ {x}*{mod1} + {x}*{mod2}")
} else {
pid = ifelse("m-y" %in% mod.path, 16, -2)
fm = meds %^% Glue(" ~ {x}")
}
}
}
if(length(mods)==2 & mod.type=="3-way") {
ptype = ifelse(
length(meds)==1,
"Moderated Mediation (2 mods; 3-way)",
Glue("Parallel Multiple Moderated Mediation ({length(meds)} meds and 2 mods; 3-way)"))
if("x-y" %in% mod.path) {
fy = Glue("{y} ~ {x}*{mod1}*{mod2}") %^% meds.all
if("x-m" %in% mod.path) {
pid = ifelse("m-y" %in% mod.path, 73, 12)
fm = meds %^% Glue(" ~ {x}*{mod1}*{mod2}")
} else {
pid = ifelse("m-y" %in% mod.path, 19, 5.3)
if(pid==5.3) ptype = Glue("Mediation and Moderated Moderation ({length(meds)} meds and 2 mods; 3-way)")
fm = meds %^% Glue(" ~ {x}")
}
} else {
fy = Glue("{y} ~ {x}") %^% meds.all
if("x-m" %in% mod.path) {
pid = ifelse("m-y" %in% mod.path, 72, 11)
fm = meds %^% Glue(" ~ {x}*{mod1}*{mod2}")
} else {
pid = ifelse("m-y" %in% mod.path, 18, -3)
fm = meds %^% Glue(" ~ {x}")
}
}
}
if(pid<0)
stop(warning.mod.path, call.=TRUE)
if(pid %in% 7)
fy = Glue("{y} ~ {x} + {mod1}") %^% meds.all
if(pid %in% c(9, 11))
fy = Glue("{y} ~ {x} + {mod1} + {mod2}") %^% meds.all
if(pid %in% 14:15)
fm = meds %^% Glue(" ~ {x} + {mod1}")
if(pid %in% 16:19)
fm = meds %^% Glue(" ~ {x} + {mod1} + {mod2}")
}
else if(med.type=="serial") {
# serial mediation
if(length(mods)==0) {
if(length(meds)>4)
stop("PROCESS() does not support serial mediation with more than 4 mediators.", call.=TRUE)
if(any(M01))
stop("PROCESS() does not support serial mediation with dichotomous mediators.", call.=TRUE)
pid = 6
ptype = Glue("Serial Multiple Mediation ({length(meds)} meds)")
fy = Glue("{y} ~ {x}") %^% meds.all
fm = meds %^% Glue(" ~ {x}")
for(mi in 2:length(meds)) {
fm[mi] = fm[mi] %^% " + " %^% paste(meds[1:(mi-1)], collapse=" + ")
}
} else {
stop("PROCESS() does not support serial mediation with moderators.\nPlease remove the \"mods\" argument from your code.", call.=TRUE)
}
}
if("m" %in% cov.path)
fm = str_replace(fm, "~", "~" %^% covs.all)
if("y" %in% cov.path) {
fy = str_replace(fy, "~", "~" %^% covs.all)
ft = str_replace(ft, "~", "~" %^% covs.all) # y ~ [covs] + x
}
if(HLM) {
if(hlm.type!="2-2-1")
fm = fm %^% hlm.re.m
fy = fy %^% hlm.re.y
ft = ft %^% hlm.re.y
}
## Regression Model Summary
varlist = function(vars=c()) {
vars.text = paste(vars, collapse=', ')
if(vars.text=="") vars.text = "-"
return(vars.text)
}
meds.text = varlist(meds)
mods.text = varlist(mods)
covs.text = varlist(covs)
clusters.text = varlist(clusters)
Print("
\n
<<bold ****************** PART 1. Regression Model Summary ******************>>
<<blue PROCESS Model Code : {pid}>> <<white (Hayes, 2018; <<underline www.guilford.com/p/hayes3>>)>>
<<blue PROCESS Model Type : {ptype}>>
<<green
- Outcome (Y) : {y}
- Predictor (X) : {x}{x.trans.info}
- Mediators (M) : {meds.text}
- Moderators (W) : {mods.text}
- Covariates (C) : {covs.text}
- HLM Clusters : {clusters.text}
>>
\n
")
if(center | std) {
Print("<<yellow
All numeric predictors have been {ifelse(std, 'standardized', 'grand-mean centered')}.
(For details, please see the help page of PROCESS.)
>>
\n
")
}
if(length(meds)>0) {
Print("<<italic Formula of Mediator>>:")
cat("- ", paste(fm, collapse="\n- "))
cat("\n")
}
Print("<<italic Formula of Outcome>>:")
cat("- ", fy)
cat("\n
CAUTION:
Fixed effect (coef.) of a predictor involved in an interaction
denotes its \"simple effect/slope\" at the other predictor = 0.
Only when all predictors in an interaction are mean-centered
can the fixed effect denote the \"main effect\"!
")
## Regression Model Building
if(Y01==FALSE) {
FUN.y = ifelse(HLM, "lmerTest::lmer", "lm")
FML.y = ""
} else {
FUN.y = ifelse(HLM, "lme4::glmer", "glm")
FML.y = ", family=binomial"
}
model.t = model.y = NULL
Run("model.y0 = {FUN.y}({fy}, data=data.v{FML.y})")
Run("model.y = {FUN.y}({fy}, data=data.c{FML.y})")
Run("model.t = {FUN.y}({ft}, data=data.c{FML.y})")
model.m = list()
model.m0 = list()
if(pid>=4) {
data.v.temp = data.v
data.c.temp = data.c
data.c = data.c.NOmed
if(HLM & hlm.type=="2-2-1") {
data.v = data.meds.L2
if(center) {
data.c = data.c.NOmed =
grand_mean_center(data.v, vars=c(x, mods, covs))
} else {
data.c = data.c.NOmed = data.v
}
}
for(i in 1:length(fm)) {
if(M01[i]==FALSE) {
FUN.m = ifelse(HLM & hlm.type!="2-2-1", "lmerTest::lmer", "lm")
FML.m = ""
} else {
FUN.m = ifelse(HLM & hlm.type!="2-2-1", "lme4::glmer", "glm")
FML.m = ", family=binomial"
}
Run("model.m0.{i} = {FUN.m}({fm[i]}, data=data.v{FML.m})")
Run("model.m.{i} = {FUN.m}({fm[i]}, data=data.c{FML.m})")
Run("model.m0 = c(model.m0, list(model.m0.{i}=model.m0.{i}))")
Run("model.m = c(model.m, list(model.m.{i}=model.m.{i}))")
}
data.v = data.v.temp
data.c = data.c.temp
rm(data.v.temp, data.c.temp)
}
model_summary(c(list(model.t), model.m, list(model.y)),
digits=digits, std=std, file=file)
file = NULL
## PROCESS Model Summary
if(pid %in% 1:3)
pkg = Glue("\u2018interactions\u2019 (v{packageVersion('interactions')})")
else if(pid==4)
pkg = Glue("\u2018mediation\u2019 (v{packageVersion('mediation')})")
else if(pid==6)
pkg = Glue("\u2018lavaan\u2019 (v{packageVersion('lavaan')})")
else
pkg = Glue("\u2018mediation\u2019 (v{packageVersion('mediation')}), \u2018interactions\u2019 (v{packageVersion('interactions')})")
Print("
<<bold ************ PART 2. Mediation/Moderation Effect Estimate ************>>
<<magenta
Package Use : {pkg}
Effect Type : {ptype} (Model {pid})
Sample Size : {nrow(data.v)}{ifelse(nmis>0, Glue(' ({nmis} missing observations deleted)'), '')}
Random Seed : {ifelse(length(meds)>0, 'set.seed('%^%seed%^%')', '-')}
Simulations : {ifelse(length(meds)>0, nsim %^% ' (' %^% nsim.type %^% ')', '-')}
>>")
if(length(meds)>0 & nsim<1000)
message("\nWarning: nsim=1000 (or larger) is suggested!")
cat("\n")
## PROCESS Model Building
if(HLM & hlm.type=="2-2-1")
stop("As limited by the \"mediation\" package, the estimate of \"2-2-1\" multilevel mediation is not supported currently.", call.=TRUE)
RES = list()
run.process.mod.xy = function(eff.tag="") {
text = Glue("
res = process_mod(model.y0, model.y,
data.c, x, y, mod1, mod2,
mod1.val, mod2.val,
mod.type,
x.label=\"X\",
y.label=\"Y\",
eff.tag=\"{eff.tag}\",
digits, file=file)
RES = c(RES, list(res))")
}
run.process.mod.xm = function(i, eff.tag="") {
text = Glue("
res = process_mod(model.m0[[i]], model.m[[i]],
data.c.NOmed, x, meds[i], mod1, mod2,
mod1.val, mod2.val,
mod.type,
x.label=\"X\",
y.label=\"M\",
eff.tag=\"{eff.tag}\",
digits, file=file)
RES = c(RES, list(res))")