-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path4_clean_data.R
2483 lines (1932 loc) · 109 KB
/
4_clean_data.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
# ---------------------------------------------------------------------------- #
# Clean Data
# Authors: Jeremy W. Eberle and Sonia Baee
# ---------------------------------------------------------------------------- #
# ---------------------------------------------------------------------------- #
# Notes ----
# ---------------------------------------------------------------------------- #
# Before running this script, restart R (CTRL+SHIFT+F10 on Windows) and set your
# working directory to the parent folder. This script will import (a) raw data
# (outputted by "1_get_raw_data.ipynb") from "./data/1_raw_full" (if available;
# only privately shared) or "./data/1_raw_partial" (otherwise; publicly shared)
# and (b) redacted data from "./data/2_redacted" (outputted by "3_redact_data.R").
# On redacted tables and raw tables in which no redaction was needed, this script
# (a) performs database-wide cleaning (Part I), (b) filters all data for a given
# study (in this case Calm Thinking; Part II), and (c) performs study-specific
# cleaning (in this case for Calm Thinking; Part III).
# The script will output intermediate clean data into "./data/3_intermediate_clean".
# The outputted data are deemed only intermediately cleaned because additional
# analysis-specific data cleaning will be required for any given analysis.
# ---------------------------------------------------------------------------- #
# Store working directory, install correct R version, load packages ----
# ---------------------------------------------------------------------------- #
# Store working directory
wd_dir <- getwd()
# Load custom functions
source("./code/2_define_functions.R")
# Check correct R version, load groundhog package, and specify groundhog_day
groundhog_day <- version_control()
# Load packages with groundhog
groundhog.library(dplyr, groundhog_day)
# ---------------------------------------------------------------------------- #
# Define functions used throughout script ----
# ---------------------------------------------------------------------------- #
# Define function to identify columns matching a grep pattern in a data frame.
# When used with lapply, function can be applied to all data frames in a list.
identify_columns <- function(df, grep_pattern) {
df_colnames <- colnames(df)
selected_columns <- grep(grep_pattern, df_colnames)
if (length(selected_columns) != 0) {
df_colnames[selected_columns]
}
}
# ---------------------------------------------------------------------------- #
# Document data file names ----
# ---------------------------------------------------------------------------- #
# Obtain file names of raw and redacted CSV data files
if (dir.exists(paste0(wd_dir, "/data/1_raw_full"))) {
raw_data_dir_full <- paste0(wd_dir, "/data/1_raw_full")
raw_full_filenames <-
list.files(raw_data_dir_full, pattern = "*.csv", full.names = FALSE)
}
if (dir.exists(paste0(wd_dir, "/data/1_raw_partial"))) {
raw_data_dir_partial <- paste0(wd_dir, "/data/1_raw_partial")
raw_partial_filenames <-
list.files(raw_data_dir_partial, pattern = "*.csv", full.names = FALSE)
}
red_data_dir <- paste0(wd_dir, "/data/2_redacted")
red_filenames <- list.files(red_data_dir, pattern = "*.csv", full.names = FALSE)
# Output file names to TXT
dir.create("./docs")
sink(file = "./docs/data_filenames.txt")
if (exists("raw_data_dir_full")) {
cat("In './data/1_raw_full'", "\n")
cat("\n")
print(raw_full_filenames, width = 80)
cat("\n")
}
if (exists("raw_data_dir_partial")) {
cat("In './data/1_raw_partial'", "\n")
cat("\n")
print(raw_partial_filenames, width = 80)
cat("\n")
}
cat("In './data/2_redacted'", "\n")
cat("\n")
print(red_filenames, width = 80)
sink()
# ---------------------------------------------------------------------------- #
# Import raw and redacted data ----
# ---------------------------------------------------------------------------- #
# Import raw and redacted CSV data files into lists. Obtain the full set of raw
# data files if available; otherwise, obtain the partial set.
if (exists("raw_data_dir_full")) {
raw_data_dir <- raw_data_dir_full
raw_filenames <- raw_full_filenames
} else {
raw_data_dir <- raw_data_dir_partial
raw_filenames <- raw_partial_filenames
}
raw_dat <- lapply(paste0(raw_data_dir, "/", raw_filenames), read.csv)
red_dat <- lapply(paste0(red_data_dir, "/", red_filenames), read.csv)
# Name data tables in lists
split_char <- "-"
names(raw_dat) <- unlist(lapply(raw_filenames,
function(x) {
unlist(strsplit(x,
split = split_char,
fixed = FALSE))[1]
}))
names(red_dat) <- paste0(unlist(lapply(red_filenames,
function(x) {
unlist(strsplit(x,
split = split_char,
fixed = FALSE))[1]
})),
"-redacted")
# Report names of imported tables
cat("Imported raw tables:")
names(raw_dat)
cat("Imported redacted tables:")
names(red_dat)
# Create single list with redacted tables (when redacted version is available)
# and raw tables (when redacted version is unavailable). Alphabetize list.
dat <- c(red_dat,
raw_dat[!(names(raw_dat) %in% sub("-redacted", "", names(red_dat)))])
dat <- dat[order(names(dat))]
cat("Selected tables:")
names(dat)
# Remove "-redacted" from table names, which rest of script requires
names(dat) <- sub("-redacted", "", names(dat))
# ---------------------------------------------------------------------------- #
# Part I. Database-Wide Data Cleaning ----
# ---------------------------------------------------------------------------- #
# The following code sections apply to data from every study in the "calm" SQL
# database (i.e., Calm Thinking, TET, GIDI).
# ---------------------------------------------------------------------------- #
# Remove irrelevant tables ----
# ---------------------------------------------------------------------------- #
# The following tables are vestiges of earlier studies and not used in the Calm
# Thinking, TET, or GIDI studies and contain no data. They can be removed.
unused_tables <- c("coach_log", "data", "media", "missing_data_log", "stimuli",
"trial", "verification_code")
# The "evaluation_how_learn" table was not used in the Calm Thinking, TET, or GIDI
# studies because its "how_learn" item was moved to the demographics measure before
# the Calm Thinking study launch. The item is called "ptp_reason" in the "demographics"
# table. The "evaluation_how_learn" table contains no data and can be removed.
unused_tables <- c(unused_tables, "evaluation_how_learn")
# The following tables are vestiges of earlier studies and not used in the Calm
# Thinking, TET, or GIDI studies. Although they contain data, after removing admin
# and test accounts they contain no data corresponding to a "participant_id" (the
# rows that have data have a blank "participant_id"). They can be removed.
unused_tables <- c(unused_tables, "imagery_prime", "impact_anxious_imagery")
# The following tables are used internally by the MindTrails system and contain
# no information relevant to individuals' participation in the Calm Thinking, TET,
# or GIDI studies. Although they have data, they can be removed.
system_tables <- c("export_log", "id_gen", "import_log", "password_token",
"random_condition", "visit")
# Remove tables
dat <- dat[!(names(dat) %in% c(unused_tables, system_tables))]
# ---------------------------------------------------------------------------- #
# Rename "id" columns in "participant" and "study" tables ----
# ---------------------------------------------------------------------------- #
# Except where noted below, in the "calm" database each table has an "id"
# column that identifies the rows in that table. By convention, when a table
# contains a column that corresponds to the "id" column of another table, the
# derived column's name starts with the name of the table whose "id" column it
# refers to and ends with "id". For example, "participant_id" refers to "id" in
# the "participant" table, and "study_id" refers to "id" in the "study" table.
# Each participant has only one "id" in the "participant" table and only one
# "id" in the "study" table, but these ids are not always the same. To make
# indexing tables by participant simpler, we rename "id" in the "participant"
# table to "participant_id" and rename "id" in the "study" table to "study_id".
# We treat "participant_id" as the primary identifier for each participant;
# once a table is indexed by "participant_id", "study_id" is superfluous.
# The exception to the naming convention above is that for measures that have
# multiple tables (i.e., one main table and one or more companion tables that
# contain responses to items in which multiple response options were possible),
# the "id" variable in the companion table corresponds to the "id" variable in
# the main table (but is not named "main_table_id" as would be expected by the
# convention). For example, the "id" column in the "demographics_race" table
# corresponds to the "id" column in the "demographics" table.
# Define function to rename "id" in "participant" table to "participant_id"
# and to rename "id" in "study" table to "study_id".
rename_id_columns <- function(dat) {
dat$participant <- dat$participant %>% select(participant_id = id,
everything())
dat$study <- dat$study %>% select(study_id = id, everything())
return(dat)
}
# Run function
dat <- rename_id_columns(dat)
# ---------------------------------------------------------------------------- #
# Add participant_id to all participant-specific tables ----
# ---------------------------------------------------------------------------- #
# Use function "identify_columns" (defined above) to identify columns containing
# "id" in each table
lapply(dat, identify_columns, grep_pattern = "id")
# Add participant_id to "study" and "task_log" tables. These are participant-
# specific tables but are currently indexed by study_id, not participant_id.
participant_id_study_id_match <-
select(dat$participant, participant_id, study_id)
dat$study <- merge(dat$study,
participant_id_study_id_match,
by = "study_id",
all.x = TRUE)
dat$task_log <- merge(dat$task_log,
participant_id_study_id_match,
by = "study_id",
all.x = TRUE)
# Add "participant_id" to support tables, which are currently indexed by the
# "id" column of the main table they support. First, for each main table,
# select its "participant_id" and "id" columns and list its support tables.
participant_id_demographics_id_match <-
select(dat$demographics, participant_id, id)
demographics_support_table <- "demographics_race"
participant_id_evaluation_id_match <-
select(dat$evaluation, participant_id, id)
evaluation_support_tables <- c("evaluation_coach_help_topics",
"evaluation_devices",
"evaluation_how_learn",
"evaluation_places",
"evaluation_preferred_platform",
"evaluation_reasons_control")
participant_id_mental_health_history_id_match <-
select(dat$mental_health_history, participant_id, id)
mental_health_history_support_tables <- c("mental_health_change_help",
"mental_health_disorders",
"mental_health_help",
"mental_health_why_no_help")
participant_id_reasons_for_ending_id_match <-
select(dat$reasons_for_ending, participant_id, id)
reasons_for_ending_support_tables <- c("reasons_for_ending_change_med",
"reasons_for_ending_device_use",
"reasons_for_ending_location",
"reasons_for_ending_reasons")
participant_id_session_review_id_match <-
select(dat$session_review, participant_id, id)
session_review_support_table <- "session_review_distractions"
# Now define a function that uses the selected "participant_id" and "id"
# columns from each main table and the list of the main table's support
# tables to add "participant_id" to each support table based on the "id"
add_participant_id <- function(dat, id_match, support_tables) {
output <- vector("list", length(dat))
for (i in 1:length(dat)) {
if (names(dat)[[i]] %in% support_tables) {
output[[i]] <- merge(dat[[i]], id_match, by = "id", all.x = TRUE)
} else {
output[[i]] <- dat[[i]]
}
}
names(output) <- names(dat)
return(output)
}
# Run the function for each set of support tables
dat <- add_participant_id(dat = dat,
id_match = participant_id_demographics_id_match,
support_tables = demographics_support_table)
dat <- add_participant_id(dat = dat,
id_match = participant_id_evaluation_id_match,
support_tables = evaluation_support_tables)
dat <- add_participant_id(dat = dat,
id_match = participant_id_mental_health_history_id_match,
support_tables = mental_health_history_support_tables)
dat <- add_participant_id(dat = dat,
id_match = participant_id_reasons_for_ending_id_match,
support_tables = reasons_for_ending_support_tables)
dat <- add_participant_id(dat = dat,
id_match = participant_id_session_review_id_match,
support_tables = session_review_support_table)
# ---------------------------------------------------------------------------- #
# Correct test accounts ----
# ---------------------------------------------------------------------------- #
# Changes/Issues log on 1/28/21 indicates that participant 1097 should not be a
# test account. Recode "test_account" accordingly.
dat$participant[dat$participant$participant_id == 1097, ]$test_account <- 0
# Changes/Issues log on 4/16/21 indicates that participant 1663 should be a test
# account. The account was created for participant 1537 because they were having
# technical issues, but the account was never used.
dat$participant[dat$participant$participant_id == 1663, ]$test_account <- 1
# ---------------------------------------------------------------------------- #
# Remove admin and test accounts ----
# ---------------------------------------------------------------------------- #
# Identify participant_ids that are admin or test accounts
admin_test_account_ids <-
dat$participant[dat$participant$admin == 1 |
dat$participant$test_account == 1, ]$participant_id
# Define function that removes in each table rows indexed by participant_ids of
# admin and test accounts
remove_admin_test_accounts <- function(dat, admin_test_account_ids) {
output <- vector("list", length(dat))
for (i in 1:length(dat)) {
if ("participant_id" %in% colnames(dat[[i]])) {
output[[i]] <- subset(dat[[i]],
!(participant_id %in% admin_test_account_ids))
} else {
output[[i]] <- dat[[i]]
}
}
names(output) <- names(dat)
return(output)
}
# Run function
dat <- remove_admin_test_accounts(dat, admin_test_account_ids)
# ---------------------------------------------------------------------------- #
# Label columns redacted by server ----
# ---------------------------------------------------------------------------- #
# Specify a character vector of columns ("<table_name>$<column_name>") whose values
# should be labeled as "REDACTED_ON_DATA_SERVER". If no column is to be labeled as
# such, specify NULL without quotes (i.e., "redacted_columns <- NULL").
# On 1/11/2021, Dan Funk said that the following columns are redacted but should
# not be given that they could be useful for analysis. These logical columns
# have all rows == NA.
unnecessarily_redacted_columns <- c("participant$coached_by_id",
"participant$first_coaching_format")
# On 1/11/2021, Dan Funk said that the following columns are redacted and should
# be. These character columns have all rows == "".
necessarily_redacted_columns <- c("participant$email", "participant$full_name",
"participant$password")
# On 1/11/2021, Dan Funk said that the following columns are redacted and should
# be. These numeric columns have all rows == NA.
necessarily_redacted_columns <- c(necessarily_redacted_columns,
"participant$phone",
"participant$password_token_id")
# On 1/11/2021, Dan Funk said that the following column is redacted and should
# be. This logical column has all rows == NA.
necessarily_redacted_columns <- c(necessarily_redacted_columns,
"participant$verification_code_id")
# On 1/13/2021, Dan Funk said that the following column is redacted and should
# be. This character column has all rows == "US", which is its default value in
# the Data Server.
necessarily_redacted_columns <- c(necessarily_redacted_columns,
"participant$award_country_code")
# On 1/13/2021, Dan Funk said that the following column is redacted and should
# be. This numeric column has all rows == 0, which is its default value in the
# Data Server.
necessarily_redacted_columns <- c(necessarily_redacted_columns,
"participant$attrition_risk")
# On 1/13/2021, Dan Funk said that the following columns are redacted and should
# be. These integer columns have all rows == 0, which is their default value in
# the Data Server.
necessarily_redacted_columns <- c(necessarily_redacted_columns,
"participant$blacklist",
"participant$can_text_message",
"participant$coaching",
"participant$verified",
"participant$wants_coaching")
# Collect all redacted columns
redacted_columns <- c(unnecessarily_redacted_columns, necessarily_redacted_columns)
# Define function to convert redacted columns to characters and label as
# "REDACTED_ON_DATA_SERVER"
label_redacted_columns <- function(dat, redacted_columns) {
output <- vector("list", length(dat))
for (i in 1:length(dat)) {
output[[i]] <- dat[[i]]
for (j in 1:length(dat[[i]])) {
table_i_name <- names(dat[i])
column_j_name <- names(dat[[i]][j])
table_i_column_j_name <- paste0(table_i_name, "$", column_j_name)
if (table_i_column_j_name %in% redacted_columns) {
output[[i]][, column_j_name] <- as.character(output[[i]][, column_j_name])
output[[i]][, column_j_name] <- "REDACTED_ON_DATA_SERVER"
}
}
}
names(output) <- names(dat)
return(output)
}
# Run function
dat <- label_redacted_columns(dat, redacted_columns)
# ---------------------------------------------------------------------------- #
# Remove irrelevant columns ----
# ---------------------------------------------------------------------------- #
# The "tag" columns in the following tables are not used in the Calm Thinking, TET,
# or GIDI studies and contain no data. They can be removed.
unused_columns <- paste0(c("angular_training", "anxiety_identity",
"anxiety_triggers", "assessing_program",
"bbsiq", "cc", "coach_prompt", "comorbid",
"covid19", "credibility", "dass21_as",
"demographics", "evaluation", "gidi", "help_seeking",
"js_psych_trial", "mechanisms",
"mental_health_history", "oa",
"return_intention", "rr", "session_review",
"technology_use", "wellness"),
"$tag")
# The following "how_learn_other" columns in "evaluation" are not used in the
# Calm Thinking, TET, or GIDI studies because the "how_learn_other" item was
# moved to the demographics measure before Calm Thinking study launch. The item
# is called "ptp_reason_other" in the "demographics" table. The two columns
# below contain no data and can be removed.
unused_columns <- c(unused_columns, "evaluation$how_learn_other",
"evaluation$how_learn_other_link")
# The following columns are also not used in the Calm Thinking, TET, or GIDI
# studies and contain no data. They can be removed.
unused_columns <- c(unused_columns, "action_log$action_value",
"angular_training$study",
"mental_health_history$other_help_text",
"participant$random_token",
"participant$return_date",
"reasons_for_ending$other_why_in_control",
"sms_log$type")
# Define function to remove irrelevant columns
remove_columns <- function(dat, columns_to_remove) {
output <- vector("list", length(dat))
for (i in 1:length(dat)) {
output[[i]] <- dat[[i]]
for (j in 1:length(dat[[i]])) {
table_i_name <- names(dat[i])
column_j_name <- names(dat[[i]][j])
table_i_column_j_name <- paste0(table_i_name, "$", column_j_name)
if (table_i_column_j_name %in% columns_to_remove) {
output[[i]] <- output[[i]][, !(names(output[[i]]) %in% column_j_name)]
}
}
}
names(output) <- names(dat)
return(output)
}
# Specify a character vector of columns to be removed, with each column listed
# as "<table_name>$<column_name>" (e.g., "js_psych_trial$tag"). If no column is
# to be removed, specify NULL without quotes (i.e., "columns_to_remove <- NULL").
# Unused columns defined above can be removed
columns_to_remove <- unused_columns
# Remove "over18" from "participant" table. Dan Funk said that for the Calm
# Thinking study we moved this item to the DASS-21 page (and thus to "dass21_as")
# and that the "over18" column in the "participant" table should be disregarded.
columns_to_remove <- c(columns_to_remove, "participant$over18")
# Run function
dat <- remove_columns(dat, columns_to_remove)
# ---------------------------------------------------------------------------- #
# Identify any remaining blank columns ----
# ---------------------------------------------------------------------------- #
# Define function to identify columns whose rows are all blank (interpreted by
# R as NA) or, if column is of class type "character", whose rows are all "".
# Do this after removing admin and test accounts because some columns may have
# been used during testing but not during the study itself. If no columns are
# blank besides those that are ignored in the search, nothing will be outputted.
find_blank_columns <- function(dat, ignored_columns) {
for (i in 1:length(dat)) {
for (j in 1:length(dat[[i]])) {
table_i_name <- names(dat[i])
column_j_name <- names(dat[[i]][j])
table_i_column_j_name <- paste0(table_i_name, "$", column_j_name)
if (!(table_i_column_j_name %in% ignored_columns)) {
if (all(is.na(dat[[i]][[j]]))) {
cat(paste0(table_i_column_j_name,
" , class ", class(dat[[i]][[j]]), ",",
" has all rows == NA", "\n"))
} else if (all(dat[[i]][[j]] == "")) {
cat(paste0(table_i_column_j_name,
" , class ", class(dat[[i]][[j]]), ",",
' has all rows == ""', "\n"))
}
}
}
}
}
# Specify a character vector of columns to be ignored, with each column listed
# as "<table_name>$<column_name>" (e.g., "js_psych_trial$tag"). If no column is
# to be ignored, specify NULL without quotes (i.e., "ignored_columns <- NULL").
ignored_columns <- NULL
# Run function. If blank columns are identified, consider whether they need to
# be added (a) to the set of columns to be indicated as "REDACTED" (see above)
# or (b) to the set of irrelevant columns to be removed (see above).
find_blank_columns(dat, ignored_columns)
# ---------------------------------------------------------------------------- #
# Identify and recode time stamp and date columns ----
# ---------------------------------------------------------------------------- #
# Use function "identify_columns" (defined above) to identify columns containing
# "date" in each table
lapply(dat, identify_columns, grep_pattern = "date")
# View structure of columns containing "date" in each table
view_date_str <- function(df, df_name) {
print(paste0("Table: ", df_name))
cat("\n")
df_colnames <- colnames(df)
date_columns <- grep("date", df_colnames)
if (length(date_columns) != 0) {
for (i in date_columns) {
print(paste0(df_colnames[i]))
str(df[, i])
print(paste0("Number NA: ", sum(is.na(df[, i]))))
print(paste0("Number blank: ", sum(df[, i] == "")))
print(paste0("Number 555: ", sum(df[, i] == 555, na.rm = TRUE)))
print("Number of characters: ")
print(table(nchar(df[, i])))
}
} else {
print('No columns containing "date" found.')
}
cat("----------")
cat("\n")
}
invisible(mapply(view_date_str, df = dat, df_name = names(dat)))
# Some "date" and "date_submitted" fields are blank in "js_psych_trial" table.
# Changes/Issues log states on 10/7/2019 that a timeout on Recognition Ratings
# led to some of these data not being recorded for four participants (identified
# below as 639, 645, 910, and 1028). Based on "task_log", each participant
# completed "RR" at "preTest", but the data are not recorded in "js_psych_trial".
# Mark the blank "session" fields for these entries as "preTest" and replace their
# "date" and "date_submitted" with corresponding "date_completed" from "task_log".
blank_date_ids <- unique(dat$js_psych_trial[dat$js_psych_trial$date == "" |
dat$js_psych_trial$date_submitted == "",
"participant_id"])
for (i in 1:length(blank_date_ids)) {
dat$js_psych_trial[dat$js_psych_trial$participant_id == blank_date_ids[i] &
dat$js_psych_trial$session == "",
"session"] <- "preTest"
dat$js_psych_trial[dat$js_psych_trial$participant_id == blank_date_ids[i] &
dat$js_psych_trial$session == "preTest",
c("date", "date_submitted")] <-
dat$task_log[dat$task_log$participant_id == blank_date_ids[i] &
dat$task_log$session_name == "preTest" &
dat$task_log$task_name == "RR",
"date_completed"]
}
# Note: "last_session_date" in "study" table is blank where "current_session" is
# "preTest". Henry Behan said on 9/17/21 that this is expected.
table(dat$study[dat$study$last_session_date == "", "current_session"],
useNA = "always")
# Note: "last_login_date" in "participant" table is blank for participant 3659.
# This participant has no data in any tables besides "participant" and "study".
# Henry Behan said on 9/22/21 that this participant emailed the study team on
# "2020-11-12 02:25:00 EST" saying they were eligible but had an issue creating
# an account. An account was made manually by an admin; thus, we presumably have
# screening data for them (indexed by "session_id") but cannot connect it to their
# "participant_id". The participant is considered officially enrolled in the TET
# study; thus, this needs to be accounted for in the TET participant flow diagram.
dat$participant[dat$participant$last_login_date == "", "participant_id"]
# The following columns across tables are system-generated date and time stamps.
# Dan Funk said on 10/1/21 that all of these are in EST time zone (note: EST, or
# UTC - 5, all year, not "America/New York", which switches between EST and EDT).
system_date_time_cols <- c("date", "date_created", "date_sent", "date_submitted",
"last_login_date", "last_session_date",
"date_completed")
# The following column in "return_intention" table is user-provided dates and
# times. Dan Funk said on 9/24/21 that this data is collected in the user's
# local time but converted to UTC when stored in the database.
user_date_time_cols <- "return_date"
# Define function to reformat system-generated time stamps and user-provided dates
# and times and add time zone
recode_date_time_timezone <- function(dat) {
for (i in 1:length(dat)) {
table_name <- names(dat[i])
colnames <- names(dat[[i]])
target_colnames <- colnames[colnames %in% c(system_date_time_cols,
user_date_time_cols)]
if (length(target_colnames) != 0) {
for (j in 1:length(target_colnames)) {
# Create new variable for POSIXct values. Recode blanks as NA.
POSIXct_colname <- paste0(target_colnames[j], "_as_POSIXct")
dat[[i]][, POSIXct_colname] <- dat[[i]][, target_colnames[j]]
dat[[i]][dat[[i]][, POSIXct_colname] == "", POSIXct_colname] <- NA
# Specify time zone as "UTC" for user-provided "return_date" in
# "return_intention" and as "EST" for all system-generated
# time stamps. Specify nonstandard format to parse "date_sent" in
# "sms_log". Other columns are in standard format.
if (table_name == "return_intention" & target_colnames[j] == "return_date") {
dat[[i]][, POSIXct_colname] <-
as.POSIXct(dat[[i]][, POSIXct_colname],
tz = "UTC")
} else if (table_name == "sms_log" & target_colnames[j] == "date_sent") {
dat[[i]][, POSIXct_colname] <-
as.POSIXct(dat[[i]][, POSIXct_colname],
tz = "EST",
format = "%m/%d/%Y %H:%M")
} else {
dat[[i]][, POSIXct_colname] <-
as.POSIXct(dat[[i]][, POSIXct_colname],
tz = "EST")
}
}
}
}
return(dat)
}
# Run function
dat <- recode_date_time_timezone(dat)
# Create new variables for filtering data based on system-generated time stamps. In
# most tables, the only system-generated time stamp is "date", but "js_psych_trial"
# table also has "date_submitted". Other tables do not have "date" but have other
# system-generated time stamps (i.e., "attrition_prediction" table has "date_created";
# "email_log", "error_log", and "sms_log" tables have "date_sent"; "gift_log" table
# has "date_created" and "date_sent"; "participant" table has "last_login_date";
# "study" table has "last_session_date"; "task_log" table has "date_completed").
# Given that some tables that have multiple system-generated time stamps, let
# "system_date_time_earliest" and "system_date_time_latest" represent the earliest
# and latest time stamps, respectively, for each row in the table.
for (i in 1:length(dat)) {
table_name <- names(dat[i])
colnames <- names(dat[[i]])
dat[[i]][, "system_date_time_earliest"] <- NA
dat[[i]][, "system_date_time_latest"] <- NA
if (table_name == "js_psych_trial") {
dat[[i]][, "system_date_time_earliest"] <- pmin(dat[[i]][, "date_as_POSIXct"],
dat[[i]][, "date_submitted_as_POSIXct"],
na.rm = TRUE)
dat[[i]][, "system_date_time_latest"] <- pmax(dat[[i]][, "date_as_POSIXct"],
dat[[i]][, "date_submitted_as_POSIXct"],
na.rm = TRUE)
} else if (table_name == "attrition_prediction") {
dat[[i]][, "system_date_time_earliest"] <- dat[[i]][, "date_created_as_POSIXct"]
dat[[i]][, "system_date_time_latest"] <- dat[[i]][, "date_created_as_POSIXct"]
} else if (table_name %in% c("email_log", "error_log", "sms_log")) {
dat[[i]][, "system_date_time_earliest"] <- dat[[i]][, "date_sent_as_POSIXct"]
dat[[i]][, "system_date_time_latest"] <- dat[[i]][, "date_sent_as_POSIXct"]
} else if (table_name == "gift_log") {
dat[[i]][, "system_date_time_earliest"] <- pmin(dat[[i]][, "date_created_as_POSIXct"],
dat[[i]][, "date_sent_as_POSIXct"],
na.rm = TRUE)
dat[[i]][, "system_date_time_latest"] <- pmax(dat[[i]][, "date_created_as_POSIXct"],
dat[[i]][, "date_sent_as_POSIXct"],
na.rm = TRUE)
} else if (table_name == "participant") {
dat[[i]][, "system_date_time_earliest"] <- dat[[i]][, "last_login_date_as_POSIXct"]
dat[[i]][, "system_date_time_latest"] <- dat[[i]][, "last_login_date_as_POSIXct"]
} else if (table_name == "study") {
dat[[i]][, "system_date_time_earliest"] <- dat[[i]][, "last_session_date_as_POSIXct"]
dat[[i]][, "system_date_time_latest"] <- dat[[i]][, "last_session_date_as_POSIXct"]
} else if (table_name == "task_log") {
dat[[i]][, "system_date_time_earliest"] <- dat[[i]][, "date_completed_as_POSIXct"]
dat[[i]][, "system_date_time_latest"] <- dat[[i]][, "date_completed_as_POSIXct"]
} else if ("date" %in% colnames) {
dat[[i]][, "system_date_time_earliest"] <- dat[[i]][, "date_as_POSIXct"]
dat[[i]][, "system_date_time_latest"] <- dat[[i]][, "date_as_POSIXct"]
}
}
# The following columns in the "covid9" table are participant-provided dates
user_date_cols <- c("symptoms_date", "test_antibody_date", "test_covid_date")
# Define function to reformat participant-provided dates so that they do not
# contain empty times, which were not assessed
recode_date <- function(dat) {
for (i in 1:length(dat)) {
colnames <- names(dat[[i]])
target_colnames <- colnames[colnames %in% user_date_cols]
if (length(target_colnames) != 0) {
for (j in 1:length(target_colnames)) {
# Create new variable for Date values. Recode blanks as NA.
Date_colname <- paste0(target_colnames[j], "_as_Date")
dat[[i]][, Date_colname] <- dat[[i]][, target_colnames[j]]
dat[[i]][dat[[i]][, Date_colname] == "", Date_colname] <- NA
# Columns are in a standard format
dat[[i]][, Date_colname] <- as.Date(dat[[i]][, Date_colname])
}
}
}
return(dat)
}
# Run function. Given that these columns will be read back into R as characters,
# they will need to be reconverted back to Date using the "as.Date" function.
dat <- recode_date(dat)
# The following "covid19" columns indicate whether the participant preferred not
# to provide a date. Do not reformat these as dates.
covid19_user_date_pna_cols <- c("symptoms_date_no_answer",
"test_antibody_date_no_answer",
"test_covid_date_no_answer")
# ---------------------------------------------------------------------------- #
# Identify and rename session-related columns ----
# ---------------------------------------------------------------------------- #
# Use function "identify_columns" (defined above) to identify columns containing
# "session" in each table
lapply(dat, identify_columns, grep_pattern = "session")
# View structure of columns containing "session" in each table
view_session_str <- function(dat) {
for (i in 1:length(dat)) {
print(paste0("Table: ", names(dat[i])))
cat("\n")
colnames <- names(dat[[i]])
session_colnames <- colnames[grep("session", colnames)]
if (length(session_colnames) != 0) {
for (j in 1:length(session_colnames)) {
session_colname <- session_colnames[j]
session_colname_class <- class(dat[[i]][, session_colname])
print(paste0(session_colname))
print(paste0("Class: ", session_colname_class))
if (length(unique(dat[[i]][, session_colname])) > 20) {
print("First 20 unique levels: ")
print(unique(dat[[i]][, session_colname])[1:20])
} else {
print("All unique levels: ")
print(unique(dat[[i]][, session_colname]))
}
print(paste0("Number NA: ", sum(is.na(dat[[i]][, session_colname]))))
if (!("POSIXct" %in% session_colname_class)) {
print(paste0("Number blank: ", sum(dat[[i]][, session_colname] == "")))
print(paste0("Number 555: ", sum(dat[[i]][, session_colname] == 555,
na.rm = TRUE)))
}
cat("\n")
}
} else {
print('No columns containing "session" found.')
cat("\n")
}
cat("----------")
cat("\n", "\n")
}
}
view_session_str(dat)
# Rename selected session-related columns to clarify conflated content of some
# columns and to enable consistent naming (i.e., "session_only") across tables
# for columns that contain only session information
# Given that "session" column in "dass21_as" and "oa" tables contains both
# session information and eligibility status, rename column to reflect this.
# Also create new column "session_only" with "ELIGIBLE" and "" entries of
# original "session" column recoded as "Eligibility" (to reflect that these
# entries were collected at the eligibility screener time point.
table(dat$dass21_as$session)
table(dat$oa$session)
# Given that "session" column in "angular_training" table contains both
# session information and task-related information (i.e., "flexible_thinking",
# "Recognition Ratings"), rename column to reflect this.
table(dat$angular_training$session)
# Given that "session_name" column in "gift_log" table contains both session
# information and an indicator of whether an admin awarded the gift card (i.e.,
# "AdminAwarded"), rename column to reflect this.
table(dat$gift_log$session_name)
# Rename remaining "session_name" columns (in "action_log" and "task_log"
# tables) and remaining "session" columns to "session_only" to reflect that
# they contain only session information. Do not rename "current_session"
# column of "study" table because "current_session" does not index entries
# within participants; rather, it reflects participants' current sessions.
# Note: The resulting "session_only" column contains values of "COMPLETE" in
# some tables (i.e., "action_log", "email_log") but not others (Henry Behan
# said on 9/14/21 that the "task_log" table was not designed to record values
# of "COMPLETE" in the original "session" column). Also, although "task_log"
# table contains entries at Eligibility, "action_log" table does not; Henry
# Behan said on 9/13/21 said that "action_log" table does not record data
# until the participant has created an account.
for (i in 1:length(dat)) {
if (names(dat[i]) %in% c("dass21_as", "oa")) {
names(dat[[i]])[names(dat[[i]]) == "session"] <- "session_and_eligibility_status"
dat[[i]][, "session_only"] <- dat[[i]][, "session_and_eligibility_status"]
dat[[i]][dat[[i]][, "session_only"] %in% c("ELIGIBLE", ""),
"session_only"] <- "Eligibility"
} else if (names(dat[i]) == "angular_training") {
names(dat[[i]])[names(dat[[i]]) == "session"] <- "session_and_task_info"
} else if (names(dat[i]) == "gift_log") {
names(dat[[i]])[names(dat[[i]]) == "session_name"] <- "session_and_admin_awarded_info"
} else if (names(dat[i]) %in% c("action_log", "task_log")) {
names(dat[[i]])[names(dat[[i]]) == "session_name"] <- "session_only"
} else if ("session" %in% names(dat[[i]])) {
names(dat[[i]])[names(dat[[i]]) == "session"] <- "session_only"
}
}
# ---------------------------------------------------------------------------- #
# Check for repeated columns across tables ----
# ---------------------------------------------------------------------------- #
# Define function that identifies column names that are repeated across tables.
# This is used to identify potential columns to check as to whether their values
# are the same for a given "participant_id" across tables.
find_repeated_column_names <- function(dat, ignored_columns) {
for (i in 1:length(dat)) {
for (j in 1:length(dat[[i]])) {
if (!(names(dat[[i]][j]) %in% ignored_columns)) {
for (k in 1:length(dat)) {
if ((i != k) &
names(dat[[i]][j]) %in% names(dat[[k]])) {
print(paste0(names(dat[i]), "$", names(dat[[i]][j]),
" is also in ", names(dat[k])))
}
}
}
}
}
}
# Define system-related columns to be ignored. Note: The meanings and possible
# values of some of these columns differ across tables.
key_columns <- c("participant_id", "study_id", "session_id", "id", "X")
raw_timepoint_columns <- c("session", "session_name", "tag")
computed_timepoint_columns <- c("session_and_eligibility_status", "session_only")
raw_date_columns <- c("date", "date_created", "date_sent")
computed_date_columns <- c("date_as_POSIXct", "date_created_as_POSIXct",