-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWave Variable Mapping.R
3089 lines (2452 loc) · 117 KB
/
Wave Variable Mapping.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
library(rlang)
library(purrr)
library(dplyr)
# ------ Constants ------
DEFAULT_MAPPING_COLSPEC <- list(
group = "Group",
name1 = "HomogenizedName",
coding = "FinalCoding",
subgroup1 = "SubgroupDB3",
reduce1 = "ReductionDB3",
subgroup2 = "SubgroupDB3M",
reduce2 = "ReductionDB3M",
name2 = "FinalNameDB3",
subgroup3 = "SubgroupDB4",
reduce3 = "ReductionDB4",
name3 = "FinalNameDB4"
)
ESCAPE_PREFIX <- "___VARMAPPED___"
# ------ Helpers ------
`%||%` <- function(x, y) if (is.null(x)) y else x
`%|%` <- function(x, y) {
out <- x | y
# Override missing algebra
out[is.na(out) & is.na(x) & !is.na(y)] <- FALSE
out[is.na(out) & !is.na(x) & is.na(y)] <- FALSE
out
}
DEBUG <- function(string) if (getOption("tiestk.debug", default = FALSE)) cat(string, "\n", file = stderr(), sep = "")
FLATTEN <- function(...) {
if (missing(..1)) {
stop("At least one value must be supplied to FLATTEN")
}
x <- list(...)
if (length(x) == 1L) {
x <- x[[1L]]
if (is.data.frame(x)) {
return(do.call(FLATTEN, as.list(x)))
} else if (length(x) < 2L) {
return(x)
}
}
y <- x[[1L]]
take <- x[-1]
for (j in seq_along(take)) {
stopifnot(exprs = {
length(take[[j]]) == length(y) || length(take[[j]]) == 1L
typeof(take[[j]]) == typeof(y)
})
if (length(take[[j]]) == 1L) {
take[[j]] <- rep(take[[j]], length(y))
}
y[is.na(y)] <- take[[j]][is.na(y)]
if (length(y) < 2L && all(!is.na(y))) break # Don't waste clock cycles
}
y
}
CONSOLIDATE <- function(x, columns = NULL, pattern = NULL, consolidation_func = NULL, ...) {
pickfunc <- function(r) {
ur <- unique(r)
if (length(ur[!is.na(ur)]) > 0L) {
ur <- ur[!is.na(ur)]
}
if (length(ur[!is.na(ur)]) > 1L && !is.null(consolidation_func)) {
if (!is.null(consolidation_func)) {
ur <- consolidation_func(ur, ...)
if (length(ur) > 1L) {
stop("Consolidation function must collapse all values to one", call. = FALSE)
}
} else {
stop("Multiple unique values caught with no consolidation function: ", r, call. = FALSE)
}
}
ur
}
if (inherits(x, "data.frame")) {
DT <- data.table::as.data.table(x)
colname <- "__GENCOL__"
if (is.null(columns) && is.null(pattern)) {
# Consolidate all columns into one
DT[, c(colname) := apply(DT, 1L, pickfunc)]
} else if (!is.null(columns)) {
DT[, c(colname) := apply(.SD, 1L, pickfunc, .SDcols = columns)]
} else if (!is.null(pattern)) {
cols <- names(DT)[grepl(pattern, names(DT))]
DT[, c(colname) := apply(.SD, 1L, pickfunc), .SDcols = cols]
}
if (!colname %in% names(DT)) {
stop("Screwy error happened. Somehow consolidation did not properly create the target variable.")
}
return(DT[[colname]])
} else if (!is.recursive(x)) {
return(pickfunc(x))
} else {
stop("CONSOLIDATE only defined for vectors and data.frame-like objects.", call. = FALSE)
}
}
SUM <- function(df) {
rowSums(df, na.rm = TRUE)
}
DEDUMMIFY <- function(df, coding_vec) {
stopifnot(length(df) == length(coding_vec), inherits(df, "data.frame"))
dt <- data.table::as.data.table(df)
varnames <- data.table::copy(names(dt))
if (is.null(names(coding_vec))) {
names(coding_vec) <- varnames
} else {
stopifnot(setequal(names(coding_vec), varnames))
}
# Check to see if df *can* be dedummified
dt[, dedummifiable := apply(.SD, 1L, function(x) {
x <- tryCatch(as.integer(x), warning = function(w) stop("Cannot coerce dummies to integers", call. = FALSE))
sum(x, na.rm = TRUE) <= 1
})]
if (dt[, !all(dedummifiable)]) {
stop("Multiple choice matrix encountered. Cannot dedummify safely.", call. = FALSE)
}
for (vn in varnames) {
dt[, (vn) := ifelse(!is.na(dt[[vn]]) & dt[[vn]] == 1, coding_vec[vn], NA)]
}
dt[, data.table::fcoalesce(.SD), .SDcols = varnames]
}
COALESCE <- function(dat, cols, master_col = NULL, id_col = "MERGE_STID", time_col = ".TIME", ranges = list(y1 = 1:3, y2 = 4:5), priority = NULL) {
dt <- data.table::as.data.table(dat)
selected <- names(dt)[names(dt) %in% c(id_col, time_col, cols)]
dt <- dt[, selected, with = FALSE]
data.table::setnames(dt, c(id_col, time_col), c(".id", ".time"))
coalesced <- lapply(ranges, .coalesce_times, dt, cols, priority)
names(coalesced) <- names(ranges)
master_col <- if (is.null(master_col)) {
"master_col"
} else {
master_col
}
for (range in names(ranges)) {
dt[.time %in% ranges[[range]], (master_col) := coalesced[[range]][.SD, variable, on = ".id"]]
}
dt[, master_col, with = FALSE][[1L]]
}
coalesce_long <- COALESCE
.coalesce_times <- function(range, dt, cols, priority) {
sub_dt <- dt[.time %in% range]
if (!is.null(priority)) {
data.table::setcolorder(sub_dt, c(".id", ".time", priority))
}
dt_wide <- data.table::dcast(sub_dt, .id ~ .time, value.var = cols)
# Drop all NA cols
empty_cols <- dt_wide[, vapply(.SD, function(x) all(is.na(x)), logical(1L))]
dt_wide <- dt_wide[, names(empty_cols[!empty_cols]), with = FALSE]
dt_wide[, variable := data.table::fcoalesce(.SD), .SDcols = names(dt_wide)[names(dt_wide) != ".id"]]
dt_wide
}
typecast_char <- function(charvec) {
vec <- charvec[!is.na(charvec)]
bools <- "^T$|^F$|^[tT]rue$|^TRUE$|^[fF]alse$|^FALSE$"
uints <- "\\d+"
fracs <- "\\.\\d*"
exps <- "e[+-]?\\d+"
ints <- paste0("^-?", uints, "$")
numerics <- paste0(uints, "(", fracs, ")?(", exps, ")?")
dbls <- paste0("^-?", numerics, "$")
cmplxes <- paste0("^-?", numerics, "[+-]", numerics, "i$")
if (all(grepl(bools, vec))) {
charvec <- as.logical(charvec)
} else if (all(grepl(ints, vec))) {
charvec <- as.integer(charvec)
} else if (all(grepl(dbls, vec, ignore.case = TRUE))) {
charvec <- as.double(charvec)
} else if (all(grepl(cmplxes, vec, ignore.case = TRUE))) {
charvec <- as.complex(charvec)
}
charvec
}
str_escape <- function(string) stringr::str_replace_all(string, "(\\W)", "\\\\\\1")
all.na <- function(vec) {
length(vec[is.na(vec)]) == length(vec)
}
.pw_char <- function(num, pw_max = 32L) {
# A little spinner for some user feedback while HomogenizeWaveVariables and ApplyCodebook are working
if (pw_max < 4L) {
# Idiot check
pw_max <- 4L
}
pw_step <- pw_max %/% 4L
pw_range <- function(point) {
seq(from = (point * pw_step), to = ((point * pw_step) + (pw_step - 1L)))
}
if (pw_max < 8L) {
if (num %% 4L == 0L) {
"-"
} else if (num %% 4L == 1L) {
"/"
} else if (num %% 4L == 2L) {
"|"
} else {
"\\"
}
} else {
if ((num %% pw_max) %in% pw_range(0L)) {
"-"
} else if ((num %% pw_max) %in% pw_range(1L)) {
"/"
} else if ((num %% pw_max) %in% pw_range(2L)) {
"|"
} else {
"\\"
}
}
}
`%not_in%` <- function(x, y) !(x %in% y)
MODE <- function(..., na.rm = FALSE) {
# Shamelessly lifted from Stack Overflow because oddly mode is not already built into a statistical analysis language?
# Also uses varargs for Reduction DSL parsing
vec <- list(...)
if (length(vec) == 1L) {
vec <- vec[[1L]]
}
unique_entries <- if (na.rm == TRUE) {
u <- unique(vec)
u[!is.na(u)]
} else {
unique(vec)
}
unlist(unique_entries[which.max(tabulate(match(vec, unique_entries)))])
}
.make_env_bundle <- function(list_assessments) {
if (all(grepl("^T\\d+$", names(list_assessments)))) {
# Post database merge
merge_env <- new.env()
for (t in names(list_assessments)) {
merge_env[[t]] <- list_assessments[[t]]
}
return(merge_env)
}
env_bundle <- lapply(names(list_assessments), function(name) new.env())
names(env_bundle) <- names(list_assessments)
for (name in names(list_assessments)) {
env_bundle[[name]]$group <- name
# Pre-intragroup merge
if (is(list_assessments[[name]], "list")) {
for (i in seq_along(list_assessments[[name]])) {
env_bundle[[name]][[paste0("T", i)]] <- list_assessments[[name]][[i]]
}
} else { # Post-intragroup merge
env_bundle[[name]]$merged <- list_assessments[[name]]
}
}
env_bundle
}
.recombine_list_with_errors <- function(env_bundle) {
errors <- list()
warns <- list()
mapping <- list()
if (is.list(env_bundle)) {
recombined <- as.list(rep(NA, length(env_bundle)))
names(recombined) <- names(env_bundle)
for (df_env in env_bundle) {
errors[[length(errors) + 1]] <- df_env$err
warns[[length(warns) + 1]] <- df_env$warn
if (exists("mapping", envir = df_env)) {
mapping[[length(mapping) + 1]] <- df_env$mapping
}
# Grab all of the time points and assemble into a list for output
time_points_names <- keep(names(df_env), function(name) grepl("^T", name))
time_points <- map(time_points_names, function(name) df_env[[name]])
names(time_points) <- time_points_names
time_points_order <- time_points_names %>%
stringr::str_extract("\\d+$") %>%
as.integer() %>%
order()
recombined[[df_env$group]] <- time_points[time_points_order]
}
errors <- reduce(errors, rbind)
warns <- reduce(warns, rbind)
if (length(mapping) > 0) {
mapping <- arrange(reduce(mapping, rbind), CODE_ID)
list(output = recombined, err = errors, warn = warns, map = mapping)
} else {
list(output = recombined, err = errors, warn = warns)
}
} else {
errors[[length(errors) + 1]] <- env_bundle$err
warns[[length(warns) + 1]] <- env_bundle$warn
# Grab all of the time points and assemble into a list for output
time_points_names <- keep(names(env_bundle), function(name) grepl("^T", name))
time_points <- map(time_points_names, function(name) env_bundle[[name]])
names(time_points) <- time_points_names
time_points_order <- time_points_names %>%
stringr::str_extract("\\d+$") %>%
as.integer() %>%
order()
recombined <- time_points[time_points_order]
errors <- reduce(errors, rbind)
warns <- reduce(warns, rbind)
if (length(mapping) > 0) {
mapping <- arrange(reduce(mapping, rbind), CODE_ID)
list(output = recombined, err = errors, warn = warns, map = mapping)
} else {
list(output = recombined, err = errors, warn = warns)
}
}
}
.print_list_assessments <- function(list_assessments, output_directory, file_prefix = "T", variable_prefix = "___VARMAPPED___") {
for (group in names(list_assessments)) {
cwd <- file.path(output_directory, group)
if (!dir.exists(cwd)) {
dir.create(cwd, recursive = TRUE)
}
not_na <- list_assessments[[group]][!is.na(list_assessments[[group]])]
for (i in seq_along(not_na)) {
if (!is.na(variable_prefix)) {
# Clear any marker prefixes
cleared <- map_chr(names(not_na[[i]]), function(name) gsub(variable_prefix, "", name))
names(not_na[[i]]) <- cleared
}
file_path <- file.path(cwd, paste0(file_prefix, "_", .homogenize$wave_encode(i, .homogenize$USER_WAVES_OVERRIDE), ".csv"))
write.csv(not_na[[i]], file = file_path, row.names = F)
}
}
}
# ------ Exported functions ------
#' Homogenize variables across waves
#'
#' Given a list of base, mid, and end assessments, homogenize (and capitalize) the variables based on the base variable name.
#' `mapping` must have Baseline and Endline at the minimum. If some year has 3 waves of assessments, the input `mapping` **must** have a filled-in `NameMidline` column as well.
HomogenizeWaveVariables <- function(mapping,
list_assessments,
waves = NULL,
report_errors = F,
report_directory = NA,
export_assessments = F,
export_directory = NA) {
.homogenize$USER_WAVES_OVERRIDE <- waves
# Check to see if time points are explicitly defined -- logical test avoids deep is.na call
if (!is.null(.homogenize$USER_WAVES_OVERRIDE)) {
# Ensure that the number of time points per each assessment grouping does not exceed the number of waves
stopifnot({
!any(map_lgl(list_assessments, function(group) length(group) > length(waves)))
})
}
mapping <- .homogenize$mapping_clean(mapping)
checked_mapping <- .homogenize$mapping_error_check(mapping)
if (nrow(checked_mapping$err) > 0) {
warning("Some errors are present in the mapping file. These mappings were ignored.", call. = F)
if (report_errors) {
err_report_file <- paste0(report_directory, "/", "mapping-errs.csv")
warning(paste0("Please see \"", err_report_file, "\" for the list of variables that have some errors."), call. = F)
write.csv(checked_mapping$err, file = err_report_file, row.names = F)
}
}
env_bundle <- .homogenize$process_chunks(checked_mapping$map, list_assessments)
recombined <- .recombine_list_with_errors(env_bundle)
if (nrow(recombined$err) > 0 || nrow(recombined$warn) > 0) {
warning("Some errors occurred in the homogenization process. These erroneous variables were ignored.", call. = F)
if (report_errors) {
err_report_file <- paste0(report_directory, "/homogenization-errs.csv")
warn_report_file <- paste0(report_directory, "/homogenization-warns.csv")
warning(paste0("Please see \"", err_report_file, "\" for the list of variables that have some errors."), call. = F)
warning(paste0("Please see \"", warn_report_file, "\" for the list of variables that have some warnings."), call. = F)
write.csv(recombined$err, file = err_report_file, row.names = F)
write.csv(recombined$warn, file = warn_report_file, row.names = F)
}
}
if (export_assessments) {
.print_list_assessments(recombined$output, export_directory)
}
# Mark for garbage collection
rm(env_bundle)
list(mapping = recombined$map, data = recombined$output)
}
#' Merge homogenized assessments
#'
#' Merge a set of assessments from `HomogenizeWaveVariables` into a single dataframe. Leverages `data.table` to make the merges use pass-by-reference. Uses `id` as the merging column (more often than not, this should be a student ID).
#' Note: The `id` columns **must not** have any duplicates or NA values. This is an assumption since the input assessments should already by verified.
#'
#' @param list_assessments A list of assessment groupings. Should be the output of `HomogenizeWaveVariables`
#' @param id The column by which the assessments merge
#' @param output_file If not NA, this is the path for the CSV of the merged dataframe
#' @return The merged dataframe
MergeDatabases <- function(list_assessments,
id,
times_col = ".TIME",
merge_col = ".MERGE",
prefix_select = ESCAPE_PREFIX,
output_file = NULL) {
merge_env <- new.env(parent = emptyenv())
merge_env$pw <- 0
time_point_length <- length(list_assessments[[1L]])
stopifnot(all(vapply(list_assessments, length, integer(1L)) == time_point_length))
time_points <- 1:time_point_length
dbkeys <- paste0("T", time_points)
.list_to_merge_env(merge_env, list_assessments, dbkeys)
content_summary <- .data_content_summary(list_assessments)
variable_collisions <- unique(content_summary[, .(variable, database)])
variable_collisions[, has_collision := .N > 1, by = variable]
variable_collisions[, output_name := variable]
variable_collisions[has_collision == TRUE, output_name := paste0(variable, "_", database)]
# Set up merging column
merge_id <- id
if (length(id) > 1L) {
if (is.null(merge_col)) stop("Merge column name must be specified", call. = FALSE)
merge_id <- merge_col
}
# Drop merge_id from collisions
variable_collisions <- variable_collisions[variable != merge_id]
# Alert about variable collisions
cat("Encountered conflicting variables:\n", file = stderr(), sep = "")
cat(paste0(paste0(" - ", variable_collisions[has_collision == TRUE, unique(variable)]), collapse = "\n"), "\n", file = stderr(), sep = "")
cat('All suffixed with _[database]\n\n', file = stderr(), sep = "")
purrr::walk(time_points, function(t) {
dbkey <- dbkeys[[t]]
ok_dbs <- which(vapply(merge_env[[dbkey]], function(db) !is(db, "logical"), logical(1L)))
if (length(ok_dbs) > 1L) {
for (db in names(merge_env[[dbkey]][ok_dbs])) {
# Prefix-select variables
if (!is.null(prefix_select)) {
if (any(grepl(prefix_select, names(merge_env[[dbkey]][[db]])))) {
merge_env[[dbkey]][[db]] <- dplyr::select(merge_env[[dbkey]][[db]], dplyr::starts_with(prefix_select))
names_x <- names(merge_env[[dbkey]][[db]])
names(names_x) <- vapply(names_x, function(n) gsub(prefix_select, "", n), character(1L))
merge_env[[dbkey]][[db]] <- dplyr::rename(merge_env[[dbkey]][[db]], !!!names_x)
}
}
# Generate MERGE_ID if needed
if (length(id) > 1L) {
notindb <- id[!id %in% names(merge_env[[dbkey]][[db]])]
if (length(notindb) == length(id)) stop(paste0("At least one merge column must be present in ", db, "$", dbkey), call. = FALSE)
merge_env[[dbkey]][[db]][, notindb] <- NA
merge_env[[dbkey]][[db]][[merge_col]] <- FLATTEN(merge_env[[dbkey]][[db]][, id])
}
# Check for duplicates in merge_id
if (any(duplicated(merge_env[[dbkey]][[db]][[merge_id]]))) {
dupes <- duplicated(merge_env[[dbkey]][[db]][[merge_id]])
warning(paste0("Duplicated IDs encountered in ", db, " database merge: ",
paste0(unique(merge_env[[dbkey]][[db]][[merge_id]][dupes]), collapse = ", "),
". These were removed for merging. Please fix!"),
call. = FALSE,
immediate. = TRUE)
merge_env[[dbkey]][[db]] <- merge_env[[dbkey]][[db]][!dupes, ]
}
}
renames <- list()
for (db in names(merge_env[[dbkey]][ok_dbs])) {
needs_rename <- variable_collisions[has_collision == TRUE & database == db, variable]
names(needs_rename) <- variable_collisions[has_collision == TRUE & database == db, output_name]
renames[[db]] <- as.list(needs_rename)
}
for (db in names(renames)) {
# Filter which renames are valid
time_renames <- renames[[db]]
time_renames <- time_renames[time_renames %in% names(merge_env[[dbkey]][[db]])]
merge_env[[dbkey]][[db]] <- dplyr::rename(merge_env[[dbkey]][[db]], !!!time_renames)
}
merge_env[[dbkey]] <- purrr::reduce(merge_env[[dbkey]][ok_dbs], function(x, y) {
dplyr::full_join(x, y, by = merge_id)
})
merge_env[[dbkey]][[times_col]] <- t
} else if (length(ok_dbs) == 1L) {
merge_env[[dbkey]] <- merge_env[[dbkey]][[ok_dbs]]
if (!is.null(prefix_select)) {
if (any(grepl(prefix_select, names(merge_env[[dbkey]])))) {
merge_env[[dbkey]] <- dplyr::select(merge_env[[dbkey]], dplyr::starts_with(prefix_select))
names_x <- names(merge_env[[dbkey]])
names(names_x) <- vapply(names_x, function(n) gsub(prefix_select, "", n), character(1L))
merge_env[[dbkey]] <- dplyr::rename(merge_env[[dbkey]], !!!names_x)
}
}
# Variable collisions
db <- names(ok_dbs)
needs_rename <- variable_collisions[has_collision == TRUE & database == db, variable]
names(needs_rename) <- variable_collisions[has_collision == TRUE & database == db, output_name]
renames <- as.list(needs_rename)
# Filter out ones that only exist in working database
renames <- renames[renames %in% names(merge_env[[dbkey]])]
merge_env[[dbkey]] <- dplyr::rename(merge_env[[dbkey]], !!!renames)
merge_env[[dbkey]][[times_col]] <- t
} else {
merge_env[[dbkey]] <- NA
}
})
env_l <- as.list(merge_env)
rm(merge_env)
env_l[grepl("^T\\d+$", names(env_l))]
}
.list_to_merge_env <- function(merge_env, list_assessments, dbkeys) {
for (group in names(list_assessments)) {
names(list_assessments[[group]]) <- dbkeys
}
for (dbk in dbkeys) {
merge_env[[dbk]] <- list()
for (group in names(list_assessments)) {
if (is.data.frame(list_assessments[[group]][[dbk]])) {
merge_env[[dbk]][[group]] <- list_assessments[[group]][[dbk]]
}
}
}
invisible(NULL)
}
.data_content_summary <- function(list_assessments) {
datalist <- lapply(names(list_assessments), function(group) {
dbkeys <- paste0("T", seq_along(list_assessments[[group]]))
names(list_assessments[[group]]) <- dbkeys
ok_dbs <- vapply(dbkeys, function(dbk) is.data.frame(list_assessments[[group]][[dbk]]), logical(1L))
content_dbs <- lapply(dbkeys[ok_dbs], function(dbk) {
data.table::data.table(variable = names(list_assessments[[group]][[dbk]]), time = dbk, database = group)
})
data.table::rbindlist(content_dbs)
})
data.table::rbindlist(datalist)
}
MergeTimes <- function(merged_list,
id,
times_col = ".TIME",
prefix_select = NULL,
mapping = NULL,
map_colspec = NULL,
safe_coerce = TRUE) {
ok_times <- which(!is.na(merged_list))
if (length(ok_times) > 1L) {
merged <- purrr::reduce(merged_list[ok_times], function(x, y) {
if (!is.null(prefix_select)) {
if (any(grepl(prefix_select, names(x)))) {
x <- dplyr::select(x, dplyr::starts_with(prefix_select))
names_x <- names(x)
names(names_x) <- vapply(names_x, function(n) gsub(prefix_select, "", n), character(1L))
x <- dplyr::rename(x, !!!names_x)
}
y <- dplyr::select(y, dplyr::starts_with(prefix_select))
names_y <- names(y)
names(names_y) <- vapply(names_y, function(n) gsub(prefix_select, "", n), character(1L))
y <- dplyr::rename(y, !!!names_y)
}
notinx <- setdiff(names(y), names(x))
notiny <- setdiff(names(x), names(y))
x[, notinx] <- NA
y[, notiny] <- NA
cols_x <- setdiff(names(x), c(id, times_col))
cols_y <- setdiff(names(y), c(id, times_col))
order_cols_x <- c(id, times_col, cols_x[order(cols_x)])
order_cols_y <- c(id, times_col, cols_y[order(cols_y)])
x <- x[, order_cols_x]
y <- y[, order_cols_y]
rbind(x, y)
})
merged <- dplyr::as_tibble(merged)
if (!is.null(mapping)) {
if (is.null(map_colspec)) stop("A mapping column specification in the form `list(name = \"...\", group = \"...\")` must be provided", call. = FALSE)
col_order <- unique(mapping[[map_colspec$name]])
col_order <- col_order[!is.na(col_order)]
restored_order <- unlist(lapply(col_order, function(co) {
databases <- unique(mapping[[map_colspec$group]])
databases <- databases[!is.na(databases)]
group_pattern <- paste0(paste0("^", co, "_", databases, "$"), collapse = "|")
names(merged)[grepl(paste0("^", co, "$|", group_pattern), names(merged))]
}))
missing_cols <- setdiff(names(merged), restored_order)
if (length(missing_cols) > 0L) {
warning("Ordering columns after merging times resulted in some missed columns. These are now at the end of the dataset.", call. = FALSE, immediate. = TRUE)
}
final_order <- setdiff(c(restored_order, missing_cols), c(id, times_col))
merged <- merged[, c(id, times_col, final_order)]
}
} else if (length(ok_times) == 1L) {
merged <- merged_list[[ok_times]]
if (!is.null(prefix_select)) {
if (any(grepl(prefix_select, names(merged)))) {
merged <- dplyr::select(merged, dplyr::starts_with(prefix_select))
names_x <- names(merged)
names(names_x) <- vapply(names_x, function(n) gsub(prefix_select, "", n), character(1L))
merged <- dplyr::rename(merged, !!!names_x)
}
}
} else {
merged <- NA
}
merged
}
#' Spread tidy data to wide for for longitudinal analysis
#'
#' By inferring the "unitedness" of variables, spread out the other variables by time.
#'
#' @param df A data.frame
#' @param id The desired ID column
#' @param times_col An integer-valued column which acts as the observation time. Defaults to ".TIME"
#' @param req_united_vars If any variables should be united but may be split, include them in this vector. An error will
#' be generated if the variable cannot be united. In this situation, a function may need to be applied to the variable
#' using `ApplyCodebook`.
#' @param req_split_vars If any variables ought to be split but may be inferred to be united, include them in this vector.
#'
#' @return `df` but in wide format
SpreadTimes <- function(df,
id,
times_col = ".TIME",
spread_all = FALSE,
autocompute_split = TRUE,
drop_empty = TRUE,
mode_unite = NULL,
req_united_vars = NULL,
req_split_vars = NULL) {
stopifnot(inherits(df, "data.frame"), id %in% names(df), times_col %in% names(df))
# To not blow up memory for the ~5000 groupings, use data.table
DT <- data.table::as.data.table(df)
original_colorder <- names(DT)
if (spread_all) {
cat("Spreading ALL variables...",
"\n", sep = "", file = stdout())
split_vars <- setdiff(names(DT), c(id, times_col))
} else {
if (!is.null(mode_unite)) {
for (muv in mode_unite) {
query <- bquote(.(as.name(muv)) := MODE(.(as.name(muv), na.rm = TRUE)))
DT[, eval(query), by = id]
}
}
if (isTRUE(autocompute_split)) {
cat("Computing split variables...",
"\n", sep = "", file = stdout())
split_vars <- DT[,
lapply(.SD, function(x) {
ux <- unique(x)
length(ux[!is.na(ux)]) > 1L
}),
by = id,
.SDcols = setdiff(names(DT), c(id, times_col))
]
not_id <- setdiff(names(split_vars), id)
split_vars <- split_vars[, vapply(.SD, any, logical(1L)), .SDcols = not_id]
# Finally get the names of split variables
split_vars <- names(split_vars[split_vars])
} else {
split_vars <- setdiff(names(DT), c(id, times_col))
if (!is.null(mode_unite)) {
split_vars <- setdiff(split_vars, mode_unite)
}
}
if (!is.null(req_split_vars)) {
cat("Including required split variables...",
"\n", sep = "", file = stdout())
split_vars <- c(split_vars, req_split_vars[!req_split_vars %in% split_vars])
}
if (!is.null(req_united_vars)) {
bad_vars <- req_united_vars[req_united_vars %in% split_vars]
warning(paste0("Could not unite: ", paste0(bad_vars, collapse = ", ")), immediate. = TRUE, call. = FALSE)
}
}
if (!spread_all) {
united_vars <- setdiff(names(DT), c(id, times_col, split_vars))
cat("Spreading while keeping these variables united:\n",
paste0(paste0(" - ", united_vars), collapse = "\n"),
"\n", sep = "", file = stdout())
unique_vals <- DT[,
lapply(.SD, function(v) {
uv <- unique(v)
if (length(uv[!is.na(uv)]) < 1L) uv[is.na(uv)] else uv[!is.na(uv)]
}),
by = id,
.SDcols = united_vars
]
pw <- 0
for (.id in unique(unlist(DT[, ..id]))) {
if (!getOption("tiestk.debug", FALSE)) {
cat(.pw_char(pw, pw_max = 64), " Updating united variables...\r", sep = "")
pw <- pw + 1
}
row <- as.list(unique_vals[eval(as.name(id)) == .id][, -..id])
data.table::set(
DT,
i = which(DT[, ..id] == .id),
j = names(row),
value = row
)
}
} else {
united_vars <- ""
}
cat("\n")
# United vars, including ID but excluding times_col for dcast call
if (!spread_all) {
uv_expr <- rlang::parse_expr(paste(c(id, united_vars), collapse = "+"))
} else {
uv_expr <- rlang::parse_expr(id)
}
formula_expr <- rlang::expr(!!uv_expr ~ !!as.name(times_col))
casted <- data.table::dcast(
DT,
eval(formula_expr),
value.var = split_vars
)
if (isTRUE(drop_empty)) {
empty_cols <- casted[, vapply(.SD, function(x) all(is.na(x)), logical(1L))]
cat("Dropping empty: ",
paste0(names(empty_cols)[empty_cols], collapse = ", "),
"\n", sep = "", file = stderr())
casted <- casted[, !..empty_cols]
}
casted
}
SpreadDatabase <- function(
database,
id_col,
times_col = ".TIME",
autocompute_unite = TRUE,
required_united_vars = NULL,
force_unite = NULL,
drop_empty = TRUE,
verbose = FALSE
) {
stopifnot(inherits(database, "data.frame"), id_col %in% names(database), times_col %in% names(database))
DT <- data.table::as.data.table(database)
original_colorder <- names(DT)
.log_db <- function(...) {
if (isTRUE(verbose)) {
cat(..., "\n", sep = "")
}
invisible(NULL)
}
.mode <- function(..., na.rm = TRUE) {
vec <- list(...)
if (length(vec) == 1L) {
vec <- vec[[1L]]
}
unique_entries <- if (na.rm == TRUE) {
u <- unique(vec)
u[!is.na(u)]
} else {
unique(vec)
}
unlist(unique_entries[which.max(tabulate(match(vec, unique_entries)))])
}
if (!is.null(force_unite)) {
stopifnot(is.character(force_unite))
.log_db("Force uniting: ", paste0(force_unite, collapse = ", "))
for (fun in force_unite) {
query <- bquote(.(as.name(fun)) := .mode(.(as.name(fun)), na.rm = TRUE))
DT[, eval(query), by = id_col]
}
}
check_unite_vars <- if (isTRUE(autocompute_unite)) {
setdiff(names(DT), c(id_col, times_col))
} else {
if (!is.null(required_united_vars)) {
# Ensure no-one tries to unite the ID and times cols
setdiff(required_united_vars, c(id_col, times_col))
} else {
character(0L)
}
}
if (isTRUE(autocompute_unite)) {
.log_db("Automatically computing united variables...")
}
united_vars <- if (length(check_unite_vars) > 0L) {
unite_compatible <- DT[,
lapply(.SD, function(x) {
ux <- unique(x[!is.na(x)])
length(ux) <= 1L
}),
by = id_col,
.SDcols = check_unite_vars
]
unite_compatible <- unite_compatible[, !grep(id_col, names(unite_compatible)), with = FALSE][, vapply(.SD, all, logical(1L))]
names(unite_compatible[unite_compatible])
} else {
character(0L)
}
if (length(united_vars) < 1L) {
message("No united variables detected")
} else {
.log_db("Detected united variables: ", paste0(united_vars, collapse = ", "))
}
if (!is.null(required_united_vars) && !all(required_united_vars %in% united_vars)) {
warning("Required united variables cannot be united: ", paste0(required_united_vars[!required_united_vars %in% united_vars]), call. = FALSE, immediate. = TRUE)
}
if (length(united_vars) > 0L) {
.log_db("Updating united variables...")
for (uvar in united_vars) {
query <- bquote(.(as.name(uvar)) := {
uv <- unique(.(as.name(uvar)))