-
Notifications
You must be signed in to change notification settings - Fork 0
/
analysis.Rmd
1801 lines (1263 loc) · 52.2 KB
/
analysis.Rmd
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
---
title: "Analysis"
author: "Stefan P. Thoma"
date: "3/10/2020"
output:
rmarkdown::github_document: default
pdf_document: default
---
# Setup
Install / load packages needed:
```{r setup}
knitr::opts_chunk$set(echo = TRUE)
if (!require("pacman")) install.packages("pacman")
p_load(tidyverse, lme4, lmerTest, mvoutlier, nlme, multcomp, lsmeans, xtable, jtools, tikzDevice, gmodels, parallel, performance, optimx, tidylog)
#pacman::p_load_gh("jaredhuling/jcolors")
#jcolors::jcolors("default")
#ggplot <- function(...) ggplot2::ggplot(...) + scale_color_brewer(palette=jcolors::jcolors()) + scale_fill_brewer(palette=jcolors::jcolors()) + #ggplot2::scale_colour_brewer(palette=jcolors::jcolors()) + ggplot2::scale_color_discrete(palette=jcolors::jcolors()) #+ ggplot2::scale_fill_discrete(palette=jcolors::jcolors())
```
```{r}
sessionInfo()
```
## Load Data
```{r load data}
data <- read_csv("data/cleanData.csv")
#data <- data %>% dplyr::select(
# id, time, iat, ccs, nr, nep, ipq, sod, ses, age, edu, sex, pol, vr_exp, vr_eval1, vr_eval2, vr_eval3,
# vr_eval4, vr_eval5, span, seen, condition, starts_with("Frage"), hr_mean, Leiter, Anmerkungen, Zeit
#)
head(data)
# factor for vr or not
data <- data %>% group_by(id) %>%
mutate(
vr = ifelse(condition %in% c("a", "b", "c"), TRUE, FALSE),
type = factor(ifelse(vr, "vr", "control")),
condition = factor(condition, levels = c("b", "a", "c", "video", "text.bild", "text"))
)
```
Keep in mind the conditions coding:
a == abstract
b == realistic
c == realistic but badly so
<!-- ## Check for multivariate outlier -->
<!-- ```{r, eval = FALSE} -->
<!-- # mvoutlier::chisq.plot(data[,c(3:6)]) -->
<!-- # [1] 124 162 161 29 54 -->
<!-- # removing three most extreme cases -->
<!-- rmId <- data$id[c(124, 161, 162)] -->
<!-- data <- data %>% filter(!id %in% rmId) -->
<!-- ``` -->
<!-- ```{r} -->
<!-- data$id[c(142,144,275)] -->
<!-- ``` -->
# Descriptives
## IAT validity
Does IAT correlate to the other measures?
```{r}
cor(data %>% ungroup() %>% dplyr::select(iat, nep, ccs, nr), use = "pairwise.complete.obs")
cor.test.f <- Vectorize(FUN = function(var){
cor.test(data$iat, data[[var]], arg = "two.sided")
})
cor.test.f(c("nep", "ccs", "nr"))
```
The IAT scores correlated significantly with the nr scores (r = 0.137, p = 0.021) and with the nep scores (r = 0.139, p = 0.019) but not significantly with ccs scores (r = -0.054, p = .368).
The signs of the correlations were as expected.
## Reliability
```{r}
vars <- names(data)
ccs.vars <- vars[startsWith(vars, "ccs")]
nr.vars <- vars[startsWith(vars, "nr")]
nep.vars <- vars[startsWith(vars, "nep")]
ipq.vars <- vars[startsWith(vars, "ipq")]
sod.vars <- vars[startsWith(vars, "sod")]
vars.list1 <- list(ccs.vars, nr.vars, nep.vars)
vars.list2 <- list(ipq.vars, sod.vars)
#remove overall score (shortest name)
# this is a bit more robust compared to simply removing the last item
remove_overall <- function(char.vec){
nm <- char.vec[which.min(nchar(char.vec))]
char.vec <- char.vec[-which.min(nchar(char.vec))]
char.vec
}
vars.list1 <- lapply(vars.list1, remove_overall)
vars.list2 <- lapply(vars.list2, remove_overall)
reliable <- function(data, vars){
alph <- psych::alpha(data[vars], title = vars[1])
#omeg <- psych::omega(data[vars], plot = FALSE)
df <- data.frame(alpha = alph$total$raw_alpha, ci.low = alph$total$raw_alpha - 1.96 * alph$total$ase, ci.up = alph$total$raw_alpha + 1.96 * alph$total$ase)
df <- round(df, 3)
df$var = vars[1]
df
}
# measures which are measured twice
alpha.1 <- lapply(vars.list1, function(x) reliable(data = data, x))
# measures which are measured only once (sod and ipq)
alpha.2 <- lapply(vars.list2, function(x) reliable(data = data %>% filter(time == 1), x))
alphas <- c(alpha.1, alpha.2)
(alpha.df <- do.call("rbind", alphas) %>%
dplyr::select(var, alpha, ci.low, ci.up))
```
cronbach alpha of nep is relatively small.
What would mcdonalds omega look like for nep?
```{r}
psych::omega(data[vars.list1[[3]]], nfactors = 1)
```
Omega Total 0.71 seems ok.
### Check NEP structure
```{r}
psych::principal(r = data[nep.vars[-length(nep.vars)]])
```
For the following analysis we reduce the dataframe.
```{r}
data <- data %>% dplyr::select(
id, time, vr, type, condition, iat, ccs, nr, nep, ipq, sod, ses, age, edu, sex, pol, vr_exp, vr_eval1, vr_eval2, vr_eval3, vr_eval4, vr_eval5, span, seen, starts_with("Frage"), hr_mean, Leiter, Anmerkungen, Zeit
)
```
# Principal component analysis
We try to find an acceptable model for each DV.
First, I would like to calculate a principal component of all dependent variables (dvs)
```{r}
df_env <- data[c("iat", "ccs", "nr", "nep")]
psych::fa.parallel(df_env)
prc_env <- princomp(df_env, cor = TRUE)
# Seems like one factor might just be enough. However, this may be more revealing when done
# on raw data
summary(prc_env)
data$env_pc <- prc_env$scores[,1]
```
Unidimensionality could be assumed.
The scores of the first principal component were stored in `data$env_pc`.
This vector can now be used as a dependent variable in further exploratory analyses.
```{r, include = FALSE}
#Some look at the data, e.g. how does the variation within person compare to the variation between people.
#Based on PC1.
data <- as.data.frame(data)
data_grouped <-
groupedData(formula = env_pc ~ time | id,
data = data)
plot(data_grouped, grid = F)
```
This plot is not very useful I guess. Too crowded.
# Check Intervention
This section is concerned only with the VR conditions a, b, c.
Specifically with the variables vr_eval 1:5 and with the sod and presence scale IPQ.
Check for outliers on these scales:
```{r}
#check.data <- data %>% dplyr::filter((vr == T & time == 1 ) & !is.na(ipq))
check.data <- data %>% dplyr::filter((time == 1 ) & !is.na(ipq))
#outlier.data <- data %>% ungroup() %>% dplyr::filter(vr == T & time == 1) %>% dplyr::select(starts_with("vr_eval"), sod, ipq) %>%
# drop_na()
#mvoutlier::chisq.plot(check.data %>% ungroup() %>% dplyr::select(starts_with("vr_eval"), sod, ipq))
# remove: 38 1 63
# which corresponds to the ids:
#remove.ids <- check.data$id[c(38, 1, 63)]
# "44466757" "32504483" "80688810"
```
```{r, include = FALSE}
pacman::p_load(gtable, cowplot)
shift_legend <- function(p){
# check if p is a valid object
if(!"gtable" %in% class(p)){
if("ggplot" %in% class(p)){
gp <- ggplotGrob(p) # convert to grob
} else {
message("This is neither a ggplot object nor a grob generated from ggplotGrob. Returning original plot.")
return(p)
}
} else {
gp <- p
}
# check for unfilled facet panels
facet.panels <- grep("^panel", gp[["layout"]][["name"]])
empty.facet.panels <- sapply(facet.panels, function(i) "zeroGrob" %in% class(gp[["grobs"]][[i]]))
empty.facet.panels <- facet.panels[empty.facet.panels]
if(length(empty.facet.panels) == 0){
message("There are no unfilled facet panels to shift legend into. Returning original plot.")
return(p)
}
# establish extent of unfilled facet panels (including any axis cells in between)
empty.facet.panels <- gp[["layout"]][empty.facet.panels, ]
empty.facet.panels <- list(min(empty.facet.panels[["t"]]), min(empty.facet.panels[["l"]]),
max(empty.facet.panels[["b"]]), max(empty.facet.panels[["r"]]))
names(empty.facet.panels) <- c("t", "l", "b", "r")
# extract legend & copy over to location of unfilled facet panels
guide.grob <- which(gp[["layout"]][["name"]] == "guide-box")
if(length(guide.grob) == 0){
message("There is no legend present. Returning original plot.")
return(p)
}
gp <- gtable_add_grob(x = gp,
grobs = gp[["grobs"]][[guide.grob]],
t = empty.facet.panels[["t"]],
l = empty.facet.panels[["l"]],
b = empty.facet.panels[["b"]],
r = empty.facet.panels[["r"]],
name = "new-guide-box")
# squash the original guide box's row / column (whichever applicable)
# & empty its cell
guide.grob <- gp[["layout"]][guide.grob, ]
if(guide.grob[["l"]] == guide.grob[["r"]]){
gp <- gtable_squash_cols(gp, cols = guide.grob[["l"]])
}
if(guide.grob[["t"]] == guide.grob[["b"]]){
gp <- gtable_squash_rows(gp, rows = guide.grob[["t"]])
}
gp <- gtable_remove_grobs(gp, "guide-box")
return(gp)
}
```
## Plot
```{r}
vars <-c("vr_eval1", "vr_eval2", "vr_eval3", "vr_eval4", "vr_eval5", "ipq", "sod")
desc_plot_data <- gather(data, specific, value, vars) %>%
# filter(!is.na(ipq)) %>%
arrange(id, specific) %>%
mutate(specific = ifelse(specific=="vr_eval1", "excitement",
ifelse(specific=="vr_eval2", "graphically pleasing",
ifelse(specific=="vr_eval3", "pleasant",
ifelse(specific=="vr_eval4", "realistic",
ifelse(specific=="vr_eval5", "enjoyment", specific))))),
VRE = ifelse(condition == "b", "Real+",
ifelse(condition=="c", "Real-",
ifelse(condition=="a", "Abstract", as.character(condition))))) %>%
dplyr::select(specific, value, id, VRE)
(vr_eval_plot <- ggplot(data = desc_plot_data, aes(x = VRE, y = value, color = VRE)) +
facet_wrap( ~specific, nrow = 2)+
geom_violin(draw_quantiles = .5) + #, position = position_jitterdodge(dodge.width = 0.8, jitter.width = 0, jitter.height = 0))+
geom_point(alpha = .3, position = "jitter")+#, position = position_jitterdodge(dodge.width = 0, jitter.width = .2, jitter.height = .3)) +
ggthemes::theme_few() +
ylab("value") +
xlab("")+
# labs(title="")+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())+
scale_y_continuous(breaks = c(1,3,5,7)) +
theme(legend.position = "right") )
```
ipq and sod separately:
```{r, include = FALSE}
ipq_sod_plot_data <- gather(data, scale, value, c("ipq", "sod")) %>%
filter(time==1, condition %in% c("a", "b", "c", "video")) %>%
arrange(id, scale) %>%
mutate(VRE = ifelse(condition == "b", "R+",
ifelse(condition=="c", "R-",
ifelse(condition == "a", "A+", condition)))) %>%
dplyr::select(scale, value, id, VRE)
ipq_sod_plot <- ggplot(data = ipq_sod_plot_data, aes(x = VRE, y = value, color = VRE)) +
facet_wrap(~scale, ncol = 2)+
geom_violin(draw_quantiles = .5, position = position_jitterdodge(dodge.width = 0.8, jitter.width = 0, jitter.height = 0))+
geom_point(alpha = .3, position = position_jitterdodge(dodge.width = 0.8, jitter.width = .2, jitter.height = .1)) +
ggthemes::theme_tufte() +
ylab("scores") +
xlab("scale")+
#labs(title="Presence (IPQ) and Suspension of Disbelief (SOD)")+
scale_y_continuous(breaks = c(1,3,5,7), limits = c(1,7)); ipq_sod_plot
```
## compare initial dv values
Vector containing name of all dv's
```{r}
dvs <- c("iat", "ccs", "nr", "nep", "env_pc")
```
Mean dvs at time point 1.
```{r}
data.dv1 <- data %>% filter(time==1) %>%
dplyr::mutate(condition = ifelse(condition =="b", "real+",
ifelse(condition == "c", "real-",
ifelse(condition == "a", "abstract", as.character(condition)))),
condition = as.factor(condition))
(summar.cond <- data.dv1 %>% group_by(condition, type) %>%
summarise(mean_iat = mean(iat),
mean_ccs = mean(ccs),
mean_nr = mean(nr),
mean_nep = mean(nep)))
(summar.vr <- data.dv1 %>% group_by(type) %>%
summarise(mean_iat = mean(iat),
mean_ccs = mean(ccs),
mean_nr = mean(nr),
mean_nep = mean(nep)))
contrasts(data.dv1$condition) <- contr.sum(n = 6)
contrasts(data.dv1$condition)
lapply(dvs, function(x){
print(x)
summary(lm(get(x)~condition, data = data.dv1))
})
```
# HLM
So we will create two models for each dependent variables:
First, the model will have the formula:
`dv ~ condition * time + (time | id)`
This will be simplified to the following model if model fit is singular:
`dv ~ condition * time + (1 | id)`
This will estimate a random intercept for each participant.
This model will only take as input the vr conditions (`a`, `b` & `c`), or: `vr == TRUE`.
The second model will have the formula:
`dv ~ vr * time + (time | condition) + (1 | id)`
Where a random slope for time is estimated per condition.
Further, there is a random intercept per condition, and per id.
Should model fit be singular, we would simplify the model to:
`dv ~ vr * time + (1 | condition) + (1 | id)`
If still singular, we would simplify to:
`dv ~ vr * time + (1 | id)`
## Helping function
```{r}
fit.lme <- function(form, dat){
lme4::lmer(formula = form, data = dat)
#lme4::lmer(formula = form, data = dat,
# control = lmerControl(optimizer = "optimx", optCtrl = list(method = "nlminb", starttests = FALSE, kkt = FALSE))) # alternative optimizer
}
```
```{r}
fit_models <- function(dv, dat){
# this function returns a function which fits a model based on a formula minus the predictors.
# This function can be used in the next function which implements the conditions for reducing model complexity if model fit is singular.
function(predictors){
form <- formula(paste(dv, predictors, sep = " ~ "))
print(form)
fit <- fit.lme(form = form, dat = dat)
}
}
```
```{r}
predictors.vr <- c("condition * time + (time | id)", "condition * time + (1 | id)")
predictors.all <- c("time*type + (time | condition) + (1 | id)", "time * type + (-1 + time | condition) + (1 | id)", "time * type + (1 | id)")
#predictors.all2 <- c("vr * time + (time | condition) + (1 | id)", "vr * time + (1 | condition) + (1 | id)", "vr * time + (1 | id)")
#predictors.all3 <- c("vr * time + (time | condition) + (1 | id)", "vr * time + (-1 + time | condition) + (1 | id)", "vr * time + (1 | id)")
# function to fit various models based on different inputs of predictors
fit_many <- function(pred.vector, dat, dv){
fit_model <- fit_models(dv, dat)
sing <- TRUE
i <- 1
while((sing) & i<=length(pred.vector)){
model <- try(fit_model(pred.vector[i]))
if(class(model)!="try-error"){
sing <- isSingular(model)
}
i <- i + 1
}
print(paste("is model singular: ", sing))
model
}
```
```{r}
# split data frame:
data.vr <- data %>% dplyr::filter(vr)
```
Contrast:
We want the effect of "time" to be the average effect over all conditions.
Therefore we set the contrast of the condition variable to `contr.sum` in accordance with https://stats.oarc.ucla.edu/r/library/r-library-contrast-coding-systems-for-categorical-variables/#DEVIATION.
This is sometimes called `unweighted effect coding` or `deviation coding`.
```{r}
data.vr$condition <-droplevels(data.vr$condition)
contrasts(data.vr$condition) <- contr.sum(3)
contrasts(data$type) <- contr.sum(2)
```
## Initial model fitting
```{r}
vr.models <- lapply(dvs, FUN = function(dv) fit_many(pred.vector = predictors.vr, dat = data.vr, dv = dv))
```
```{r}
all.models <- lapply(dvs, FUN = function(dv) fit_many(pred.vector = predictors.all, dat = data, dv = dv))
```
```{r}
presence.models <- lapply(dvs, FUN = function(dv) fit_many(pred.vector = "ipq * time + (1 | id)", dat = data.vr, dv = dv))
```
```{r}
sod.models <- lapply(dvs, FUN = function(dv) fit_many(pred.vector = "sod * time + (1 | id)", dat = data.vr, dv = dv))
```
<!-- ```{r, include = FALSE} -->
<!-- all.models2 <- lapply(dvs, FUN = function(dv) fit_many(pred.vector = predictors.all2, dat = data, dv = dv)) -->
<!-- ``` -->
<!-- ```{r, include = FALSE} -->
<!-- #NEP -->
<!-- anova(all.models2[[4]], all.models[[4]]) -->
<!-- all.models2[[4]] -->
<!-- all.models[[4]] -->
<!-- ``` -->
## Model diagnostics
I save model diagnostics as pdfs separately, for visibility reasons.
```{r}
plot_diagn <- function(model){
filename <- paste( model@call$formula[2], sub("\\ .*", "", model@call$formula[3]), sep = "_")
png(filename = paste("analysisOutputs/diagnostics/", filename, ".png", sep = ""), # The directory you want to save the file in
#paper = "a3",
height = 5900/4,
width = 4200/4
)
print(performance::check_model(model) )
dev.off()
}
```
```{r, eval = TRUE}
lapply(vr.models, FUN = plot_diagn)
lapply(all.models, FUN = plot_diagn)
```
I focus model diagnostic on the vr models.
They include all data.
Residuals are slightly left skewed.
However, this does not yet warrant a transformation of the dv in my opinion.
### IAT
```{r, include=TRUE, fig.align="center", fig.cap=c("iat_vr_diagnostics"), echo=FALSE, fig.height=5.9*4,fig.width=4.2*4}
knitr::include_graphics("analysisOutputs/diagnostics/iat_vr.png")
```
Some thoughts:
Band of residuals increases as fitted values increase.
Homogeneity of variance seems acceptable.
Random effects appear normal.
### CCS
First some descriptives about ccs.
```{r}
data %>% group_by(as.factor(time)) %>%
summarise(mean = mean(ccs),
range = range(ccs),
median = median(ccs))
```
```{r, include=TRUE, fig.align="center", fig.cap=c("ccs_vr_diagnostics"), echo=FALSE, fig.height=5.9*4,fig.width=4.2*4}
knitr::include_graphics("analysisOutputs/diagnostics/ccs_vr.png")
```
Some thoughts:
Homogeneity of variance appears implausible.
Residual variance increases with larger fitted values.
Residuals are also not normally distributed.
Random effects do not appear normal.
The reason for this unexpected behaviour may well be the floor-effect of the dv ccs.
There was generally a very low ccs score for participants.
This is due to the relatively extreme nature of climate change scepticism, especially in a relatively well educated sample.
Maybe a boxcox transformation may help:
```{r, fig.height=5.9*4,fig.width=4.2*4}
#estimate lambda of the boxcox transformation
bc <- boxcox(ccs ~ vr * time, data = data)
lambda_ccs <- bc$x[which.max(bc$y)]
# transform data according to the transformation
data <- data %>%
mutate(ccs_bc = (ccs^lambda_ccs-1)/lambda_ccs)
# refit the model
all.ccs2 <- fit_many(pred.vector = predictors.all, dat = data, dv = "ccs_bc")
performance::check_model(all.ccs2)
```
The situation has improved!
All model assumptions appear plausible.
```{r}
all.models[[2]] <- all.ccs2
```
For within the VE:
```{r, include=TRUE, fig.align="center", fig.cap=c("ccs_condition_diagnostics"), echo=FALSE, fig.height=5.9*4,fig.width=4.2*4}
knitr::include_graphics("analysisOutputs/diagnostics/ccs_condition.png")
```
And based on the transformed ccs:
```{r, fig.height=5.9*4,fig.width=4.2*4}
data.vr <- data.vr %>%
mutate(ccs_bc = (ccs^lambda_ccs-1)/lambda_ccs)
vr.ccs2 <- fit_many(pred.vector = predictors.vr, dat = data.vr, dv = "ccs_bc")
performance::check_model(vr.ccs2)
```
```{r}
vr.models[[2]] <- vr.ccs2
```
### NR
```{r, include=TRUE, fig.align="center", fig.cap=c("nr_vr_diagnostics"), echo=FALSE, fig.height=5.9*4,fig.width=4.2*4}
knitr::include_graphics("analysisOutputs/diagnostics/iat_vr.png")
```
Model assumptions are not too far off:
Slight slope in the "fitted vs residuals".
Homogeneity assumption is appropriate.
Residual distribution is slightly skewed with a heavy left tail.
ID intercept distribution is not quite normal, but not far from it.
Slightly skewed as well.
Overall assumptions seem acceptable and warrant no further action.
### NEP
```{r, include=TRUE, fig.align="center", fig.cap=c("nep_vr_diagnostics"), echo=FALSE, fig.height=5.9*4,fig.width=4.2*4}
knitr::include_graphics("analysisOutputs/diagnostics/nep_vr.png")
```
Model assumptions are not too far off:
Slight slope in the "fitted vs residuals".
Residuals appear normally distributed, slightly skewed to the right.
Overall assumptions seem acceptable and warrant no further action.
### Principal component
```{r, include=TRUE, fig.align="center", fig.cap=c("env_pc_vr_diagnostics"), echo=FALSE, fig.height=5.9*4,fig.width=4.2*4}
knitr::include_graphics("analysisOutputs/diagnostics/env_pc_vr.png")
```
```{r}
min(data$env_pc)
data$env_pc2 <- data$env_pc + 6
#estimate lambda of the boxcox transformation
bc <- boxcox(env_pc2 ~ vr * time, data = data)
lambda_pc <- bc$x[which.max(bc$y)]
# transform data according to the transformation
data <- data %>%
mutate(env_pc_bc = (env_pc2^lambda_pc-1)/lambda_pc)
# refit the model
all.env_pc2 <- fit_many(pred.vector = predictors.all, dat = data, dv = "env_pc_bc")
performance::check_model(all.env_pc2)
```
Transformation does not help much here. Lets not do it.
But let us save the final model diagnostics plots as well.
```{r, eval = TRUE}
lapply(vr.models, FUN = plot_diagn)
lapply(all.models, FUN = plot_diagn)
```
## Inference
### vr vs control
```{r}
lapply(all.models, FUN = lmerTest:::summary.lmerModLmerTest)
```
Follow up tests:
```{r}
# iat
contrast( emmeans(all.models[[1]], ~ time | type))
# ccs
contrast( emmeans(all.models[[2]], ~ time | type))
# nr
contrast( emmeans(all.models[[3]], ~ time | type))
# nep
contrast( emmeans(all.models[[4]], ~ time | type))
```
### Within the VEs (condition)
```{r}
lapply(vr.models, FUN = lmerTest:::summary.lmerModLmerTest)
```
contrast analysis:
```{r}
# iat
contrast( emmeans(vr.models[[1]], ~ time | condition))
# ccs
contrast( emmeans(vr.models[[2]], ~ time | condition))
# nr
contrast( emmeans(vr.models[[3]], ~ time | condition))
# nep
contrast( emmeans(vr.models[[4]], ~ time | condition))
```
#### Model comparisons
For the three VE conditions we need ot test the predictor `condition` with model comparisons.
```{r}
compare.models <- function(model){
model0 <- update(model, .~. - time:condition)
anova(model0, model)
}
lapply(vr.models, compare.models)
```
The condition:time interaction did not significantly add to the explained variance.
<!-- # old code -->
<!-- #### HLM helper -->
<!-- ```{r} -->
<!-- rmlm <- function(dv, condition = "condition", cov = NULL, ...){ -->
<!-- ########## -->
<!-- #dv <- "nep" -->
<!-- #condition = "vr" -->
<!-- #cov = c("age", "gender") -->
<!-- ########## -->
<!-- iv <- numeric(4) -->
<!-- iv[1] <- "1" -->
<!-- iv[2] <- "time" -->
<!-- iv[3] <- paste(iv[2], condition, sep = " + ") -->
<!-- iv[4] <- paste(iv[3], paste("time", condition, sep = ":"), sep = " + ") -->
<!-- if(!is_null(cov)){ -->
<!-- models <- paste(paste(dv, " ~ ", sep = ""), iv," + ", paste(cov, collapse = " + ")," + (1|id)", sep = "") -->
<!-- } else { -->
<!-- if(condition == "vr"){ -->
<!-- models <- paste(paste(dv, " ~ ", sep = ""), iv," + (1|id) + (1|condition)", sep = "") -->
<!-- } else {models <- paste(paste(dv, " ~ ", sep = ""), iv," + (1|id)", sep = "")} -->
<!-- } -->
<!-- models <- lapply(models, as.formula) -->
<!-- fits <- lapply(models, fit.lme, ...) -->
<!-- names(fits) <- models -->
<!-- summaries <- lapply(fits, summary) -->
<!-- names(summaries) <- models -->
<!-- anova.list <- anova(fits[[1]], fits[[2]], fits[[3]], fits[[4]]) -->
<!-- ret.list <- list("fits" = fits, "summaries" = summaries, "model.comp" = anova.list) -->
<!-- return(ret.list) -->
<!-- } -->
<!-- ``` -->
<!-- ```{r} -->
<!-- # get model comp -->
<!-- get.comp <- function(rmlm.list, type = "comp"){ -->
<!-- if(type == "comp"){ -->
<!-- for(i in 1:length(rmlm.list)){ -->
<!-- print(rmlm.list[[i]]$model.comp) -->
<!-- } -->
<!-- } -->
<!-- if(type == "fit"){ -->
<!-- models <- list() -->
<!-- for(i in 1:length(rmlm.list)){ -->
<!-- models[[i]] <- rmlm.list[[i]]$fits -->
<!-- } -->
<!-- return(models) -->
<!-- } -->
<!-- } -->
<!-- ``` -->
<!-- ### Fit -->
<!-- Here, we will see a lot of model comparisons. -->
<!-- This indicates, whether including the interaction effect makes sense and thus whether there was an effect of `condition` on the dv. -->
<!-- #### Separate for vr == TRUE -->
<!-- ```{r} -->
<!-- dvs <- c("iat", "ccs", "nr", "nep", "env_pc") -->
<!-- vr.res <- lapply(dvs, rmlm, dat = data %>% filter(vr == TRUE)) -->
<!-- get.comp(vr.res) -->
<!-- ``` -->
<!-- So what we saw here: -->
<!-- *IAT* -->
<!-- Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) -->
<!-- iat ~ time + condition + (1 | id) -->
<!-- 6 167.01 184.49 -77.508 155.01 7.8935 2 0.01932 -->
<!-- *CCS* -->
<!-- ccs ~ 1 + (1 | id) -->
<!-- 3 104.85 113.59 -49.427 98.853 -->
<!-- *NEP* -->
<!-- nep ~ time + (1 | id) -->
<!-- 4 74.880 86.530 -33.440 66.880 8.3113 1 0.00394 -->
<!-- *NR* -->
<!-- nr ~ time + condition + (1 | id) -->
<!-- 6 91.087 108.56 -39.543 79.087 12.7669 2 0.001689 -->
<!-- There seems to be no significant interaction effect between condition and time. -->
<!-- ```{r} -->
<!-- control.res <- lapply(dvs, rmlm, dat = data %>% filter(vr == FALSE)) -->
<!-- get.comp(control.res) -->
<!-- ``` -->
<!-- RM-Anova shows that for all dependent variables, the control group conditions likely did not have any effect. -->
<!-- This result is without including any covariates. -->
<!-- #### Effect of VR -->
<!-- ```{r} -->
<!-- ## VR vs non-VR -->
<!-- vr.vs.nonvr.res <- lapply(dvs, rmlm, dat = data, condition = "vr") -->
<!-- lapply(vr.vs.nonvr.res[[2]]$fits, anova) -->
<!-- get.comp(vr.vs.nonvr.res) -->
<!-- ``` -->
<!-- When looking at the IAT and the first component score, the interaction of time and VR might have an effect. -->
<!-- However, this is without adjusting for multiple testing and again without incorporating covariates. -->
<!-- ## Best models: -->
<!-- ```{r} -->
<!-- # first for condition: -->
<!-- cond.models <- lapply(dvs, rmlm, dat = data) -->
<!-- vr.models <- lapply(dvs, rmlm, dat = data, cond = "vr") -->
<!-- # best models according to get.comp(cond.models) -->
<!-- best.cond <- list("IAT" = cond.models[[1]]$fits[[2]], "CCS" = cond.models[[2]]$fits[[1]], "NEP" = cond.models[[3]]$fits[[1]], "NR" = cond.models[[4]]$fits[[2]]) -->
<!-- # best models according to get.comp(vr.models) -->
<!-- best.vr <- list("IAT" = vr.models[[1]]$fits[[3]], "CCS" = vr.models[[2]]$fits[[1]], "NEP" = vr.models[[3]]$fits[[1]], "NR" = vr.models[[4]]$fits[[1]]) -->
<!-- best.models <- list("Condition" = best.cond, "VR" = best.vr) -->
<!-- ``` -->
<!-- # Some Plots -->
<!-- ```{r} -->
<!-- data <- data %>% -->
<!-- group_by(id) %>% -->
<!-- mutate(iat_diff = iat[time == 2]- iat[time == 1], -->
<!-- ccs_diff = ccs[time == 2]- ccs[time == 1], -->
<!-- nep_diff = nep[time == 2]- nep[time == 1], -->
<!-- nr_diff = nr [time == 2]- nr [time == 1] -->
<!-- ) -->
<!-- data.plot <- data %>% -->
<!-- gather(key = dv, value = value, iat_diff:nr_diff) %>% -->
<!-- filter(time == 1) -->
<!-- label <- paste(rep(c("ccs", "iat", "nep", "nr"), each = 2), c(" 2D", " vr"), sep = "") -->
<!-- ggplot(data = data.plot, aes(y = value, x = interaction(vr, dv), col = vr, shape = vr)) + -->
<!-- geom_jitter(width = .05) + -->
<!-- geom_boxplot() + -->
<!-- scale_x_discrete(labels = label) -->
<!-- ``` -->
<!-- ```{r} -->
<!-- data.plot2 <- data %>% -->
<!-- filter(time == 1) -->
<!-- plotcond <- function(dv, data2 = data.plot2){ -->
<!-- #data2 <- data.plot2 -->
<!-- data2$dv <- data2[[dv]] -->
<!-- ggplot(data = data2, aes(y = `$`(data2, dv), x = condition, col = condition, shape = vr)) + -->
<!-- geom_jitter(width = .05) + -->
<!-- geom_boxplot(fill = NA)+ -->
<!-- geom_abline(intercept = 0, slope = 0, size = .1)+ -->
<!-- ylab(dv) + -->
<!-- ggthemes::theme_tufte() + -->
<!-- ggtitle(paste("Difference of ", dv, " values by condition", sep = "")) -->
<!-- } -->
<!-- diff_dvs <- colnames(data %>% dplyr::select(ends_with("diff")))[-1] -->
<!-- lapply(diff_dvs, plotcond) -->
<!-- ``` -->
### Presence & SOD
```{r}
lapply(presence.models, FUN = lmerTest:::summary.lmerModLmerTest)
```
```{r}
lapply(sod.models, FUN = lmerTest:::summary.lmerModLmerTest)
```
# Export
## Correlation table
```{r}
lower <- round(cor(data[dvs[-5]]),2)
lower[upper.tri(lower)] <- ""
lower <- as.data.frame(lower)
rownames(lower) <- toupper(rownames(lower))
colnames(lower) <- toupper(colnames(lower))
print(xtable(lower, label = "tab:cortable",
caption = "Correlation table of the four environmental attitudes measures. Computed on the untranformed CCS scale."), file = "analysisOutputs/tables/correlationtable.tex")
```
## Tables for models
First, we define a couple of helping functions
```{r}
#lmermods = all.models
# x <- lmermods[[1]]
make.x.table <- function(lmermods, save = TRUE, add = ""){
#lapply(lmermods, function(x) formula(x)[2])
dvs <- as.character(lapply(lmermods, function(x) as.character(formula(x)[2])))
iv <- sub("\\ .*", "", lmermods[[1]]@call$formula[3])
helpf <- function(x){
# get fixed effects table