-
Notifications
You must be signed in to change notification settings - Fork 0
/
99_interplot-3-way.R
executable file
·1294 lines (1190 loc) · 47.3 KB
/
99_interplot-3-way.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
if (getRversion() >= "2.15.1")
utils::globalVariables(c(".", "X.weights.", "ks_diff", "ks.test"))
#' Plot Conditional Coefficients in Mixed-Effects Models with Interaction Terms
#'
#' \code{interplot.mlm} is a method to calculate conditional coefficient estimates from the results of multilevel (mixed-effects) regression models with interaction terms. The extension of this package allows for three-way interactions but it does not allow for three way interactions where two terms are the same variable (quadratic).
#'
#' @param m A model object including an interaction term, or, alternately, a data frame recording conditional coefficients.
#' @param var1 The name (as a string) of the variable of interest in the interaction term; its conditional coefficient estimates will be plotted.
#' @param var2 The name (as a string) of the other variable in the interaction term.
#' @param plot A logical value indicating whether the output is a plot or a dataframe including the conditional coefficient estimates of var1, their upper and lower bounds, and the corresponding values of var2.
#' @param steps Desired length of the sequence. A non-negative number, which for seq and seq.int will be rounded up if fractional. The default is 100 or the unique categories in the \code{var2} (when it is less than 100. Also see \code{\link{unique}}).
#' @param ci A numeric value defining the confidence intervals. The default value is 95\% (0.95).
#' @param adjCI Not working for `lmer` outputs yet.
#' @param hist A logical value indicating if there is a histogram of `var2` added at the bottom of the conditional effect plot.
#' @param var2_dt A numerical value indicating the frequency distribution of `var2`. It is only used when `hist == TRUE`. When the object is a model, the default is the distribution of `var2` of the model.
#' @param predPro A logical value with default of `FALSE`. When the `m` is an object of class `glmerMod` and the argument is set to `TRUE`, the function will plot predicted probabilities at the values given by `var2_vals`.
#' @param var2_vals A numerical value indicating the values the predicted probabilities are estimated, when `predPro` is `TRUE`.
#' @param point A logical value determining the format of plot. By default, the function produces a line plot when var2 takes on ten or more distinct values and a point (dot-and-whisker) plot otherwise; option TRUE forces a point plot.
#' @param sims Number of independent simulation draws used to calculate upper and lower bounds of coefficient estimates: lower values run faster; higher values produce smoother curves.
#' @param xmin A numerical value indicating the minimum value shown of x shown in the graph. Rarely used.
#' @param xmax A numerical value indicating the maximum value shown of x shown in the graph. Rarely used.
#' @param ercolor A character value indicating the outline color of the whisker or ribbon.
#' @param esize A numerical value indicating the size of the whisker or ribbon.
#' @param ralpha A numerical value indicating the transparency of the ribbon.
#' @param rfill A character value indicating the filling color of the ribbon.
#' @param stats_cp A character value indicating what statistics to present as the plot note. Three options are available: "none", "ci", and "ks". The default is "none". See the Details for more information.
#' @param txt_caption A character string to add a note for the plot, a value will sending to \code{ggplot2::labs(caption = txt_caption))}.
#' @param facet_labs An optional character vector of facet labels to be used when plotting an interaction with a factor variable.
#' @param ... Other ggplot aesthetics arguments for points in the dot-whisker plot or lines in the line-ribbon plots. Not currently used.
#'
#' @details \code{interplot.mlm} is a S3 method from the \code{interplot}. It works on mixed-effects objects with class \code{lmerMod} and \code{glmerMod}.
#'
#' Because the output function is based on \code{\link[ggplot2]{ggplot}}, any additional arguments and layers supported by \code{ggplot2} can be added with the \code{+}.
#'
#' \code{interplot} visualizes the conditional effect based on simulated marginal effects. The simulation provides a probabilistic distribution of moderation effect of the conditioning variable (\code{var2}) at every preset values (including the minimum and maximum values) of the conditioned variable (\code{var1}), denoted as Emin and Emax. This output allows the function to further examine the conditional effect statistically in two ways. One is to examine if the distribution of \eqn{Emax - Emin} covers zero. The other is to directly compare Emin and Emax through statistical tools for distributional comparisons. Users can choose either method by setting the argument \code{stats_cp} to "ci" or "ks".
#' \itemize{
#' \item "ci" provides the confidence interval of the difference of \eqn{Emax - Emin}. An interval including 0 suggests no statistical difference before and after the conditional effect is applied, and vise versa.
#' \item "ks" presents the result of a two-sample Kolmogorov-Smirnov test of the simulated distributions of Emin and Emax. The output includes a D statistics and a p-value of the null hypothesis that the two distributions come from the same distribution at the 0.05 level.
#' }
#'
#' See an illustration in the package vignette.
#'
#' @return The function returns a \code{ggplot} object.
#'
#' @importFrom arm sim
#' @importFrom stats quantile
#' @importFrom stats median
#' @importFrom stats plogis
#' @importFrom stats model.matrix
#' @importFrom purrr map
#' @import ggplot2
#' @import dplyr
#'
#'
#' @export
# Coding function for non-mi mlm objects
interplot.lmerMod_3 <- function(m,
var1,
var2,
var3 = NULL,
plot = TRUE,
steps = NULL,
var2_steps = NULL,
var3_steps = NULL,
ci = .95,
adjCI = FALSE,
hist = FALSE,
var2_dt = NA,
predPro = FALSE,
var2_vals = NULL,
var3_vals = NULL,
point = FALSE,
sims = 5000,
xmin = NA,
xmax = NA,
var2_xmin = NA,
var2_xmax = NA,
var3_xmin = NA,
var3_xmax = NA,
ercolor = NA,
esize = 0.5,
ralpha = 0.5,
rfill = "grey70",
stats_cp = "none",
txt_caption = NULL,
facet_labs = NULL,
...) {
m.class <- class(m)
if (predPro == TRUE){stop("Predicted probability is estimated only for general linear models.")}
m.sims <- arm::sim(m, sims)
## For factor base terms####
factor_v1 <- factor_v2 <- factor_v3 <- FALSE
# A) 3-way interaction ----------------------------------------------------
if (!is.null(var3)) {
# if the first two terms are factors, or if the second term is a factor => abort
if (
# is.factor(eval(parse(text = paste0("m@frame$", var1)))) &
# is.factor(eval(parse(text = paste0("m@frame$", var2)))) |
# is.factor(eval(parse(text = paste0("m@frame$", var3)))) # var 3 cannot be a factor.
is.factor(m@frame[,var1]) & is.factor(m@frame[,var2]) |
is.factor(m@frame[,var3])
) {
stop("The function does not support interactions between two factors.")
}
# Arriving at the term names of the coefficients -------------------------------
# var1, var12
if (
# is.factor(eval(parse(text = paste0("m@frame$", var1))))
is.factor(m@frame[,var1])
) {
var1_bk <- var1
# var1 <- paste0(var1, levels(eval(parse(
# text = paste0("m@frame$",
# var1)
var1 <- paste0(var1, levels(
m@frame[,var1]
))
factor_v1 <- TRUE
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,":",var1)[-1])
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) { # if this term is not in the coefficients
var12[i] <- paste0(var1, ":", var2)[-1][i] # then turn the names of the terms around.
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) { # if the turned around version is also not in there => error!
stop(paste("Model does not include the interaction of", var1, "and", var2, "."))
}
}
} else if (
# is.factor(eval(parse(text = paste0("m@frame$", var2))))
is.factor(m@frame[,var2])
) { # if the second variable is a factor
var2_bk <- var2
# var2 <- paste0(var2, levels(eval(parse(
# text = paste0("m@frame$",
# var2)
# ))))
var2 <- paste0(var2, levels(m@frame[,var2]))
factor_v2 <- TRUE
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,":", var1)[-1])
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[-1][i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste("Model does not include the interaction of",var1,"and",var2,"."))
}
}
} else {
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,":", var1))
# the first category is censored to avoid multicolinarity
# TODO this would actually not have to be a for loop.
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
}
if (
# is.factor(eval(parse(text = paste0("m@frame$", var2))))
is.factor(m@frame[,var3])
) { # if the second variable is a factor
stop("The function is currently not implemented for var 3 being a factor")
var3_bk <- var3
# var2 <- paste0(var2, levels(eval(parse(
# text = paste0("m@frame$",
# var2)
# ))))
var3 <- paste0(var3, levels(m@frame[,var3]))
factor_v3 <- TRUE
} else {
# var13
ifelse(
var1 == var3,
stop("The function is currently not implemented for the case in which there is a quadratic term"),
var13 <- paste0(var3,":", var1) # the first category is censored to avoid multicolinarity
)
# TODO this is still from the factor code and not necessary
for (i in seq(var13)) {
if (!var13[i] %in% unlist(dimnames(m@pp$X)[2])) {
var13[i] <- paste0(var1, ":", var3)[i]
}
if (!var13[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste("Model does not include the interaction of",var1,"and",var3,"."))
}
}
# var123
var123 <- paste0(var3,":", var2, ":", var1) # the first category is censored to avoid multicolinarity
for (i in seq(var123)) {
if (!var123[i] %in% unlist(dimnames(m@pp$X)[2])) {
var123[i] <- paste0(var1, ":", var2, ":", var3)[i]
}
if (!var123[i] %in% unlist(dimnames(m@pp$X)[2])) {
var123[i] <- paste0(var2, ":", var1, ":", var3)[i]
}
if (!var123[i] %in% unlist(dimnames(m@pp$X)[2])) {
var123[i] <- paste0(var1, ":", var3, ":", var2)[i]
}
if (!var123[i] %in% unlist(dimnames(m@pp$X)[2])) {
var123[i] <- paste0(var3, ":", var1, ":", var2)[i]
}
if (!var123[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste("Model does not include the interaction of",var1,"and",var3,"."))
}
}
}
# create relevant values of the moderator variables -----------------------
# Steps for var2
if(is.null(var2_vals)) {
if (factor_v2) {
var2_xmin <- 0
var2_xmax <- 1
var2_steps <- 2
} else {
if (is.na(var2_xmin)) {
var2_xmin <- min(m@frame[var2], na.rm = T)
}
if (is.na(var2_xmax)) {
var2_xmax <- max(m@frame[var2], na.rm = T)
}
if (is.null(var2_steps)) {
var2_steps <- length(unique(na.omit(m@frame[, var2])))
# eval(parse(text = paste0(
# "length(unique(na.omit(m@frame$",
# var2, ")))"
# )))
}
if (var2_steps > 100) {
var2_steps <- 100
} # avoid redundant calculation
}
var2_vals <- seq(var2_xmin, var2_xmax, length.out = var2_steps)
} else {
if (is.na(var2_xmin)) {
var2_xmin <- min(var2_vals)
}
if (is.na(var2_xmax)) {
var2_xmax <- max(var2_vals)
}
}
# Steps for var3
if(is.null(var3_vals)) {
if (factor_v3) {
var3_xmin <- 0
var3_xmax <- 1
var3_steps <- 2
} else {
if (is.na(var3_xmin)) {
var3_xmin <- min(m@frame[var3], na.rm = T)
}
if (is.na(var3_xmax)) {
var3_xmax <- max(m@frame[var3], na.rm = T)
}
if (is.null(var3_steps)) {
var3_steps <- length(unique(na.omit(m@frame[, var3])))
# eval(parse(text = paste0(
# "length(unique(na.omit(m@frame$",
# var2, ")))"
# )))
}
if (var3_steps > 100) {
var3_steps <- 100
} # avoid redundant calculation
}
var3_vals <- seq(var3_xmin, xmax_b, length.out = steps_b)
} else {
if (is.na(var3_xmin)) {
var3_xmin <- min(var3_vals)
}
if (is.na(var3_xmax)) {
var3_xmax <- max(var3_vals)
}
}
# get the mean and cis from the simulations -------------------------------
coef <- expand.grid(
fake_var2 = var2_vals,
fake_var3 = var3_vals,
coef1 = NA,
ub = NA,
lb = NA
)
coef_df <- data.frame(
fake_var2 = numeric(0),
fake_var3 = numeric(0),
coef1 = numeric(0),
ub = numeric(0),
lb = numeric(0),
model = character(0)
)
if (factor_v1) {
# TODO make it work for factors
stop("The function is currently not implemented for the case in which the first interaction term is a moderator")
for (j in 1:(length(levels(
# eval(parse(text = paste0("m@frame$",var1_bk)))
m@frame[var1_bk]
)) - 1)) {
# only n - 1 interactions; one category is avoided against
# multicolinarity
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))], (1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var1[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs))
facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(
m = coef_df,
hist = hist,
var2_dt = var2_dt,
point = point,
ercolor = ercolor,
esize = esize,
ralpha = ralpha,
rfill = rfill,
ci_diff = ci_diff,
ks_diff = ks_diff,
stats_cp = stats_cp,
txt_caption = txt_caption,
...
) + facet_grid(. ~ value)
} else if (factor_v2
) {
# TODO make it work for factors no2
stop("The function is currently not implemented for the case in which the first interaction term is a moderator")
for (j in 1:(length(levels(eval(
parse(text = paste0("m@frame$",
var2_bk))
))) - 1)) {
# only n - 1 interactions; one category is avoided against
# multicolinarity
for (i in 1:steps) {
coef$coef1[i] <-
mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
(1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var2[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs))
facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(
m = coef_df,
hist = hist,
var2_dt = var2_dt,
point = point,
ercolor = ercolor,
esize = esize,
ralpha = ralpha,
rfill = rfill,
ci_diff = ci_diff,
ks_diff = ks_diff,
stats_cp = stats_cp,
txt_caption = txt_caption,
...
) + facet_grid(. ~ value)
} else if (factor_v3
) {
# TODO make it work for factors no2
stop("The function is currently not implemented for the case in which the first interaction term is a moderator")
} else {
## Correct marginal effect for quadratic terms
# TODO => if we allow for quadratic terms, bring this part back into the function
# multiplier <- if (var1 == var2) {
# 2
# } else {
# 1
# }
for (i in 1:nrow(coef)) {
# estimates <-
# m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
# coef$fake[i] *
# m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))]
estimates <-
m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] + # effect of negativity
m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))] * # effect of interaction term between negativity X alternatives
coef$fake_var2[i] + # value of variable alternatives
m.sims@fixef[, match(var13, unlist(dimnames(m@pp$X)[2]))] * # effect of interaction term between negativity X ideological distance
coef$fake_var3[i] + # value of ideological distance
m.sims@fixef[, match(var123, unlist(dimnames(m@pp$X)[2]))] * # effect of interaction term between negativity X ideological distance X alternatives
coef$fake_var2[i] * # value of variable alternatives
coef$fake_var3[i] # value of ideological distance
coef$coef1[i] <- mean(estimates)
coef$ub[i] <- quantile(estimates, (1 - ci) / 2)
coef$lb[i] <- quantile(estimates, 1 - (1 - ci) / 2)
}
# min_sim <-
# m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
# multiplier * xmin * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))] # simulation of the value at the minimum value of the conditioning variable
min_sim <- # simulation of the value at the minimum value of the conditioning variable
m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
var2_xmin * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))] +
var3_xmin * m.sims@fixef[, match(var13, unlist(dimnames(m@pp$X)[2]))] +
var2_xmin * var3_xmin * m.sims@fixef[, match(var123, unlist(dimnames(m@pp$X)[2]))]
max_sim <- # simulation of the value at the minimum value of the conditioning variable
m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
var2_xmax * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))] +
var3_xmax * m.sims@fixef[, match(var13, unlist(dimnames(m@pp$X)[2]))] +
var2_xmax * var3_xmax * m.sims@fixef[, match(var123, unlist(dimnames(m@pp$X)[2]))]
diff <- max_sim - min_sim # calculating the difference
ci_diff <- c(quantile(diff, (1 - ci) / 2),
quantile(diff, 1 - (1 - ci) / 2)) # confidence intervals of the difference
if (plot == TRUE) {
if (hist == TRUE) {
# TODO implement this for var3
if (is.na(var2_dt)) {
# var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
var2_dt <- m@frame[,var2]
} #else {
# var2_dt <- var2_dt
# }
}
interplot.plot(
m = coef,
hist = hist,
var2_dt = var2_dt,
point = point,
ercolor = ercolor,
esize = esize,
ralpha = ralpha,
rfill = rfill,
ci_diff = ci_diff,
ks_diff = ks_diff,
stats_cp = stats_cp,
txt_caption = txt_caption,
...
)
} else {
names(coef) <- c(var2, var3, "coef", "ub", "lb")
return(coef)
}
}
# TODO this bracket may not be closed
} else {
# B) 2-way interaction ----------------------------------------------------
if (is.factor(eval(parse(text = paste0(
"m@frame$", var1
)))) &
is.factor(eval(parse(text = paste0(
"m@frame$",
var2
))))) {
stop("The function does not support interactions between two factors.")
}
if (is.factor(eval(parse(text = paste0(
"m@frame$", var1
))))) {
var1_bk <- var1
var1 <- paste0(var1, levels(eval(parse(
text = paste0("m@frame$",
var1)
))))
factor_v1 <- TRUE
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,
":", var1)[-1])
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[-1][i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
} else if (is.factor(eval(parse(text = paste0(
"m@frame$", var2
))))) {
var2_bk <- var2
var2 <- paste0(var2, levels(eval(parse(
text = paste0("m@frame$",
var2)
))))
factor_v2 <- TRUE
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,
":", var1)[-1])
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[-1][i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
} else {
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,
":", var1))
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
}
###################
if (factor_v2) {
xmin <- 0
xmax <- 1
steps <- 2
} else {
if (is.na(xmin)) {
xmin <- min(m@frame[var2], na.rm = T)
}
if (is.na(xmax)) {
xmax <- max(m@frame[var2], na.rm = T)
}
if (is.null(steps)) {
steps <- eval(parse(text = paste0(
"length(unique(na.omit(m@frame$",
var2, ")))"
)))
}
if (steps > 100) {
steps <- 100
} # avoid redundant calculation
}
coef <- data.frame(
fake = seq(xmin, xmax, length.out = steps),
coef1 = NA,
ub = NA,
lb = NA
)
coef_df <- data.frame(
fake = numeric(0),
coef1 = numeric(0),
ub = numeric(0),
lb = numeric(0),
model = character(0)
)
if (factor_v1) {
for (j in 1:(length(levels(eval(
parse(text = paste0("m@frame$",
var1_bk))
))) - 1)) {
# only n - 1 interactions; one category is avoided against
# multicolinarity
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))], (1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var1[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs))
facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(
m = coef_df,
hist = hist,
var2_dt = var2_dt,
point = point,
ercolor = ercolor,
esize = esize,
ralpha = ralpha,
rfill = rfill,
ci_diff = ci_diff,
ks_diff = ks_diff,
stats_cp = stats_cp,
txt_caption = txt_caption,
...
) + facet_grid(. ~ value)
} else if (factor_v2) {
for (j in 1:(length(levels(eval(
parse(text = paste0("m@frame$",
var2_bk))
))) - 1)) {
# only n - 1 interactions; one category is avoided against
# multicolinarity
for (i in 1:steps) {
coef$coef1[i] <-
mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
(1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var2[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs))
facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(
m = coef_df,
hist = hist,
var2_dt = var2_dt,
point = point,
ercolor = ercolor,
esize = esize,
ralpha = ralpha,
rfill = rfill,
ci_diff = ci_diff,
ks_diff = ks_diff,
stats_cp = stats_cp,
txt_caption = txt_caption,
...
) + facet_grid(. ~ value)
} else {
## Correct marginal effect for quadratic terms
multiplier <- if (var1 == var2) {
2
} else {
1
}
for (i in 1:steps) {
coef$coef1[i] <-
mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <-
quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))],
(1 - ci) / 2)
coef$lb[i] <-
quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
multiplier <- if (var1 == var2) {
2
} else {
1
}
min_sim <-
m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * xmin * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))] # simulation of the value at the minimum value of the conditioning variable
max_sim <-
m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * xmax * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))] # simulation of the value at the maximum value of the conditioning variable
diff <- max_sim - min_sim # calculating the difference
ci_diff <- c(quantile(diff, (1 - ci) / 2),
quantile(diff, 1 - (1 - ci) / 2)) # confidence intervals of the difference
if (plot == TRUE) {
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
interplot.plot(
m = coef,
hist = hist,
var2_dt = var2_dt,
point = point,
ercolor = ercolor,
esize = esize,
ralpha = ralpha,
rfill = rfill,
ci_diff = ci_diff,
ks_diff = ks_diff,
stats_cp = stats_cp,
txt_caption = txt_caption,
...
)
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
}
}
#' @export
#'
interplot.glmerMod <- function(m,
var1,
var2,
plot = TRUE,
steps = NULL,
ci = .95,
adjCI = FALSE,
hist = FALSE,
var2_dt = NA,
predPro = FALSE,
var2_vals = NULL,
point = FALSE,
sims = 5000,
xmin = NA,
xmax = NA,
ercolor = NA,
esize = 0.5,
ralpha = 0.5,
rfill = "grey70",
stats_cp = "none",
txt_caption = NULL,
facet_labs = NULL,
...) {
m.class <- class(m)
m.sims <- arm::sim(m, sims)
### For factor base terms###
factor_v1 <- factor_v2 <- FALSE
if (is.factor(eval(parse(text = paste0("m@frame$", var1)))) &
is.factor(eval(parse(text = paste0("m@frame$",
var2))))) {
stop("The function does not support interactions between two factors.")
}
if (is.factor(eval(parse(text = paste0("m@frame$", var1))))) {
var1_bk <- var1
var1 <- paste0(var1, levels(eval(parse(
text = paste0("m@frame$",
var1)
))))
factor_v1 <- TRUE
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,
":", var1)[-1])
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[-1][i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
} else if (is.factor(eval(parse(text = paste0("m@frame$", var2))))) {
var2_bk <- var2
var2 <- paste0(var2, levels(eval(parse(
text = paste0("m@frame$",
var2)
))))
factor_v2 <- TRUE
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,
":", var1)[-1])
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[-1][i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
} else {
ifelse(var1 == var2,
var12 <- paste0("I(", var1, "^2)"),
var12 <- paste0(var2,
":", var1))
# the first category is censored to avoid multicolinarity
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
var12[i] <- paste0(var1, ":", var2)[i]
}
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2])) {
stop(paste(
"Model does not include the interaction of",
var1,
"and",
var2,
"."
))
}
}
}
###################
if (factor_v2) {
xmin <- 0
xmax <- 1
steps <- 2
} else {
if (is.na(xmin)) {
xmin <- min(m@frame[var2], na.rm = T)
}
if (is.na(xmax)) {
xmax <- max(m@frame[var2], na.rm = T)
}
if (is.null(steps)) {
steps <- eval(parse(text = paste0(
"length(unique(na.omit(m@frame$",
var2, ")))"
)))
}
if (steps > 100) {
steps <- 100
} # avoid redundant calculation
}
coef <- data.frame(
fake = seq(xmin, xmax, length.out = steps),
coef1 = NA,
ub = NA,
lb = NA
)
coef_df <- data.frame(
fake = numeric(0),
coef1 = numeric(0),
ub = numeric(0),