-
Notifications
You must be signed in to change notification settings - Fork 2
/
FeatureEngineering_CrossRowOperations.R
3017 lines (2695 loc) · 142 KB
/
FeatureEngineering_CrossRowOperations.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
#' @title Mode
#'
#' @description Statistical mode. Only returns the first mode if there are many
#'
#' @author Adrian Antico
#' @family EDA
#'
#' @param x vector
#' @export
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
#' @title AutoLagRollMode
#'
#' @description Create lags and rolling modes for categorical variables.
#'
#' @author Adrian Antico
#' @family Feature Engineering
#'
#' @param data A data.table you want to run the function on
#' @param Lags A numeric vector of the specific lags you want to have generated. You must include 1 if WindowingLag = 1.
#' @param ModePeriods A numberic vector of window sizes
#' @param Targets A character vector of the column names for the reference column in which you will build your lags and rolling stats
#' @param GroupingVars A character vector of categorical variable names you will build your lags and rolling stats by
#' @param SortDateName The column name of your date column used to sort events over time
#' @param WindowingLag Set to 0 to build rolling stats off of target columns directly or set to 1 to build the rolling stats off of the lag-1 target
#' @param Type List either "Lag" if you want features built on historical values or "Lead" if you want features built on future values
#' @param SimpleImpute Set to TRUE for factor level imputation of "0" and numeric imputation of -1
#' @param Debug = FALSE
#' @return data.table of original data plus created lags, rolling stats, and time between event lags and rolling stats
#' @examples
#' \dontrun{
#' # NO GROUPING CASE: Create fake Panel Data----
#' Count <- 1L
#' for(Level in LETTERS) {
#' datatemp <- Rodeo::FakeDataGenerator(
#' Correlation = 0.75,
#' N = 25000L,
#' ID = 0L,
#' ZIP = 0L,
#' FactorCount = 2L,
#' AddDate = TRUE,
#' Classification = FALSE,
#' MultiClass = FALSE)
#' datatemp[, Factor1 := eval(Level)]
#' if(Count == 1L) {
#' data <- data.table::copy(datatemp)
#' } else {
#' data <- data.table::rbindlist(
#' list(data, data.table::copy(datatemp)))
#' }
#' Count <- Count + 1L
#' }
#'
#' # NO GROUPING CASE: Create rolling modes for categorical features
#' data <- Rodeo::AutoLagRollMode(
#' data,
#' Lags = seq(1,5,1),
#' ModePeriods = seq(2,5,1),
#' Targets = c("Factor_1"),
#' GroupingVars = NULL,
#' SortDateName = "DateTime",
#' WindowingLag = 1,
#' Type = "Lag",
#' SimpleImpute = TRUE)
#'
#' # GROUPING CASE: Create fake Panel Data----
#' Count <- 1L
#' for(Level in LETTERS) {
#' datatemp <- Rodeo::FakeDataGenerator(
#' Correlation = 0.75,
#' N = 25000L,
#' ID = 0L,
#' ZIP = 0L,
#' FactorCount = 2L,
#' AddDate = TRUE,
#' Classification = FALSE,
#' MultiClass = FALSE)
#' datatemp[, Factor1 := eval(Level)]
#' if(Count == 1L) {
#' data <- data.table::copy(datatemp)
#' } else {
#' data <- data.table::rbindlist(
#' list(data, data.table::copy(datatemp)))
#' }
#' Count <- Count + 1L
#' }
#'
#' # GROUPING CASE: Create rolling modes for categorical features
#' data <- Rodeo::AutoLagRollMode(
#' data,
#' Lags = seq(1,5,1),
#' ModePeriods = seq(2,5,1),
#' Targets = c("Factor_1"),
#' GroupingVars = "Factor_2",
#' SortDateName = "DateTime",
#' WindowingLag = 1,
#' Type = "Lag",
#' SimpleImpute = TRUE)
#' }
#' @export
AutoLagRollMode <- function(data,
Lags = 1,
ModePeriods = 0,
Targets = NULL,
GroupingVars = NULL,
SortDateName = NULL,
WindowingLag = 0,
Type = c("Lag"),
SimpleImpute = TRUE,
Debug = FALSE) {
# Number of Targets
tarNum <- length(Targets)
if(Debug) print('AutoLagRollMode 1')
# Argument Checks ----
if(is.null(Lags) && WindowingLag == 1) Lags <- 1
if(!(1 %in% Lags) && WindowingLag == 1) Lags <- c(1, Lags)
if(any(Lags < 0)) stop("Lags need to be positive integers")
if(!is.null(GroupingVars)) if(!is.character(GroupingVars)) stop("GroupingVars needs to be a character scalar or vector")
if(!is.character(Targets)) stop("Targets needs to be a character scalar or vector")
if(!is.character(SortDateName)) stop("SortDateName needs to be a character scalar or vector")
if(!(WindowingLag %in% c(0, 1))) stop("WindowingLag needs to be either 0 or 1")
if(!(tolower(Type) %chin% c("lag", "lead"))) stop("Type needs to be either Lag or Lead")
if(!is.logical(SimpleImpute)) stop("SimpleImpute needs to be TRUE or FALSE")
if(Debug) print('AutoLagRollMode 2')
# Ensure enough columns are allocated beforehand----
if(!is.null(GroupingVars)) {
if(Debug) print('AutoLagRollMode 3.a')
if(ncol(data) + (length(Lags) + length(ModePeriods)) * tarNum * length(GroupingVars) > data.table::truelength(data)) {
data.table::alloc.col(DT = data, n = ncol(data) + (length(Lags) + length(ModePeriods)) * tarNum * length(GroupingVars))
}
} else {
if(Debug) print('AutoLagRollMode 3.b')
if(ncol(data) + (length(Lags) + length(ModePeriods)) * tarNum > data.table::truelength(data)) {
data.table::alloc.col(DT = data, n = ncol(data) + (length(Lags) + length(ModePeriods)) * tarNum)
}
}
if(Debug) print('AutoLagRollMode 4')
# Names
ColumnNames <- names(data.table::copy(data))
if(Debug) print('AutoLagRollMode 5')
# Ensure Targets are Factors
class_switch <- c()
for(fac in Targets) {
if(class(data[[eval(fac)]])[1L] %in% c('character')) {
class_switch <- c(class_switch, fac)
data.table::set(data, j = eval(fac), value = as.factor(data[[eval(fac)]]))
}
}
# Begin feature engineering ----
if(!is.null(GroupingVars)) {
if(Debug) print('AutoLagRollMode 6')
# i = 1L
for(i in seq_along(GroupingVars)) {
if(Debug) print('AutoLagRollMode 7')
# Sort data ----
if(tolower(Type) == "lag") {
colVar <- c(GroupingVars[i], SortDateName[1L])
data.table::setorderv(data, colVar, order = 1L)
} else {
colVar <- c(GroupingVars[i], SortDateName[1L])
data.table::setorderv(data, colVar, order = -1L)
}
if(Debug) print('AutoLagRollMode 8')
# Lags ----
LAG_Names <- c()
for(t in Targets) LAG_Names <- c(LAG_Names, paste0(GroupingVars[i], "_LAG_", Lags, "_", t))
data[, paste0(LAG_Names) := data.table::shift(.SD, n = Lags, type = "lag"), by = c(GroupingVars[i]), .SDcols = Targets]
if(Debug) print('AutoLagRollMode 9')
# Define targets ----
if(WindowingLag > 0L) {
Targets <- c(paste0(GroupingVars[i], "_LAG_", WindowingLag, "_", Targets))
}
if(Debug) print('AutoLagRollMode 10')
# Mode ----
if(!all(ModePeriods %in% c(0,1))) {
if(Debug) print('AutoLagRollMode 11')
tempperiods <- ModePeriods[ModePeriods > 1L]
Mode_Names <- c()
if(Debug) print('AutoLagRollMode 12.a')
counter <- 1L
temp_targets <- c()
print(data)
for(gg in Targets) {
data[is.na(get(gg)), eval(gg) := "0"]
temp_targets <- c(temp_targets, paste0("TEMP_", gg))
if(Debug) print(str(data))
data[, paste0("TEMP_", gg) := unclass(get(gg))]
if(Debug) print(str(data))
counter <- counter + 1L
}
if(Debug) print('AutoLagRollMode 13')
for(t in Targets) for(j in seq_along(tempperiods)) Mode_Names <- c(Mode_Names, paste0(GroupingVars[i], "Mode_", tempperiods[j], "_", t))
if(Debug) {
print(data)
print(temp_targets)
}
data[, paste0(Mode_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = Mode), by = c(GroupingVars[i]), .SDcols = c(temp_targets)]
if(Debug) print('AutoLagRollMode 14')
# Convert back to catgegorical ----
if(Debug) print('AutoLagRollMode 15')
for(t in seq_along(Targets)) {
if(Debug) print('AutoLagRollMode 16')
for(j in seq_along(tempperiods)) {
if(Debug) print('AutoLagRollMode 17')
temp <- data[, .N, by = c(Targets[t], temp_targets[t])][, N := NULL]
data.table::setkeyv(temp, paste0("TEMP_", Targets[t]))
data[, paste0("remove_", GroupingVars[i], "Mode_", tempperiods[j], "_", Targets[t]) := get(paste0(GroupingVars[i], "Mode_", tempperiods[j], "_", Targets[t]))]
data[, paste0(GroupingVars[i], "Mode_", tempperiods[j], "_", Targets[t]) := NULL]
data.table::setkeyv(data, paste0("remove_", GroupingVars[i], "Mode_", tempperiods[j], "_", Targets[t]))
data[temp, paste0(GroupingVars[i], "Mode_", tempperiods[j], "_", Targets[t]) := as.character(get(paste0("i.", Targets[t])))]
data[, paste0("remove_", GroupingVars[i], "Mode_", tempperiods[j], "_", Targets[t]) := NULL]
}
}
if(Debug) print('AutoLagRollMode 18')
# Remove TEMP_ columns
data.table::set(data, j = c(names(data)[names(data) %like% "TEMP_"]), value = NULL)
}
}
if(Debug) print('AutoLagRollMode 19')
# Impute missing values ----
UpdateColumnNames <- setdiff(names(data), ColumnNames)
if(SimpleImpute) {
for(j in which(names(data) %in% UpdateColumnNames)) {
if(is.factor(data[[j]])) {
data.table::set(data, which(!(data[[j]] %in% levels(data[[j]]))), j, "0")
} else if(is.character(data[[j]])) {
data.table::set(data, which(is.na(data[[j]])), j, "0")
} else {
data.table::set(data, which(is.na(data[[j]])), j, -1)
}
}
}
if(Debug) print('AutoLagRollMode 20')
# Convert changed types back to original types
if(length(class_switch) > 0L) {
for(fac in class_switch) data.table::set(data, j = eval(fac), value = as.character(data[[eval(fac)]]))
}
# Done!! ----
return(data)
} else {
if(Debug) print('AutoLagRollMode 6.b')
# Non grouping case
if(tolower(Type) == "lag") {
colVar <- c(SortDateName[1L])
data.table::setorderv(data, colVar, order = 1L)
} else {
colVar <- c(SortDateName[1L])
data.table::setorderv(data, colVar, order = -1L)
}
if(Debug) print('AutoLagRollMode 7.b')
# Lags ----
LAG_Names <- c()
for(t in Targets) LAG_Names <- c(LAG_Names, paste0("LAG_", Lags, "_", t))
if(Debug) print('AutoLagRollMode 8.b')
# Build features ----
data[, paste0(LAG_Names) := data.table::shift(.SD, n = Lags, type = "lag"), .SDcols = c(Targets)]
if(Debug) print('AutoLagRollMode 9.b')
# Define targets ----
if(WindowingLag != 0L) {
Targets <- c(paste0("LAG_", WindowingLag, "_", Targets))
} else {
Targets <- Targets
}
if(Debug) print('AutoLagRollMode 10.b')
# Mode ----
if(!all(ModePeriods %in% c(0,1))) {
if(Debug) print('AutoLagRollMode 11.b')
tempperiods <- ModePeriods[ModePeriods > 1L]
Mode_Names <- c()
g <- names(data)[which(sapply(data, is.factor))]
if(!identical(integer(0), g)) {
if(Debug) print('AutoLagRollMode 12.b')
cats <- g[which(g %chin% Targets)]
counter <- 1L
temp_targets <- c()
for(gg in cats) {
if(Debug) print('AutoLagRollMode 13.b')
data[is.na(get(gg)), eval(gg) := "0"]
temp_targets <- c(temp_targets, paste0("TEMP_", gg))
data[, paste0("TEMP_", gg) := unclass(get(gg))]
counter <- counter + 1L
}
} else {
if(Debug) print('AutoLagRollMode 11.bb')
temp_targets <- Targets
}
if(Debug) print('AutoLagRollMode 14.b')
for(t in Targets) for(j in seq_along(tempperiods)) Mode_Names <- c(Mode_Names, paste0("Mode_", tempperiods[j], "_", t))
data[, paste0(Mode_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = Mode), .SDcols = c(temp_targets)]
if(Debug) print('AutoLagRollMode 15.b')
# Convert back to catgegorical
if(!identical(integer(0), g)) {
if(Debug) print('AutoLagRollMode 16.b')
for(t in seq_along(Targets)) {
if(Debug) print('AutoLagRollMode 17.b')
for(j in seq_along(tempperiods)) {
if(Debug) print('AutoLagRollMode 18.b')
temp <- data[, .N, by = c(Targets[t], temp_targets[t])][, N := NULL]
data.table::setkeyv(temp, paste0("TEMP_", Targets[t]))
data[, paste0("remove_", "Mode_", tempperiods[j], "_", Targets[t]) := get(paste0("Mode_", tempperiods[j], "_", Targets[t]))]
data[, paste0("Mode_", tempperiods[j], "_", Targets[t]) := NULL]
data.table::setkeyv(data, paste0("remove_", "Mode_", tempperiods[j], "_", Targets[t]))
data[temp, paste0("Mode_", tempperiods[j], "_", Targets[t]) := as.character(get(paste0("i.", Targets[t])))]
data[, paste0("remove_", "Mode_", tempperiods[j], "_", Targets[t]) := NULL]
}
}
}
if(Debug) print('AutoLagRollMode 19.b')
# Remove TEMP_ columns
data.table::set(data, j = c(names(data)[names(data) %like% "TEMP_"]), value = NULL)
}
if(Debug) print('AutoLagRollMode 20.b')
# Impute missing values ----
UpdateColumnNames <- setdiff(names(data), ColumnNames)
if(SimpleImpute) {
for(j in which(names(data) %in% UpdateColumnNames)) {
if(is.factor(data[[j]])) {
data.table::set(data, which(!(data[[j]] %in% levels(data[[j]]))), j, "0")
} else if(is.character(data[[j]])) {
data.table::set(data, which(is.na(data[[j]])), j, "0")
} else {
data.table::set(data, which(is.na(data[[j]])), j, -1)
}
}
}
if(Debug) print('AutoLagRollMode 21.b')
# Convert changed types back to original types
if(length(class_switch) > 0L) {
for(fac in class_switch) data.table::set(data, j = eval(fac), value = as.character(data[[eval(fac)]]))
}
# Done!! ----
return(data)
}
}
#' @title DiffDT
#'
#' @description Difference a column in a data.table
#'
#' @author Adrian Antico
#' @family Misc
#'
#' @param data Source data
#' @param x Column name
#' @param NLag1 Numeric
#' @param NLag2 Numeric
#' @param Type Choose from 'numeric' or 'date'
#' @export
DiffDT <- function(data, x, NLag1, NLag2, Type = "numeric") {
if(Type == "numeric") {
if(NLag1 == 0) {
temp <- data[[eval(x)]] - data[[paste0("Diff_", NLag2, "_", x)]]
} else {
temp <- data[[paste0("Diff_", NLag1, "_", x)]] - data[[paste0("Diff_", NLag1,"-", NLag2, "_", x)]]
}
} else if(Type == "date") {
if(NLag1 == 0) {
temp <- difftime(time1 = data[[eval(x)]], time2 = data[[paste0("Diff_", NLag2, "_", x, "_temp")]], units = "days")
} else {
temp <- difftime(time1 = data[[paste0("Diff_",NLag1, "_", x, "_temp")]], time2 = data[[paste0("Diff_", NLag1,"-", NLag2, "_", x, "_temp")]], units = "days")
}
} else if(Type == "categorical") {
if(NLag1 == 0) {
temp <- "No_Change"
temp <- ifelse(data[[eval(x)]] != data[[paste0("Diff_", NLag2, "_", x)]], paste0("New=",data[[eval(x)]]," Old=",data[[paste0("Diff_", NLag2, "_", x)]]), "No_Change")
} else {
temp <- ifelse(data[[paste0("Diff_", NLag1, "_", x)]] != data[[paste0("Diff_", NLag2, "_", x)]], paste0("New=",data[[eval(x)]]," Old=",data[[paste0("Diff_", NLag2, "_", x)]]), "No_Change")
}
}
if(Type == "categorical") {
return(temp)
} else {
return(as.numeric(temp))
}
}
#' @title AutoDiffLagN
#'
#' @description AutoDiffLagN create differences for selected numerical columns
#'
#' @family Feature Engineering
#' @author Adrian Antico
#'
#' @param data Source data
#' @param DateVariable Date column used for sorting
#' @param GroupVariables Difference data by group
#' @param DiffVariables Column names of numeric columns to difference
#' @param DiffDateVariables Columns names for date variables to difference. Output is a numeric value representing the difference in days.
#' @param DiffGroupVariables Column names for categorical variables to difference. If no change then the output is 'No_Change' else 'New=NEWVAL Old=OLDVAL' where NEWVAL and OLDVAL are placeholders for the actual values
#' @param NLag1 If the diff calc, we have column 1 - column 2. NLag1 is in reference to column 1. If you want to take the current value minus the previous weeks value, supply a zero. If you want to create a lag2 - lag4 NLag1 gets a 2.
#' @param NLag2 If the diff calc, we have column 1 - column 2. NLag2 is in reference to column 2. If you want to take the current value minus the previous weeks value, supply a 1. If you want to create a lag2 - lag4 NLag1 gets a 4.
#' @param Type 'lag' or 'lead'
#' @param Sort TRUE to sort your data inside the function
#' @param RemoveNA Set to TRUE to remove rows with NA generated by the lag operation
#' @examples
#' \dontrun{
#'
#' # Create fake data
#' data <- Rodeo::FakeDataGenerator(
#' Correlation = 0.70,
#' N = 50000,
#' ID = 2L,
#' FactorCount = 3L,
#' AddDate = TRUE,
#' ZIP = 0L,
#' TimeSeries = FALSE,
#' ChainLadderData = FALSE,
#' Classification = FALSE,
#' MultiClass = FALSE)
#'
#' # Store Cols to diff
#' Cols <- names(data)[which(unlist(data[, lapply(.SD, is.numeric)]))]
#'
#' # Clean data before running AutoDiffLagN
#' data <- Rodeo::ModelDataPrep(data = data, Impute = FALSE, CharToFactor = FALSE, FactorToChar = TRUE)
#'
#' # Run function
#' data <- Rodeo::AutoDiffLagN(
#' data,
#' DateVariable = "DateTime",
#' GroupVariables = c("Factor_1", "Factor_2"),
#' DiffVariables = Cols,
#' DiffDateVariables = NULL,
#' DiffGroupVariables = NULL,
#' NLag1 = 0L,
#' NLag2 = 1L,
#' Sort = TRUE,
#' RemoveNA = TRUE)
#' }
#'
#' @export
AutoDiffLagN <- function(data,
DateVariable = NULL,
GroupVariables = NULL,
DiffVariables = NULL,
DiffDateVariables = NULL,
DiffGroupVariables = NULL,
NLag1 = 0L,
NLag2 = 1L,
Type = 'lag',
Sort = FALSE,
RemoveNA = TRUE) {
# Ensure data.table ----
if(!data.table::is.data.table(data)) data.table::setDT(data)
# Check args ----
if(!is.null(DateVariable) && !is.character(DateVariable)) stop("DateVariable needs to be a charcter valued vector or scalar")
if(!is.null(GroupVariables) && !is.character(GroupVariables)) stop("GroupVariables needs to be a charcter valued vector or scalar")
if(!is.numeric(NLag1)) stop("NLag1 needs to be a numeric valued scalar")
if(!is.numeric(NLag2)) stop("NLag2 needs to be a numeric valued scalar")
if(NLag1 < 0) stop("NLag1 needs to be a positive numeric valued scalar")
if(NLag2 < 0) stop("NLag2 needs to be a positive numeric valued scalar")
if(!is.logical(Sort)) stop("Sort needs to be a logical valued scalar")
# Sort if TRUE ----
if(!is.null(GroupVariables)) {
data.table::setorderv(x = data, cols = c(GroupVariables, DateVariable), order = c(rep(1, length(GroupVariables)), 1), na.last = FALSE)
} else {
data.table::setorderv(x = data, cols = c(DateVariable), order = 1L, na.last = FALSE)
}
# Diff numeric data ----
if(!is.null(DiffVariables)) {
if(NLag1 == 0L) {
ModDiffVariables <- paste0("Diff_", NLag2, "_", DiffVariables)
data[, (ModDiffVariables) := lapply(.SD, collapse::fdiff, n = NLag2), .SDcols = c(DiffVariables)]
} else {
ModDiffVariables1 <- paste0("Diff_", NLag1, "_", DiffVariables)
ModDiffVariables2 <- paste0("Diff_", NLag1,"-", NLag2, "_", DiffVariables)
if(!is.null(GroupVariables)) {
data <- data[, (ModDiffVariables1) := data.table::shift(x = .SD, n = NLag1, fill = NA, type = Type), .SDcols = c(DiffVariables), by = eval(GroupVariables)]
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = NA, type = Type), .SDcols = c(DiffVariables), by = eval(GroupVariables)]
} else {
data <- data[, (ModDiffVariables1) := data.table::shift(x = .SD, n = NLag1, fill = NA, type = Type), .SDcols = c(DiffVariables)]
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = NA, type = Type), .SDcols = c(DiffVariables)]
}
data[, (ModDiffVariables2) := {g <- list(); for(x in DiffVariables) g[[x]] <- DiffDT(data, x, NLag1, NLag2, Type = "numeric"); g}]
data.table::set(data, j = ModDiffVariables1, value = NULL)
}
}
# Diff date data ----
if(!is.null(DiffDateVariables)) {
if(NLag1 == 0L) {
ModDiffVariables1 <- paste0("Diff_", NLag2, "_", DiffDateVariables)
ModDiffVariables2 <- paste0("Diff_", NLag2, "_", DiffDateVariables, "_temp")
if(!is.null(GroupVariables)) {
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = NA, type = Type), .SDcols = c(DiffDateVariables), by = eval(GroupVariables)]
} else {
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = NA, type = Type), .SDcols = c(DiffDateVariables)]
}
data <- data[, (ModDiffVariables1) := {g <- list(); for(x in DiffDateVariables) g[[x]] <- DiffDT(data, x, NLag1, NLag2, Type = "date"); g}]
data.table::set(data, j = ModDiffVariables2, value = NULL)
} else {
ModDiffVariables1 <- paste0("Diff_", NLag1, "_", DiffDateVariables,"_temp")
ModDiffVariables2 <- paste0("Diff_", NLag1,"-", NLag2, "_", DiffDateVariables,"_temp")
ModDiffVariables22 <- paste0("Diff_", NLag1,"-", NLag2, "_", DiffDateVariables)
if(!is.null(GroupVariables)) {
data <- data[, (ModDiffVariables1) := data.table::shift(x = .SD, n = NLag1, fill = NA, type = Type), .SDcols = c(DiffDateVariables), by = eval(GroupVariables)]
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = NA, type = Type), .SDcols = c(DiffDateVariables), by = eval(GroupVariables)]
} else {
data <- data[, (ModDiffVariables1) := data.table::shift(x = .SD, n = NLag1, fill = NA, type = Type), .SDcols = c(DiffDateVariables)]
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = NA, type = Type), .SDcols = c(DiffDateVariables)]
}
data <- data[, (ModDiffVariables22) := {g <- list(); for(x in DiffDateVariables) g[[x]] <- DiffDT(data, x, NLag1, NLag2, Type = "date"); g}]
data.table::set(data, j = c(ModDiffVariables1, ModDiffVariables2), value = NULL)
}
}
# Diff categorical data ----
if(!is.null(DiffGroupVariables)) {
if(NLag1 == 0L) {
ModDiffVariables <- paste0("Diff_", NLag2, "_", DiffGroupVariables)
if(!is.null(GroupVariables)) {
data <- data[, (ModDiffVariables) := data.table::shift(x = .SD, n = NLag2, fill = "missing", type = Type), .SDcols = c(DiffGroupVariables), by = eval(GroupVariables)]
} else {
data <- data[, (ModDiffVariables) := data.table::shift(x = .SD, n = NLag2, fill = "missing", type = Type), .SDcols = c(DiffGroupVariables)]
}
data <- data[, (ModDiffVariables) := {g <- list(); for(x in DiffGroupVariables) g[[x]] <- DiffDT(data, x, NLag1, NLag2, Type = "categorical"); g}]
} else {
ModDiffVariables1 <- paste0("Diff_", NLag1, "_", DiffGroupVariables)
ModDiffVariables2 <- paste0("Diff_", NLag1,"-", NLag2, "_", DiffGroupVariables)
if(!is.null(GroupVariables)) {
data <- data[, (ModDiffVariables1) := data.table::shift(x = .SD, n = NLag1, fill = "missing", type = Type), .SDcols = c(DiffGroupVariables), by = eval(GroupVariables)]
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = "missing", type = Type), .SDcols = c(DiffGroupVariables), by = eval(GroupVariables)]
} else {
data <- data[, (ModDiffVariables1) := data.table::shift(x = .SD, n = NLag1, fill = "missing", type = Type), .SDcols = c(DiffGroupVariables)]
data <- data[, (ModDiffVariables2) := data.table::shift(x = .SD, n = NLag2, fill = "missing", type = Type), .SDcols = c(DiffGroupVariables)]
}
data <- data[, (ModDiffVariables2) := {g <- list(); for(x in DiffGroupVariables) g[[x]] <- DiffDT(data, x, NLag1, NLag2, Type = "categorical"); g}]
data.table::set(data, j = ModDiffVariables1, value = NULL)
}
}
# Final prep ----
if(RemoveNA) {
if(NLag1 == 0L) {
if(!is.null(DiffVariables)) {
data <- data[!is.na(get(paste0("Diff_", NLag2, "_", DiffVariables[1L])))]
} else if(!is.null(DiffDateVariables)) {
data <- data[!is.na(get(paste0("Diff_", NLag2, "_", DiffDateVariables[1L])))]
} else if(!is.null(DiffGroupVariables)) {
data <- data[!is.na(get(paste0("Diff_", NLag2, "_", DiffGroupVariables[1L])))]
}
} else {
if(!is.null(DiffVariables)) {
data <- data[!is.na(get(paste0("Diff_", NLag1,"-", NLag2, "_", DiffVariables[1L])))]
} else if(!is.null(DiffDateVariables)) {
if(!is.null(DiffDateVariables)) data <- data[!is.na(get(paste0("Diff_", NLag1,"-", NLag2, "_", DiffDateVariables[[1L]])))]
} else if(!is.null(DiffGroupVariables)) {
data <- data[!is.na(get(paste0("Diff_", NLag1,"-", NLag2, "_", DiffGroupVariables[1L])))]
}
}
}
# Return data
return(data)
}
#' @title AutoLagRollStats
#'
#' @description AutoLagRollStats Builds lags and a large variety of rolling statistics with options to generate them for hierarchical categorical interactions.
#'
#' @author Adrian Antico
#' @family Feature Engineering
#'
#' @param data A data.table you want to run the function on
#' @param Targets A character vector of the column names for the reference column in which you will build your lags and rolling stats
#' @param DateColumn The column name of your date column used to sort events over time
#' @param IndependentGroups A vector of categorical column names that you want to have run independently of each other. This will mean that no interaction will be done.
#' @param HierarchyGroups A vector of categorical column names that you want to have generate all lags and rolling stats done for the individual columns and their full set of interactions.
#' @param TimeGroups A vector of TimeUnits indicators to specify any time-aggregated GDL features you want to have returned. E.g. c("raw" (no aggregation is done),"hour", "day","week","month","quarter","year")
#' @param TimeBetween Specify a desired name for features created for time between events. Set to NULL if you don't want time between events features created.
#' @param TimeUnit List the time aggregation level for the time between events features, such as "hour", "day", "weeks", "months", "quarter", or "year"
#' @param TimeUnitAgg List the time aggregation of your data that you want to use as a base time unit for your features. E.g. "raw" or "day"
#' @param Lags A numeric vector of the specific lags you want to have generated. You must include 1 if WindowingLag = 1.
#' @param MA_RollWindows A numeric vector of the specific rolling statistics window sizes you want to utilize in the calculations.
#' @param SD_RollWindows A numeric vector of Standard Deviation rolling statistics window sizes you want to utilize in the calculations.
#' @param Skew_RollWindows A numeric vector of Skewness rolling statistics window sizes you want to utilize in the calculations.
#' @param Kurt_RollWindows A numeric vector of Kurtosis rolling statistics window sizes you want to utilize in the calculations.
#' @param Quantile_RollWindows A numeric vector of Quantile rolling statistics window sizes you want to utilize in the calculations.
#' @param Quantiles_Selected Select from the following c("q5", "q10", "q15", "q20", "q25", "q30", "q35", "q40", "q45", "q50", "q55", "q60"," q65", "q70", "q75", "q80", "q85", "q90", "q95")
#' @param RollOnLag1 Set to FALSE to build rolling stats off of target columns directly or set to TRUE to build the rolling stats off of the lag-1 target
#' @param Type List either "Lag" if you want features built on historical values or "Lead" if you want features built on future values
#' @param SimpleImpute Set to TRUE for factor level imputation of "0" and numeric imputation of -1
#' @param ShortName Default TRUE. If FALSE, Group Variable names will be added to the rolling stat and lag names. If you plan on have multiple versions of lags and rollings stats by different group variables then set this to FALSE.
#' @param Debug Set to TRUE to get a print of which steps are running
#' @return data.table of original data plus created lags, rolling stats, and time between event lags and rolling stats
#' @examples
#' \dontrun{
#' # Create fake Panel Data----
#' Count <- 1L
#' for(Level in LETTERS) {
#' datatemp <- Rodeo::FakeDataGenerator(
#' Correlation = 0.75,
#' N = 25000L,
#' ID = 0L,
#' ZIP = 0L,
#' FactorCount = 0L,
#' AddDate = TRUE,
#' Classification = FALSE,
#' MultiClass = FALSE)
#' datatemp[, Factor1 := eval(Level)]
#' if(Count == 1L) {
#' data <- data.table::copy(datatemp)
#' } else {
#' data <- data.table::rbindlist(
#' list(data, data.table::copy(datatemp)))
#' }
#' Count <- Count + 1L
#' }
#'
#' # Add scoring records
#' data <- Rodeo::AutoLagRollStats(
#' data = data,
#' DateColumn = "DateTime",
#' Targets = "Adrian",
#' HierarchyGroups = NULL,
#' IndependentGroups = c("Factor1"),
#' TimeUnitAgg = "days",
#' TimeGroups = c("days","weeks","months","quarters"),
#' TimeBetween = NULL,
#' TimeUnit = "days",
#' RollOnLag1 = TRUE,
#' Type = "Lag",
#' SimpleImpute = TRUE,
#' Lags = list("days" = c(seq(1,5,1)), "weeks" = c(seq(1,3,1)), "months" = c(seq(1,2,1)), "quarters" = c(seq(1,2,1))),
#' MA_RollWindows = list("days" = c(seq(1,5,1)), "weeks" = c(seq(1,3,1)), "months" = c(seq(1,2,1)), "quarters" = c(seq(1,2,1))),
#' SD_RollWindows = list("days" = c(seq(1,5,1)), "weeks" = c(seq(1,3,1)), "months" = c(seq(1,2,1)), "quarters" = c(seq(1,2,1))),
#' Skew_RollWindows = list("days" = c(seq(1,5,1)), "weeks" = c(seq(1,3,1)), "months" = c(seq(1,2,1)), "quarters" = c(seq(1,2,1))),
#' Kurt_RollWindows = list("days" = c(seq(1,5,1)), "weeks" = c(seq(1,3,1)), "months" = c(seq(1,2,1)), "quarters" = c(seq(1,2,1))),
#' Quantile_RollWindows = list("days" = c(seq(1,5,1)), "weeks" = c(seq(1,3,1)), "months" = c(seq(1,2,1)), "quarters" = c(seq(1,2,1))),
#' Quantiles_Selected = c('q5','q50'),
#' Debug = FALSE)
#' }
#' @export
AutoLagRollStats <- function(data,
Targets = NULL,
HierarchyGroups = NULL,
IndependentGroups = NULL,
DateColumn = NULL,
TimeUnit = NULL,
TimeUnitAgg = NULL,
TimeGroups = NULL,
TimeBetween = NULL,
RollOnLag1 = TRUE,
Type = "Lag",
SimpleImpute = TRUE,
Lags = NULL,
MA_RollWindows = NULL,
SD_RollWindows = NULL,
Skew_RollWindows = NULL,
Kurt_RollWindows = NULL,
Quantile_RollWindows = NULL,
Quantiles_Selected = NULL,
ShortName = TRUE,
Debug = FALSE) {
# Define args ----
RollFunctions <- c()
if(!is.null(MA_RollWindows)) RollFunctions <- c(RollFunctions,"mean")
if(!is.null(SD_RollWindows)) RollFunctions <- c(RollFunctions,"sd")
if(!is.null(Skew_RollWindows)) RollFunctions <- c(RollFunctions,"skew")
if(!is.null(Kurt_RollWindows)) RollFunctions <- c(RollFunctions,"kurt")
if(!is.null(Quantiles_Selected)) RollFunctions <- c(RollFunctions,Quantiles_Selected)
if(is.null(TimeBetween)) TimeBetween <- NULL else TimeBetween <- "TimeBetweenRecords"
if(RollOnLag1) RollOnLag1 <- 1L else RollOnLag1 <- 0L
TimeGroupPlaceHolder <- c()
if("raw" %chin% tolower(TimeGroups)) TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "raw")
if(any(c("hours","hour","hr","hrs","hourly") %chin% tolower(TimeGroups))) {
TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "hour")
if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour"
if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour"
if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour"
if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour"
if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour"
if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour"
}
if(any(c("days","day","dy","dd","d") %chin% tolower(TimeGroups))) {
TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "day")
if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("days","day","dy","dd","d"))] <- "day"
if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day"
if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day"
if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day"
if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day"
if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day"
}
if(any(c("weeks","week","weaks","weak","wk","wkly","wks") %chin% tolower(TimeGroups))) {
TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "weeks")
if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks"
if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks"
if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks"
if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks"
if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks"
if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks"
}
if(any(c("months","month","mth","mnth","monthly","mnthly") %chin% tolower(TimeGroups))) {
TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "months")
if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months"
if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months"
if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months"
if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months"
if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months"
if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months"
}
if(any(c("quarter","quarters","qarter","quarterly","q","qtly") %chin% tolower(TimeGroups))) {
TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "quarter")
if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter"
if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter"
if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter"
if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter"
if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter"
if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter"
}
if(any(c("year","years","annual","yearly","annually","ann","yr","yrly") %chin% tolower(TimeGroups))) {
TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "year")
if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year"
if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year"
if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year"
if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year"
if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year"
if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year"
}
TimeGroups <- TimeGroupPlaceHolder
if(is.null(TimeUnitAgg)) TimeUnitAgg <- TimeGroups[1L]
#The correct TimeGroups are: c("hour", "day", "weeks", "months", "quarter", "year", "1min", "5min", "10min", "15min", "30min", "45min")
# Ensure date column is proper ----
if(Debug) print("Data Wrangling: Convert DateColumnName to Date or POSIXct----")
if(!(tolower(TimeUnit) %chin% c("1min","5min","10min","15min","30min","hour"))) {
if(is.character(data[[eval(DateColumn)]])) {
x <- data[1,get(DateColumn)]
x1 <- lubridate::guess_formats(x, orders = c("mdY", "BdY", "Bdy", "bdY", "bdy", "mdy", "dby", "Ymd", "Ydm"))
data.table::set(data, j = eval(DateColumn), value = as.Date(data[[eval(DateColumn)]], tryFormats = x1))
}
} else {
data.table::set(data, j = eval(DateColumn), value = as.POSIXct(data[[eval(DateColumn)]]))
}
# Debugging----
if(Debug) print("AutoLagRollStats: No Categoricals")
# No Categoricals----
if(is.null(IndependentGroups) && is.null(HierarchyGroups)) {
# Initialize Counter----
Counter <- 0L
# Loop through various time aggs----
for(timeaggs in TimeGroups) {
# Increment Counter----
Counter <- Counter + 1L
# Copy data----
tempData <- data.table::copy(data)
# Check time scale----
if(Counter > 1) {
# Floor Date column to timeagg level----
data.table::set(tempData, j = eval(DateColumn), value = lubridate::floor_date(x = tempData[[eval(DateColumn)]], unit = timeaggs))
# Agg by date column----
tempData <- tempData[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(eval(Targets)), by = c(eval(DateColumn))]
# Build features----
tempData <- DT_GDL_Feature_Engineering(
tempData,
lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags,
periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows,
SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows,
Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows,
Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows,
Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows,
statsFUNs = RollFunctions,
targets = Targets,
groupingVars = NULL,
sortDateName = DateColumn,
timeDiffTarget = NULL,
timeAgg = timeaggs,
WindowingLag = RollOnLag1,
ShortName = ShortName,
Type = Type,
SimpleImpute = SimpleImpute)
} else {
# Build features----
data.table::setkeyv(data <- DT_GDL_Feature_Engineering(
data,
lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags,
periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows,
SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows,
Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows,
Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows,
Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows,
statsFUNs = RollFunctions,
targets = Targets,
groupingVars = NULL,
sortDateName = DateColumn,
timeDiffTarget = NULL,
timeAgg = timeaggs,
WindowingLag = RollOnLag1,
ShortName = ShortName,
Type = Type,
SimpleImpute = SimpleImpute), DateColumn)
}
# Check if timeaggs is same of TimeUnit----
if(Counter > 1L) {
data.table::setkeyv(data[, TEMPDATE := lubridate::floor_date(get(DateColumn), unit = eval(timeaggs))], "TEMPDATE")
data[tempData, (setdiff(names(tempData), names(data))) := mget(paste0("i.", setdiff(names(tempData), names(data))))]
data.table::set(data, j = "TEMPDATE", value = NULL)
}
}
}
# Debugging----
if(Debug) print("AutoLagRollStats: Indep + Hierach")
# Hierarchy Categoricals----
if(!is.null(HierarchyGroups)) {
# Categorical Names Fully Interacted----
Categoricals <- FullFactorialCatFeatures(GroupVars = HierarchyGroups, BottomsUp = TRUE)
# Categorical Names Fully Interacted (Check if there already)----
for(cat in seq_len(length(Categoricals)-length(HierarchyGroups))) {
if(!any(names(data) %chin% Categoricals[cat])) data[, eval(Categoricals[cat]) := do.call(paste, c(.SD, sep = " ")), .SDcols = c(unlist(data.table::tstrsplit(Categoricals[cat], "_")))]
}
# Loop through each feature interaction
Counter <- 0L
for(Fact in Categoricals) {
# Loop through all TimeGroups----
for(timeaggs in TimeGroups) {
# Counter incrementing
Counter <- Counter + 1L
# Check if timeaggs is same of TimeUnitAgg ----
if(Counter > 1L) {
# Aggregate tempData and tempRegs to correct dimensional level----
tempData <- data[, .SD, .SDcols = c(eval(Targets), eval(DateColumn), eval(Fact))]
# Agg by date column ----
if(timeaggs != "raw") {
tempData[, eval(DateColumn) := lubridate::floor_date(x = get(DateColumn), unit = timeaggs)]
tempData <- tempData[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(eval(Targets)), by = c(eval(DateColumn), eval(Fact))]
}
# Build GDL Features----
data.table::setkeyv(tempData <- DT_GDL_Feature_Engineering(
tempData,
lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags,
periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows,
SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows,
Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows,
Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows,
Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows,
statsFUNs = RollFunctions,
targets = Targets,
groupingVars = Fact,
sortDateName = DateColumn,
timeDiffTarget = NULL,
timeAgg = timeaggs,
WindowingLag = RollOnLag1,
ShortName = ShortName,
Type = Type,
SimpleImpute = SimpleImpute), c(Fact, DateColumn))
} else {
# Build GDL Features----
data <- DT_GDL_Feature_Engineering(
data,
lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags,
periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows,
SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows,
Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows,
Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows,
Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows,
statsFUNs = RollFunctions,
targets = Targets,
groupingVars = Fact,
sortDateName = DateColumn,
timeDiffTarget = NULL,
timeAgg = timeaggs,
WindowingLag = RollOnLag1,
ShortName = ShortName,
Type = Type,
SimpleImpute = SimpleImpute)
}
# Check if timeaggs is same of TimeUnit----
if(Counter > 1L) {
data.table::setkeyv(data[, TEMPDATE := lubridate::floor_date(get(DateColumn), unit = eval(timeaggs))], c(Fact,"TEMPDATE"))
data[tempData, (setdiff(names(tempData), names(data))) := mget(paste0("i.", setdiff(names(tempData), names(data))))]
data.table::set(data, j = "TEMPDATE", value = NULL)
}
}
}
}
# Debugging----
if(Debug) print("AutoLagRollStats: Indep")
# Single categoricals at a time AND no hierarchical: if there are hierarchical the single cats will be handled above----
if(!is.null(IndependentGroups) && is.null(HierarchyGroups)) {
# Loop through IndependentGroups----
Counter <- 0L
# Fact = IndependentGroups[1]
# timeaggs = TimeGroups[1]
for(Fact in IndependentGroups) {
# Loop through all TimeGroups----
for(timeaggs in TimeGroups) {
# Counter incrementing
Counter <- Counter + 1L
# Copy data----
tempData <- data.table::copy(data)
# Check if timeaggs is same of TimeUnit ----
if(Counter > 1L) {
# Floor Date column to timeagg level ----
tempData[, eval(DateColumn) := lubridate::floor_date(x = get(DateColumn), unit = timeaggs)]