-
Notifications
You must be signed in to change notification settings - Fork 0
/
Supplemental-Material-A-Annotated-Analysis.Rmd
12667 lines (11230 loc) · 445 KB
/
Supplemental-Material-A-Annotated-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: "Supplemental Information A: Full Annotated Analysis and Reproducible Code"
subtitle: "Supplemental Material for 'Psychological Needs During Intergroup Contact: Three Experience Sampling Studies'"
author:
- Jannis Kreienkamp^1^
- Maximilian Agostini^1^
- Laura F. Bringmann^1^
- Peter de Jonge^1^
- Kai Epstude^1^
- ^1^University of Groningen, Department of Psychology
- "Author Information:"
- "Correspondence concerning this article should be addressed to ██████ ██████████, ██████████ ██ ██████████, █████████ ██ ██████████, █████ ██████████ ███, ████ ██ █████████ ████████████████. E-mail: █████████████████"
- 'The main manuscript is available at <a href="https://www.doi.org/ToBePublished" target="_blank">doi.org/ToBePublished</a>'
- 'The data repository for this manuscript is available at <a href="https://osf.io/pr9zs/?view_only=1ea47bb646694632a764dead807ef970" target="_blank">osf.io/pr9zs/?view_only=1ea47bb646694632a764dead807ef970</a>'
- 'The GitHub repository for this manuscript is available at <a href="https://github.com/maskedForPeerReview" target="_blank">github.com/maskedForPeerReview</a>'
date: "Last updated: `r format(Sys.time(), '%d %B, %Y')`"
output:
bookdown::html_document2:
fig_caption: yes
md_extensions: +footnotes
code_folding: hide
mathjax: default
theme: yeti
toc: yes
toc_float: yes
number_sections: false
css: style.css
includes:
in_header: "_includes/head-custom-rmd.html"
editor_options:
chunk_output_type: console
bibliography: references.bib
csl: apa.csl
header-includes:
- \usepackage{amsmath, nccmath}
---
<style type="text/css">
.main-container {
max-width: 1300px;
margin-left: auto;
margin-right: auto;
}
.table {
margin-left:auto;
margin-right:auto;
}
</style>
```{r setup, include=FALSE}
# R Studio Clean-Up
cat("\014") # clear console
# rm(list=ls()) # clear workspace - use restart R instead [cmd/alt + shift + F10]
gc() # garbage collector
# Install and Load Packages
# !IMPORTANT!
# BEFORE FIRST RENDER:
# To install all relevant packages please run "renv::restore()" (or renv::init() and then initiate from lockfile) in the console before the first use to ensure that all packages are using the correct version.
# to store the packages in a contained library within the project folder: renv::settings$use.cache(FALSE) and add 'RENV_CONFIG_SANDBOX_ENABLED = FALSE' to an '.Renviron' file
lib <- c(
"rmarkdown",
"knitr",
"remedy",
"bookdown",
"brms",
"psych",
"ggplot2",
"ggthemes",
"haven",
"RColorBrewer",
"plotly",
"gridExtra",
"ggpattern",
"ggridges",
"lme4",
"nlme",
"jtools",
"gtsummary",
"sessioninfo",
"tibble",
"pander",
"devtools",
"mada",
"data.table",
#"tidyr",
#"tidyverse",
"plyr",
"dplyr",
"Hmisc",
"kableExtra",
"papaja",
"stringr",
"stringi",
"reshape2",
"lubridate",
"purrr",
"metafor"
)
invisible(lapply(lib, library, character.only = TRUE))
rm(lib)
# Load Custom Packages
source("./scripts/functions/fun.panel.R")
source("./scripts/functions/themes.R")
source("./scripts/functions/binaryCor.R")
source("./scripts/functions/MlCorMat.R")
source("./scripts/functions/MlTbl.R")
source("./scripts/functions/metaLmer.R")
# Markdown Options
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file()) # set working directory
knitr::opts_knit$get("root.dir") # check working directory
options(
scipen = 999,
digits = 4,
width = 400
) # removes scientific quotation
# knitr::opts_chunk$set(echo = TRUE, cache = F, cache.path = rprojroot::find_rstudio_root_file('cache/')) # cache settings
knitr::knit_hooks$set(
error = function(x, options) {
paste('\n\n<div class="alert alert-danger">',
gsub("##", "\n", gsub("^##\ Error", "**Error**", x)),
"</div>",
sep = "\n"
)
},
warning = function(x, options) {
paste('\n\n<div class="alert alert-warning">',
gsub("##", "\n", gsub("^##\ Warning:", "**Warning**", x)),
"</div>",
sep = "\n"
)
},
message = function(x, options) {
paste('\n\n<div class="alert alert-info">',
gsub("##", "\n", x),
"</div>",
sep = "\n"
)
}
)
htmltools::tagList(rmarkdown::html_dependency_font_awesome())
# Global Chunk Options
knitr::opts_chunk$set(
fig.width = 12,
fig.height = 8,
fig.path = "Figures/",
echo = TRUE,
cache = TRUE,
warning = FALSE,
message = FALSE
)
# set ggplot theme
theme_set(theme_Publication())
```
<br/>
<i class="fas fa-exclamation-circle"></i> Note. Boxplots display the interquartile range (IQR, center box), and the whiskers extend 1.5*IQR from the lower and upper hinge. The white point indicates the mean and the white center line indicates the median.
<br/>
<i class="fas fa-exclamation-circle"></i> Note. All multilevel assumptions are tested as usual including (e.g., for random slopes model with _j_ within person predictors):
$$
\begin{align}
&\textrm{Level 1 Variance:}\ e_{ti} \sim \mathcal{N}(0,\sigma^2) \\
&\textrm{Level 2 Variance:}\ \begin{bmatrix} u_{0i}\\ \vdots\\ u_{ji}\end{bmatrix}
\sim \mathcal{N}
\begin{pmatrix}
\begin{bmatrix}
0 \\
\vdots \\
0
\end{bmatrix},
\begin{bmatrix}
\tau_{00}^2 & & \\
\vdots & \ddots & \\
\tau_{j0} & \ldots & \tau_{jj}^2
\end{bmatrix}
\end{pmatrix}
\end{align}
$$
</br>
<!-- <i class="fas fa-exclamation-circle"></i> Note. Multilevel effect size could be: -->
<!-- \begin{equation} -->
<!-- (\#eq:MlEffectSize) -->
<!-- f_b^2 = \frac{R_{ab}^2 - R_a^2}{1 - R_{ab}^2} \\ -->
<!-- R^2 = \frac{V_{null} - V_{model}}{V_{null}} \\ -->
<!-- f_b^2 = \frac{\frac{V_{null} - V_{ab}}{V_{null}} - \frac{V_{null} - V_{a}}{V_{null}}}{1 - \frac{V_{null} - V_{ab}}{V_{null}}} -->
<!-- \end{equation} -->
<!-- <br/> -->
# **Data Preparation**
In an initial preparatory step, we import the data into the R project environment and prepare the variables for further processing and later analyses.
## Data Import
The data were collected using two different survey tools. For the study with sojourners (Study 1: worker) we used the survey platform Qualtrics XM, whereas the studies with international students (Study 2: student), and the international medical professionals (Study 3: medical) were conducted using the survey framework FormR. This means that the datasets had inconsistent file formats and naming conventions. For the Qualtrics study we pre-processed some variables to ease the import process (for the syntax files see the SPS files in '_data/S1_Workers/processed/cleaned_' and for the raw data files see '_data/S1_Workers/raw_'). For the two other studies, we import the raw csv files from their respective folders.
```{r formrImport}
# workers
# initial data cleaning was done in SPSS (syntax files are available in "")
dtWorker <- list(
raw.pre = read_spss("data/S1_Workers/processed/cleaned/MT - Pre-Measure - 06-15-2018.sav"),
raw.post = read_spss("data/S1_Workers/processed/cleaned/MT - Post-Measure - 06-15-2018.sav"),
raw.morning = read_spss("data/S1_Workers/processed/cleaned/MT - Morning - 06-15-2018.sav"),
raw.afternoon = read_spss("data/S1_Workers/processed/cleaned/MT - Afternoon - 06-15-2018.sav")
)
# students
dtStudents <- list(
raw.pre = read.csv(file = "data/S2_Students/raw/AOTS_Pre.csv", header = T, sep = ","),
raw.post = read.csv(file = "data/S2_Students/raw/AOTS_Post.csv", header = T, sep = ","),
raw.daily = read.csv(file = "data/S2_Students/raw/AOTS_Daily.csv", header = T, sep = ",")
)
# young medical professionals
dtMedical <- list(
raw.eligibility = read.csv("data/S3_Medical/raw/AOTM_Eligibility.csv"),
raw.pre = read.csv("data/S3_Medical/raw/AOTM_Pre.csv"),
raw.post = read.csv("data/S3_Medical/raw/AOTM_Post.csv"),
raw.daily = read.csv("data/S3_Medical/raw/AOTM_Daily.csv")
)
# goal-directedness coding
goal_topics <- read.csv("data/goal_topics/outgroup_interactions-all_ppt_goals_with_topics.csv")
goal_directedness_coding <- read.csv("data/goal_topics/outgroup_interaction_need_topics_goal_directedness_coding.csv")
```
## Data Cleaning & Data Exclusions
### Study 1
For the sojourner sample data was collected in four separate surveys: (1) the pre-measurement, (2) the daily morning survey, (3) the daily afternoon survey, as well as (4) a post-measurement. We combine the four individual surveys into one cohesive dataframe and drop superfluous variables that are not relevant to the analyses relevant here. We then format the time and date variables and add person- and measurement indices (for easy and meaningful addressing of the data). We also exclude our own test data.
<i class="fas fa-info-circle"></i> _Note:_ All data preparation steps are saved in the '_dtWorker_' list.
```{r cleanWorker}
# important names for Morning and Afternoon
names.m <- c(
"StartDate",
"EndDate",
"Finished",
"Duration__in_seconds_",
"RecordedDate",
"ExternalReference",
"Meta_Operating_System",
"Contact_dum",
"number",
"time",
"duration_1",
"dyad.group",
"gr_size",
"gr_type_1",
"gr_type_2",
"gr_type_3",
"gr_type_4",
"gr_type_5",
"gr_type_6",
"gr_type_7",
"gr_type_8",
"gr_type_9",
"gr_type_10",
"gr_type_11",
"gr_type_12",
"gr_type_13",
"gr_type_14",
"gr_type_15",
"gr_type_16",
"gr_type_17_TEXT",
"gr_context_1",
"gr_context_2",
"gr_context_3",
"gr_context_4",
"gr_context_5",
"gr_context_6",
"gr_context_7",
"gr_context_8",
"gr_context_9",
"gr_context_10",
"gr_context_11",
"gr_context_12",
"gr_context_13_TEXT",
"gr_context_14_TEXT",
"gr_dutchness",
"dyad_type_1",
"dyad_type_2",
"dyad_type_3",
"dyad_type_4",
"dyad_type_5",
"dyad_type_6",
"dyad_type_7",
"dyad_type_8",
"dyad_type_9",
"dyad_type_10",
"dyad_type_11",
"dyad_type_12",
"dyad_type_13",
"dyad_type_14",
"dyad_type_15",
"dyad_type_16",
"dyad_type_17_TEXT",
"Context_1",
"Context_2",
"Context_3",
"Context_4",
"Context_5",
"Context_6",
"Context_7",
"Context_8",
"Context_9",
"Context_10",
"Context_11",
"Context_12",
"Context_13_TEXT",
"Context_14_TEXT",
"keyMotive",
"keymotive_fulfillemt_1",
"keyMotive_Dutch_1",
"autonomy_1",
"competence_1",
"relatedness_self_1",
"relatedness_other_1",
"qualityAccidental_1",
"qualityVoluntary_1",
"qualityCooperative_1",
"qualityDutchy_1",
"quality_overall_1",
"quality_meaning_1",
"quality_star_1",
"wantInt",
"desire_type_1",
"desire_type_2",
"desire_type_3",
"desire_type_4",
"desire_type_5",
"desire_type_6",
"desire_type_7",
"desire_type_8",
"desire_type_9",
"desire_type_10",
"desire_type_11",
"desire_type_12",
"desire_type_13",
"desire_type_14",
"desire_type_15",
"desire_type_16",
"desire_type_17_TEXT",
"desire_context_1",
"desire_context_2",
"desire_context_3",
"desire_context_4",
"desire_context_5",
"desire_context_6",
"desire_context_7",
"desire_context_8",
"desire_context_9",
"desire_context_10",
"desire_context_11",
"desire_context_12",
"desire_context_13_TEXT",
"desire_context_14_TEXT",
"Reason_nodesire",
"keyMotive_noInt",
"keyMotive_noInt_fulf_1",
"autonomy_NoInt_1",
"competence_NoInt_1",
"relatedness_1_NoInt_1",
"thermometerDutch_1",
"thermometerDutchInt_2",
"ExWB_1",
"alertness1",
"calmness1",
"valence1",
"alertness2",
"calmness2",
"valence2",
"inNonDutch",
"NonDutchNum",
"NonDutchType_1",
"NonDutchType_2",
"NonDutchType_3",
"NonDutchType_4",
"NonDutchType_5",
"NonDutchType_6",
"NonDutchType_7",
"NonDutchType_8",
"NonDutchType_9",
"NonDutchType_10",
"NonDutchType_11",
"NonDutchType_12",
"NonDutchType_13",
"NonDutchType_14",
"NonDutchType_15_TEXT",
"date",
"time.0",
"LocationLatitude",
"LocationLongitude"
)
names.a <- c(names.m, "keyInteraction_1", "keyInteractionTime")
# Create reduced data sets for morning and afternoon
dat.mo <- dtWorker$raw.morning[, names.m]
dat.mo$daytime <- "morning"
dat.af <- dtWorker$raw.afternoon[, names.a]
dat.af$daytime <- "afternoon"
# merge morning and afternoon measurements with indicator [+ clean up]
daily.dat <- plyr::rbind.fill(dat.mo, dat.af)
daily.dat <- daily.dat[daily.dat$ExternalReference != 55951, ]
dtWorker$daily <- daily.dat
rm(dat.mo, dat.af, names.m, names.a, daily.dat)
# names for pre-measurement
names.pre <- c(
"Finished",
"age",
"Gender",
"Living",
"roommate_1",
"roommate_2",
"roommate_3",
"nationality",
"SecondNationality",
"timeNL_1",
"Reason_2",
"Reason_5",
"Reason_7",
"Reason_8_TEXT",
"DutchLang",
"occupation_1",
"occupation_2",
"occupation_3",
"occupation_4",
"occupation_7",
"CurrentEducation_1",
"education_level",
"EduLang_2",
"RUG_faculty",
"Study.0",
"association",
"DutchMeetNum",
"DutchFriends_1",
"assimilation",
"separation",
"integration",
"marginalization",
"VIA_heritage",
"VIA_Dutch",
"SSAS_surrounding",
"SSAS_privat",
"SSAS_public",
"autonomy",
"relatedness",
"competence",
"anxiety",
"swl",
"alertness",
"calmness",
"valence",
"date",
"time",
"City",
"ZIP",
"id"
)
# reduced data set for pre measurement
dat.pre.red <- dtWorker$raw.pre[, names.pre]
# merge with daily data [+ clean up]
df.pre <- merge(
x = dtWorker$daily,
y = dat.pre.red,
by.x = "ExternalReference",
by.y = "id",
all = T
)
rm(names.pre)
# adjust duplicate names to fit to indicate daily or pre measurement
names(df.pre) <- gsub("[[:punct:]]x", ".daily", names(df.pre))
names(df.pre) <- gsub("[[:punct:]]y", ".pre", names(df.pre))
# names for post measurement
names.post <- c(
"ExternalReference",
"assimilation",
"separation",
"integration",
"marginalization",
"VIA_heritage",
"VIA_Dutch",
"anxiety",
"swl",
"rosenberg",
"social_support",
"stress",
"discrimination",
"discrimination_month",
"NLE_1month",
"NLE_6month",
"NLE_12month"
)
# reduced data set for post-measurement
dat.post.red <- dtWorker$raw.post[, names.post]
# merge post measurement with pre- and daily data
df <- merge(
x = df.pre,
y = dat.post.red,
by.x = "ExternalReference",
by.y = "ExternalReference",
all = T
)
# adjust duplicate names to indicate pre or post
names(df) <- gsub("[[:punct:]]x", ".pre", names(df))
names(df) <- gsub("[[:punct:]]y", ".post", names(df))
# add to list
dtWorker$combined <- df
# create data frame with cleaned data
df <- dtWorker$combined %>%
filter(
Finished.pre == 1,
Finished.daily == 1,
!is.na(ExternalReference)
)
# add running number as measurement ID within participants
df$measureID <- rowidv(df, cols = c("ExternalReference"))
df <- df %>%
mutate(
PID = as.numeric(factor(ExternalReference)),
# participant ID
TID = measureID - 1,
# time ID with t0 = 0 for meaningfull intercept interpretations
date = substr(StartDate, 1, 10),
# awkward way of extracting date (best converted to )
time = substr(StartDate, 12, 19),
# awkward way of extracting time
daynum = as.numeric(factor(date)),
# all days as numeric for ordering
daycor = ifelse(
daytime == "morning" &
period_to_seconds(hms(time)) < period_to_seconds(hms("12:00:00")) |
daytime == "afternoon" &
period_to_seconds(hms(time)) < period_to_seconds(hms("19:00:00")),
daynum - 1,
daynum
),
# correctly identify which date the questionnaire is about
daycor.lead = sprintf("%02d", daycor),
daytime.lt = ifelse(daytime == "morning", "a", "b"),
# morning / afternoon to a / b
day_time = paste(daycor.lead, daytime.lt, sep = "_"),
# combine day id with morning / afternoon
session = as.numeric(factor(day_time)),
# day and time identifier as numeric id
SubTime = chron::times(time.0),
time.daily = as.character(time.daily),
PPDate = as.Date(df$date.daily),
number = tidyr::replace_na(number, 0),
NonDutchNum = tidyr::replace_na(NonDutchNum, 0)
)
dtWorker$clean <- df
# clean up
rm(df.pre, names.post, dat.post.red, dat.pre.red, df)
# Export reduced Data
# write.csv(dtWorker$clean, "data/processed/MT_clean-merged_07-05-2018.csv", row.names = F)
# save(dtWorker$clean, file = "data/processed/MT_clean-merged_07-05-2018.RData")
```
### Study 2
For the student sample data was, similarly, collected in three separate surveys: (1) the pre-measurement, (2) the daily survey sent out at lunch and dinner time, and (3) a post-measurement. We combine the three individual surveys into one large dataframe and drop superfluous variables that are not relevant to the analyses relevant here. We exclude our own test data as well as one participant who entered the study twice (but gave different responses during the pre-measurement). We also reformat missing values and format core ID variables.
<i class="fas fa-info-circle"></i> _Note:_ All data preparation steps are saved in the '_dtStudents_' list.
```{r cleanStudents}
# our own test IDs
ownIDs <- c(
"beautifulLionfishXXXR5rcgVBzGu8hPvOqrK8UBJBw4owvi9nfRFSFu3lMzYhE",
"niceDogoXXXmB8JI5SFu78SF3DVof84mGUPPNUr14p2HYFTtp31a6D1OwAzM6F-K",
"amusedQuailXXXmhuc_fpTp8vPkMwDH1BzjaH1d1kHSO1bsPEfsnaEYk4WeVBfPi",
"juwGAbtXX0_1kmZtSVqKh3PGaHOICqUyU4iBkrT3nDsI_uifuD1gzKcZerxaM5FL"
)
# Prepare dfs for Cleaning
df.pre <- dtStudents$raw.pre %>%
naniar::replace_with_na_all(condition = ~.x == "") %>%
naniar::replace_with_na_all(condition = ~.x == "NA") %>%
# mutate_all(na_if, "") %>%
# mutate_all(na_if, "NA") %>%
filter(!is.na(ended)) %>% # remove all who did not finish
filter(!e_mail %in% .$e_mail[duplicated(.$e_mail)]) %>% # remove all who did the pre questionnaire multiple times (b/c inconsistent ratings scales)
filter(!session %in% ownIDs) %>% # remove our own test
mutate(session = as.character(session)) # turn factor into character strings (probably just precaution)
df.post <- dtStudents$raw.post %>%
naniar::replace_with_na_all(condition = ~.x == "") %>%
naniar::replace_with_na_all(condition = ~.x == "NA") %>%
filter(!is.na(session)) %>% # remove own test runs
filter(!session %in% ownIDs) %>% # remove our own test
filter(session %in% df.pre$session) %>% # remove anyone who wasn't in the pre
filter(!is.na(ended)) %>% # remove all who never finished
filter(!session %in% .$session[duplicated(.$session)]) %>% # remove all duplicate sessions
mutate(session = as.character(session)) # turn factor into character strings (probably just precaution)
df.daily <- dtStudents$raw.daily %>%
naniar::replace_with_na_all(condition = ~.x == "") %>%
naniar::replace_with_na_all(condition = ~.x == "NA") %>%
filter(!session %in% ownIDs) %>% # remove our own test
filter(session %in% df.pre$session) %>% # remove anyone who wasn't in the pre
filter(!is.na(ended)) %>% # remove all who never finished
mutate(session = as.character(session)) # turn factor into character strings (probably just precaution)
# merge daily with pre
dfPreDaily <- merge(
x = df.daily,
y = df.pre,
by = "session",
suffixes = c(".daily", ".pre"),
all = F
)
# merge daily with post
dfCombined <- merge(
x = dfPreDaily,
y = df.post,
by = "session",
suffixes = c(".pre", ".post"),
all = F
)
# add to list
dtStudents$clean <- dfCombined
# clean up workspace
rm(df.pre, df.daily, df.post, dfPreDaily, dfCombined, ownIDs)
```
### Study 3
For the medical professionals sample data was, again, collected in three separate surveys: (1) the pre-measurement, (2) the daily survey sent out at lunch and dinner time, and (3) a post-measurement. We combine the three individual surveys into one large dataframe. We exclude our own test data. We also reformat missing values and format core ID variables.
<i class="fas fa-info-circle"></i> _Note:_ All data preparation steps are saved in the '_dtMedical_' list.
```{r cleanMedical}
# our own test IDs
ownIDs <- c(
"test_LeonieXXXSklxecPLW0-FBPM4796o3pUwUhAY5jb9KGw8jQsKxWmGpa1Jiy",
"test_MaxXXXtOp_5dTNefIq0yKXtXt2IN6eEKxeHoPY9mlyvdsqPpLp1B0NGg4UL",
"test_JannisXXXBsNqk62fOpX6chbd2tMWPptUdjjnhAqnQ3uBqckZ7gLIEoPlfZ",
"quaintLeopardCatXXXAJ9cfSj-_SZLwNwMDxv_xv_iyr1Bg5YFLTlYdrjW0UXZY",
"blue-eyedIndianElephantXXXLf5zPMpQCDGS3umFzIj-YVky7ivTItvvozW49m"
)
# Prepare dfs for Cleaning
df.pre <- dtMedical$raw.pre %>%
naniar::replace_with_na_all(condition = ~.x == "") %>%
naniar::replace_with_na_all(condition = ~.x == "NA") %>%
filter(!is.na(ended)) %>% # remove all who did not finish
filter(!session %in% ownIDs) %>% # remove our own test
mutate(session = as.character(session)) # turn factor into character strings (probably just precaution)
df.post <- dtMedical$raw.post %>%
naniar::replace_with_na_all(condition = ~.x == "") %>%
naniar::replace_with_na_all(condition = ~.x == "NA") %>%
filter(!is.na(session)) %>% # remove own test runs
filter(!session %in% ownIDs) %>% # remove our own test
filter(session %in% df.pre$session) %>% # remove anyone who wasn't in the pre
#filter(!is.na(ended)) %>% # remove all who never finished [disabled because only relevant if data is missing]
filter(!session %in% .$session[duplicated(.$session)]) %>% # remove all duplicate sessions
mutate(session = as.character(session)) # turn factor into character strings (probably just precaution)
df.daily <- dtMedical$raw.daily %>%
naniar::replace_with_na_all(condition = ~.x == "") %>%
naniar::replace_with_na_all(condition = ~.x == "NA") %>%
filter(!session %in% ownIDs) %>% # remove our own test
filter(session %in% df.pre$session) %>% # remove anyone who wasn't in the pre
#filter(!is.na(ended)) %>% # remove all who never finished [disabled because only relevant if data is missing]
mutate(session = as.character(session)) # turn factor into character strings (probably just precaution)
# merge daily with pre
dfPreDaily <- merge(
x = df.daily,
y = df.pre,
by = "session",
suffixes = c(".daily", ".pre"),
all = F
)
# merge daily with post
dfCombined <- merge(
x = dfPreDaily,
y = df.post,
by = "session",
suffixes = c(".pre", ".post"),
all = F
)
# add to list
dtMedical$clean <- dfCombined
# clean up workspace
rm(df.pre, df.daily, df.post, dfPreDaily, dfCombined, ownIDs)
```
## Calculate needed transformations
### Study 1
For the worker sample, the data transformation stage had three main aims:
1. We first corrected time indicators within the surveys. In some cases participants completed their daily diary surveys for the afternoon after midnight. In these cases the measurement still is in reference to the previous day and is indicated in the corrected variable.
2. We then created indices of scales. Some indices were multi-item scales while some indices combine equivalent measurement for different situational circumstances (e.g., competence perceptions after interactions and at measurement occasions without interactions).
3. Finally, we calculated several basic participant summaries (averages across all measurement occasions).
```{r newVarsWorkers}
df <- dtWorker$clean
# Time and Date Variables
# remove seconds from afternoon time
df$SubTime[df$daytime == "afternoon"] <- paste0(substring(as.character(df$time.0[df$daytime == "afternoon"]), 4, 8), ":00")
df$time.daily[df$daytime == "afternoon" &
!is.na(df$time.daily != "<NA>")] <- paste0(substring(as.character(df$time.daily[df$daytime == "afternoon" &
!is.na(df$time.daily != "<NA>")]), 4, 8), ":00")
# Correct morning / afternoon date where survey was collected the day after to indicate the correct date that was targeted
df$PPDate[df$SubTime < "11:50:00" &
df$daytime == "morning"] <- df$PPDate[df$SubTime < "11:50:00" &
df$daytime == "morning"] - 1
df$PPDate[df$SubTime < "18:50:00" &
df$daytime == "afternoon"] <- df$PPDate[df$SubTime < "18:50:00" &
df$daytime == "afternoon"] - 1
# Interaction Quality
pairs.panels.new(
df[c("quality_overall_1", "quality_meaning_1")],
labels = c(
"Pleasantness.",
"Meaningfulness."
)
)
df$interaction_quality <-
rowMeans(df[c("quality_overall_1", "quality_meaning_1")], na.rm = TRUE)
df$interaction_quality[df$interaction_quality == "NaN"] <- NA
# Need scales
df$keyMotiveFulfilled <- rowSums(df[, c("keymotive_fulfillemt_1", "keyMotive_noInt_fulf_1")], na.rm = T)
df$autonomy.daily.all <- rowSums(df[, c("autonomy_1", "autonomy_NoInt_1")], na.rm = T)
df$competence.daily.all <- rowSums(df[, c("competence_1", "competence_NoInt_1")], na.rm = T)
# cor(df$relatedness_other_1, df$relatedness_self_1,use="complete.obs")
df$relatedness.daily.all <- rowMeans(df[, c(
"relatedness_other_1",
"relatedness_self_1",
"relatedness_1_NoInt_1"
)], na.rm = T)
pairs.panels.new(
df[c("relatedness_self_1", "relatedness_other_1")],
labels = c(
"I shared information about myself.",
"X shared information about themselves."
)
)
df$relatedness_1 <- rowMeans(df[, c("relatedness_other_1", "relatedness_self_1")], na.rm = T)
df$interaction_accidental <- df$qualityAccidental_1
df$interaction_voluntary <- df$qualityVoluntary_1
df$interaction_meaningful <- df$quality_meaning_1
# summarize by participant (check that everything is within pp might not be the case for )
between <- df %>%
group_by(ExternalReference) %>%
mutate(
CtContactNL = sum(Contact_dum),
CtContactNonNl = sum(inNonDutch),
CtContactNLAll = sum(number),
CtContactNonNlAll = sum(NonDutchNum),
AvKeyNeed = mean(keyMotiveFulfilled, na.rm = T),
AvKeyNeedInt = mean(keymotive_fulfillemt_1, na.rm = T),
AvKeyNeedNoInt = mean(keyMotive_noInt_fulf_1, na.rm = T),
AvAutonomy = mean(autonomy.daily.all, na.rm = T),
AvCompetence = mean(competence.daily.all, na.rm = T),
AvRelatedness = mean(relatedness.daily.all, na.rm = T),
AvThermo = mean(thermometerDutch_1, na.rm = T),
AvWB = mean(ExWB_1, na.rm = T),
AvAccidental = mean(interaction_accidental+50, na.rm = TRUE),
AvVoluntary = mean(interaction_voluntary+50, na.rm = TRUE),
AvMeaningful = mean(interaction_meaningful, na.rm = TRUE)
) %>%
ungroup() %>%
mutate(
CtContactNL_c = scale(CtContactNL, scale = FALSE),
AvKeyNeedInt_c = scale(AvKeyNeedInt, scale = FALSE),
AvKeyNeed_c = scale(AvKeyNeed, scale = FALSE),
CtContactNL_z = scale(CtContactNL, scale = TRUE),
AvKeyNeedInt_z = scale(AvKeyNeedInt, scale = TRUE),
AvKeyNeed_z = scale(AvKeyNeed, scale = TRUE)
)
warning(
"some variable transformations (esp. _c and _z) might be across all participants (i.e., not within PP). See next step."
)
dtWorker$full <- between
rm(df, between)
# dataframe where interaction types are recoded
workerInteractionType <- dtWorker$full %>%
mutate(
OutgroupInteraction = as_factor(Contact_dum),
NonOutgroupInteraction = as_factor(inNonDutch)
) %>%
mutate(
OutgroupInteractionNum = as.numeric(as.factor(OutgroupInteraction))-1,
NonOutgroupInteractionNum = as.numeric(as.factor(NonOutgroupInteraction))-1
) %>%
mutate(
interaction_accidental = interaction_accidental+50,
interaction_voluntary = interaction_voluntary+50
) %>%
group_by(PID) %>%
mutate(
# Center ( https://quantpsy.org/pubs/yaremych_preacher_hedeker_(in.press).pdf )
OutgroupInteractionC = scale(OutgroupInteractionNum, center = TRUE, scale = FALSE)[,1],
NonOutgroupInteractionC = scale(NonOutgroupInteractionNum, center = TRUE, scale = FALSE)[,1],
# Mean
OutgroupInteractionM = mean(OutgroupInteractionNum, na.rm = TRUE),
NonOutgroupInteractionM = mean(NonOutgroupInteractionNum, na.rm = TRUE)
) %>%
ungroup %>%
mutate(
keyMotiveFulfilled = keyMotiveFulfilled+50,
keymotive_fulfillemt_1 = keymotive_fulfillemt_1+50,
competence.daily.all = competence.daily.all+50,
autonomy.daily.all = autonomy.daily.all+50,
relatedness.daily.all = relatedness.daily.all+50,
competence_1 = competence_1+50,
autonomy_1 = autonomy_1+50,
relatedness_1 = relatedness_1+50,
quality_overall_1 = quality_overall_1+50,
interaction_quality = interaction_quality+50,
ExWB_1 = ExWB_1+50,
OutgroupInteractionLab = as.character(OutgroupInteraction)
)
# Create variables centered and standardized within Participant
# i.e., divide into trait and state
workerWithinBetween <-
MlTraitState(
data = workerInteractionType,
id = "PID",
selection =
c(
"keyMotiveFulfilled",
"competence.daily.all",
"autonomy.daily.all",
"relatedness.daily.all",
"thermometerDutch_1",
"keymotive_fulfillemt_1",
"competence_1",
"autonomy_1",
"relatedness_1",
"quality_overall_1",
"interaction_quality",
"ExWB_1",
"OutgroupInteraction",
"NonOutgroupInteraction",
"OutgroupInteractionM",
"NonOutgroupInteractionM",
"interaction_accidental",
"interaction_voluntary",
"interaction_meaningful"
)
)
workerOutWithinBetween <-
MlTraitState(
data = workerInteractionType %>%
filter(OutgroupInteraction == "Yes"),
id = "PID",
selection =
c(
"keyMotiveFulfilled",
"thermometerDutch_1",
"keymotive_fulfillemt_1",
"competence_1",
"autonomy_1",
"relatedness_1",
"quality_overall_1",
"ExWB_1",
"interaction_quality",
"interaction_accidental",
"interaction_voluntary",
"interaction_meaningful"
)
)
# Between participants contact frequency
workerContactFreq <- dtWorker$full %>%
group_by(PID) %>%
summarise(
n = n(),
SumContactNL = sum(Contact_dum),
PercContactNL = SumContactNL / n * 100,
SumContactNLAll = sum(number),
AvAttitude = mean(thermometerDutch_1, na.rm = TRUE),
AvWellBeing = mean(ExWB_1, na.rm = TRUE),
AvQualityComb = mean(interaction_quality, na.rm = TRUE),
AvAccidental = mean(interaction_accidental+50, na.rm = TRUE),
AvVoluntary = mean(interaction_voluntary+50, na.rm = TRUE),
AvMeaningful = mean(interaction_meaningful, na.rm = TRUE)
) %>%
mutate(
WinSumContactNL = DescTools::Winsorize(SumContactNL),
WinSumContactNLAll = DescTools::Winsorize(SumContactNLAll)
)
# save cleaned data
# save(df.btw, file = "data/processed/df.btw.RData")
# write_sav(df.btw, "data/processed/MT_clean-merged_pre-post.sav")
# export data to Mplus
# df.mplus = remove_all_labels(select(df,
# PID, session,
# thermometerDutch_1, inNonDutch, Contact_dum,
# keyMotiveFulfilled, autonomy.daily.all, competence.daily.all, relatedness.daily.all))
# names(df.mplus)= c("PID", "session", "att", "intin", "intout", "keymot", "aut", "comp", "rel")
# mplus = df.mplus[order(df.mplus$PID, df.mplus$session),]
# mplus.intcont = mplus[mplus$intout==1,]
# prepareMplusData(mplus.intcont, "data/processed/dynamic-subset-intonly.dat")
```
### Study 2
For the student sample, the data transformation stage had five main aims:
1. We first create person, survey type, and measurement ID variables.
2. We then created indices of scales. Some indices were multi-item scales while some indices combine equivalent measurement for different situational circumstances (e.g., competence perceptions after interactions and at measurement occasions without interactions).
3. We add information about the interaction partner to the beep during which a person was selected as an interaction partner.
4. We cluster mean-center key variables within participants.
5. Finally, we calculated several basic participant summaries (averages across all measurement occasions).
```{r newVarsStudents}
df <- dtStudents$clean
# Add ID variables
df$PID <- as.numeric(factor(df$session)) # participant ID
# order time
df$TID <-
factor(df$date_period, levels = unique(dtStudents$raw.daily$date_period))
df$TIDnum <- as.numeric(df$TID) # get numeric TID
# check whether time ordering worked
df <- df %>%
arrange(PID, TID) # %>%
# View()
# Interaction as Factor
df$interaction.f <-
factor(df$Interaction,
levels = c("no interaction", "Dutch", "Non-Dutch")
)
df$intNL <- ifelse(df$Interaction == "Dutch", 1, 0)
df$intNonNL <- ifelse(df$Interaction == "Non-Dutch", 1, 0)
# Rename interaction accidental
df$interaction_accidental <- df$InteractionContextAccidental
df$interaction_voluntary <- df$InteractionContextvoluntary
df$interaction_meaningful <- df$quality_meaning
df$interaction_importance <- df$quality_importance
# -------------------------------------------------------------------------------------------------------------
# Combine Variables
# -------------------------------------------------------------------------------------------------------------
# Interaction Quality