-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_functions_analysis.R
2366 lines (1860 loc) · 76.7 KB
/
helper_functions_analysis.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
################################################################################
# Section 1: Dummies ###########################################################
################################################################################
# Section 1.1: updated function has output just like dummy_cols; but is A LOT FASTER! :) ----
dummy_cols_for_big_data <- function(datatable,
index,
col,
vector_of_dummies,
ignore_na=F){
# delete later - example
# datatable <- owners %>% copy()
# index <- index_fpyi
# col <- "nationality"
# vector_of_dummies <- nationality %>% .[, nationality]
# datatable <- owners_fy;
# index <- index_fyi;
# col <- characteristic;
# vector_of_dummies <- unique_characteristics;
# ignore_na <- T
# make sure elements are unique
vector_of_dummies <- unique(vector_of_dummies) %>% sort()
# convert into a vector must be a vector
column <- c(col)
# set up subset of data.table
subset <- append(index, column)
datatable_subset <- datatable %>% copy() %>% .[, ..subset]
names(datatable_subset) <- index %>% append(c("column"))
paste0("creating dummies for column: ", col, "; for the following elements: ") %>% print()
# for each unique element in the vector of dummy elements
for(element in vector_of_dummies){
print(element)
# temporary data.table just with column
datatable_subset_tmp <- datatable_subset %>% copy()
# create indicator
datatable_subset_tmp[,indicator := 0]
datatable_subset_tmp[column==element, indicator := 1]
just_element <- paste0(col, "_", element) %>% c()
names(datatable_subset_tmp) <- index %>% append(., c('column')) %>% append(just_element)
if(element==vector_of_dummies[1]){
datatable_subset_out <- datatable_subset_tmp %>% copy()
}else{
datatable_subset_out <- datatable_subset_tmp %>% copy() %>%
.[, ..just_element] %>%
cbind(datatable_subset_out,. )
}
}
if(!ignore_na){
# create a missing column
datatable_subset_out[, NA_MISSING := 0][is.na(column), NA_MISSING := 1]
vars_names <- names(datatable_subset_out)
names(datatable_subset_out)[length(vars_names)] <- paste0(col, "_NA_MISSING")
}
# rename column & dummies in the same way as the original dummy cols
datatable_subset_out[, column := NULL]
# merge with input
datatable_out <- datatable %>% merge(x = ., y = datatable_subset_out, by = index, all=T)
# output
return(datatable_out)
print("Notice: all dummy columns are output; even those with all zeros! :) ")
}
# Section 1.2: create firm-year indexed panel of `at least one` indicators ----
create_fy_indicator_alo <- function(datatable,
index_fy,
index_fyi,
vars_owner_characteristics){
# delete later
# datatable <- copy(owners_fyi)
# index_fy<-index_fy
# index_fyi<-index_fyi
# vars_owner_characteristics <- vars_characteristics
# section 0: initialize dummies data-set
owners_fyi_dummies <- datatable %>% copy()
# section 1: create dummies for all characteristics, for all owners ----
print("1/3: create dummies for all characteristics, for all owners")
# for all owners; for each characteristic, create full set of indicators
for(characteristic in vars_owner_characteristics){
print(characteristic)
# place variable into vector for subsetting
vars_characteristic <- c(characteristic)
# get all of the unique characteristics
unique_characteristics <- owners_fyi_dummies %>% .[, ..vars_characteristic] %>% unique() %>% unlist
unique_characteristics %<>% ifelse(is.na(.), 0, .)
owners_fyi_dummies <- dummy_cols_for_big_data(
datatable = owners_fyi_dummies,
index = index_fyi,
col = characteristic,
vector_of_dummies = unique_characteristics,
ignore_na = F)
}
# section 2: compute totals for each firmid-year ----
print("2/3: aggregate (sum) dummies at the firm-year level")
# section 2.1: keep dummies and firmid-year identifier ------
vars_owners_fyi_dummies <- get_new_column_names(
old_datatable = datatable,
new_datatable = owners_fyi_dummies)
vars_keep_these <- append(index_fy, vars_owners_fyi_dummies)
# section 2.2: compute totals for each firmid-year ----
# owner sum variables
vars_firms_fy_sum <- paste0("fy_sum_", vars_owners_fyi_dummies)
firms_fy_sum <- owners_fyi_dummies %>%
# reduce data-set
.[, ..vars_keep_these] %>%
# aggregate over firm-year index
.[, lapply(.SD, sum, na.rm=T), index_fy] %>%
# rename columns to indicate they are sums
rename_columns(
datatable = .,
current_names = vars_owners_fyi_dummies,
new_names = vars_firms_fy_sum)
# section 3: create indicators based on totals for each firmid-year ----
print("3/3: create 'At Least One' indicators at the firm-year level")
# owner indicator variable names
vars_firms_fy_indicator_alo <- paste0("fy_indicator_alo_", vars_owners_fyi_dummies)
# section 2.3.1: create indicators based on totals for each firmid-year ----
firms_fy_indicator_alo <- firms_fy_sum %>% copy() %>%
# isolate sum variables
.[, ..vars_firms_fy_sum] %>%
# determine if each is greater than zero (greater than or equal to one)
.[, lapply(.SD, is_greater_than_zero)] %>%
# append index
cbind(firms_fy_sum[, ..index_fy], .) %>%
# rename columns to indicate they are indicators
rename_columns(datatable = .,
current_names = vars_firms_fy_sum,
new_names = vars_firms_fy_indicator_alo)
# section 4: export
return(firms_fy_indicator_alo)
}
# Section 1.3: create firm-year-individual indexed panel of indicators ----
create_fyi_indicator <- function(datatable,
index_fy,
index_fyi,
vars_individual_characteristics){
# delete later
# datatable <- copy(workers_fyi)
# index_fy<-index_fy
# index_fyi<-index_fyi
# vars_individual_characteristics <- vars_characteristics
# section 0: initialize dummies data-set
individual_fyi_dummies <- datatable %>% copy()
# section 1: create dummies for all characteristics, for all individual ----
print("1/1: create dummies for all characteristics, for all individuals")
# for all owners; for each characteristic, create full set of indicators
for(characteristic in vars_individual_characteristics){
print(characteristic)
# place variable into vector for subsetting
vars_characteristic <- c(characteristic)
# get all of the unique characteristics
unique_characteristics <- individual_fyi_dummies %>% .[, ..vars_characteristic] %>% unique() %>% unlist
individual_fyi_dummies <- dummy_cols_for_big_data(
datatable = individual_fyi_dummies,
index = index_fyi,
col = characteristic,
vector_of_dummies = unique_characteristics,
ignore_na = F)
}
# section 2.1: keep dummies and firmid-year identifier ------
vars_individual_fyi_dummies <- get_new_column_names(
old_datatable = datatable,
new_datatable = individual_fyi_dummies)
vars_keep_these <- append(index_fyi, vars_individual_fyi_dummies)
individual_fyi_dummies <- individual_fyi_dummies %>%
.[, ..vars_keep_these]
# rename
individual_fyi_dummies <- rename_columns(datatable = individual_fyi_dummies,
current_names = vars_individual_fyi_dummies,
new_names = paste0("i_", vars_individual_fyi_dummies))
# section 4: export
return(individual_fyi_dummies)
}
# Section 1.4: convert all of the variables in a data-set to boolean excpet index ----
convert_to_boolean_gtz <- function(datatable, index, prefix="bool_"){
print("converting numeric variables greater than zero to boolean")
# all columns except index will be converted
convert_these <- names(datatable) %>% .[!(.%in% index)]
new_convert_these <- paste0(prefix, convert_these)
out <- datatable %>% copy() %>%
.[, ..convert_these] %>%
.[, lapply(.SD, is_greater_than_zero)] %>%
cbind(datatable[, ..index], .) %>%
rename_columns(
.,
current_names = convert_these,
new_names = new_convert_these)
return(out)
}
# Section 1.5: create create_alo_column_is_not_local function to indicate that at least one surname is not local (our paper) ----
create_alo_column_is_not_local <- function(datatable, index, not_local_name, omit_these_variables){
# do not sum across the index nor the local origin variable
omit_from_sum <-c(omit_these_variables) %>% append(index, .)
datatable <- datatable %>%
# sum across the indicators for whether there is
create_variable_row_sum_greater_than_zero(
datatable = .,
variables_to_omit = omit_from_sum,
column_name = not_local_name
)
return(datatable)
}
# Section 1.6: create a new column which indicates whether both columns are equal to one another ----
are_both_dummies_one <- function(datatable, dummyA, dummyB, new_dummy_name){
# datatable = dyads_dt_light_all;
# dummyA = worker_dummy;
# dummyB = firm_dummy;
# new_dummy_name = var_share_column
keep1 <- c(dummyA, dummyB) #%>% append(index, .)
keep2 <- c(new_dummy_name) #%>% append(index,. )
out <- datatable %>%
# subset columns
.[, ..keep1] %>%
# rename columns
rename_columns(datatable = .,
current_names = c(dummyA, dummyB),
new_names = c("dummyA", "dummyB")) %>%
# create new column for whether dummies are both equal to 1
.[, new_dummy := ((dummyA==dummyB)&(dummyA==1))*1] %>%
# rename columns
rename_columns(datatable = .,
current_names = c("new_dummy"),
new_names = c(new_dummy_name)) %>%
.[, ..keep2]
return(out)
}
# create variable that sums across rows, except specific rows ----
create_variable_row_sum_greater_than_zero <- function(datatable,
variables_to_omit,
column_name){
# get columns which are not either the key or the specified column
vars_to_sum <- datatable %>% names() %>% .[!(.%in%variables_to_omit)] #%>% .[!(.%in%index)]
series <- datatable %>% copy() %>%
.[,..vars_to_sum] %>%
apply(., 1, sum, na.rm=T) %>%
data.table() %>%
dplyr::rename(., column_name_sum =".") %>%
.[, column_name_greater_than_zero := is_greater_than_zero(column_name_sum)] %>%
.[, .(column_name_greater_than_zero)]
names(series) <- column_name
datatable <- datatable %>% copy() %>%
cbind(., series)
return(datatable)
}
# create boolean using vector of categories -----
create_boolean_using_vector_of_categories <-
function(datatable, categories, variable){
datatable <- datatable %>% copy() %>%
rename_columns(
datatable = .,
current_names = c(variable),
new_names = c("variable"))
datatable %>% copy() %>%
.[, variable] %>%
lapply(X = categories, FUN = str_detect, string = .) %>%
as.data.table() %>%
rename_columns(
datatable = .,
current_names = names(.),
new_names = categories) %>%
return()
}
# create dummies using vector of categories -----
create_dummy_if_any_category_present <-
function(datatable, categories, variable, indicator_name="contains_at_least_one_category"){
datatable_original <- datatable %>% copy()
# create a matrix indicating the presense of each category
create_boolean_using_vector_of_categories(
datatable=datatable,
categories = categories,
variable=variable) %>%
# sum across all indicators
apply(X = .,MARGIN = 1, FUN = sum, na.rm=T) %>%
#wrangle
as.data.table() %>%
rename_columns(
datatable = .,
current_names = c("."),
new_names = c("SUM")) %>%
.[, SUM := (SUM>0)*1] %>%
# rename
rename_columns(
datatable = .,
current_names = c("SUM"),
new_names = c(indicator_name)) %>%
# bind back to original dataset
cbind(datatable_original, .) %>%
# output
return()
}
# indicate years present: spit out matrix with the years available -----
indicate_years_present <- function(
datatable,
year_min,
year_max,
variable_start_str,
variable_end_str){
# delete later
# parameters to be defined
# datatable <- peppercat2 %>% copy()
# year_min <- 1990
# year_max <- 2022+3
# variable_start_str = "year_start_str"
# variable_end_str = "year_end_assumed_str"
print("Notice: start & end year variables must be characters!")
# define order
year_order <- (c(year_min:year_max)-year_min)+1
year_order_rev <- year_order %>% rev()
available_years <- c(year_min:(year_max)) %>% as.character()
available_years_rev <- available_years %>% rev()
# Section 2: create an indicator for each year -----
# Section 2.1: start year -----
year_start_mat <- datatable %>% copy() %>%
create_boolean_using_vector_of_categories(
datatable = .,
# correct order
categories = available_years,
variable = variable_start_str
) %>%
as.matrix() *1
# Section 2.2: end year -----
year_end_mat_rev <- datatable %>% copy() %>%
create_boolean_using_vector_of_categories(
datatable = .,
# reversed order
categories = available_years_rev,
variable = variable_end_str
) %>%
as.matrix() *1
# Section 3: sum across years -----
for(j in 1:(ncol(year_start_mat)-1)){
print(j)
year_start_mat[,j+1] <- year_start_mat[,j+1] + year_start_mat[,j]
year_end_mat_rev[,j+1] <- year_end_mat_rev[,j+1] + year_end_mat_rev[,j]
}
# reverse end matrix order to correct order
year_end_mat <- year_end_mat_rev[, year_order_rev]
# their intersection sums to 2
years_present <- ((year_start_mat + year_end_mat) == 2)*1
return(years_present)
}
expand_given_start_end_year <- function(
datatable,
year_min = min(years)-10,
year_max = max(years)+10,
variable_start_str = "year_start_str",
variable_end_str = "year_end_str"){
# datatable <- AR_supp
# year_min = min(years)-10
# year_max = max(years) + 10
# variable_start_str = "year_start_str"
# variable_end_str = "year_end_str"
# save original info
datatable_original <- datatable %>% copy()
cols <- datatable_original %>% names() %>% .[!(.%chin%c("year", "in_office", "rowID"))]
cols_new <- append(cols, c("year", "in_office"))
# create rowID
datatable[, rowID:=.I]
# create a matrix with the years that the original row occuied
years_present_rowID <- datatable %>% copy() %>%
indicate_years_present(
datatable = .,
year_min = year_min,
year_max = year_max,
variable_start_str = variable_start_str,
variable_end_str = variable_end_str
) %>%
data.table() %>%
.[, rowID := 1:.N] %>%
melt(data = ., id.vars = "rowID") %>%
.[order(rowID)] %>% # only keep observations where the rowID is present
.[value == 1] %>%
dplyr::rename(., year = variable, in_office = value)
years_present_rowID %>%
merge(x=datatable, y = ., by ="rowID", all=T) %>%
.[, ..cols_new] %>%
.[year_start>=year_min] %>%
return()
}
# indicate years present: spit out matrix with the years available -----
create_dummy_matrix_to_indicate_years_present <- function(
datatable,
year_min,
year_max,
variable_start_str,
variable_end_str){
# delete later
# parameters to be defined
# datatable <- peppercat2 %>% copy()
# year_min <- 1990
# year_max <- 2022+3
# variable_start_str = "year_start_str"
# variable_end_str = "year_end_assumed_str"
message_with_lines("Notice: start & end year variables must be characters!")
# define order
year_order <- (c(year_min:year_max)-year_min)+1
year_order_rev <- year_order %>% rev()
available_years <- c(year_min:(year_max)) %>% as.character()
available_years_rev <- available_years %>% rev()
# Section 2: create an indicator for each year -----
# Section 2.1: start year -----
year_start_mat <- datatable %>% copy() %>%
create_boolean_using_vector_of_categories(
datatable = .,
# correct order
categories = available_years,
variable = variable_start_str
) %>%
as.matrix() *1
# Section 2.2: end year -----
year_end_mat_rev <- datatable %>% copy() %>%
create_boolean_using_vector_of_categories(
datatable = .,
# reversed order
categories = available_years_rev,
variable = variable_end_str
) %>%
as.matrix() *1
# Section 3: sum across years -----
for(j in 1:(ncol(year_start_mat)-1)){
print(j)
year_start_mat[,j+1] <- year_start_mat[,j+1] + year_start_mat[,j]
year_end_mat_rev[,j+1] <- year_end_mat_rev[,j+1] + year_end_mat_rev[,j]
}
# reverse end matrix order to correct order
year_end_mat <- year_end_mat_rev[, year_order_rev]
# their intersection sums to 2
years_present <- ((year_start_mat + year_end_mat) == 2)*1
return(years_present)
}
################################################################################
# Section 2: Merging ###########################################################
################################################################################
# Section 2.1: this function takes in a data-table indexed by an ID variable & outputs two data.tables as a list: (used to be unique_by_column_with_threshold_ids) -----
## once which has more than 'threshold' id's per 'by_column' & another with the wide data & 'threshold columns'
reshape_unique_bycol_with_t_id_cols <- function(datatable, id, by_column, threshold, dir_save, wide_summary_name, unique_by_column_id_prefix = "i", fill=""){
# DELETE LATER
# datatable = datatable_y_alt %>% copy()
# id = "id_y"
# by_column = "by_column"
# threshold = threshold1
# dir_save = dir_save
# wide_summary_name = paste0("bvd", "_", COUNTRY, "_")
# unique_by_column_id_prefix = "y",
# fill = ""
var_name <- id
# section 1: preliminary cleaning of data
datatable_alt <- datatable %>% copy() %>%
rename_columns(
datatable = .,
current_names = c(id, by_column),
new_names = c("id", "by_column") ) %>%
# clean by_column by removing empty strings
.[by_column!=""] %>%
# create a unique id
.[, unique_by_column_id := .GRP, by_column] %>%
.[, unique_by_column_id := paste0(unique_by_column_id_prefix, unique_by_column_id)] %>%
.[, per_by_column := 1:.N ,by_column]
# export this
filename <- paste0(dir_save, wide_summary_name, "wide_summary.csv")
paste0("Saving wide summary in: ", filename) %>% message_with_lines()
datatable_alt %>% copy() %>% .[, .N, .(per_by_column)] %>%
fwrite(., filename)
# display
paste0("Displaying CMF up til threshold for id: (",id, ") and by_column: (", by_column, ")") %>% message_with_lines()
stats <- datatable_alt %>% copy() %>% .[, .N, .(per_by_column)] %>%
.[, cumsum := cumsum(N)] %>%
.[, cumsum_perc := cumsum/sum(N)] %>%
.[1:threshold]
stats %>% print() # 98% of cases occur below 10
# cases where we have more than 10 pepids, are left for later; -----
# identify names with many linked IDs
datatable_alt_try_later <- datatable_alt %>% copy() %>%
.[, max_per_by_column := max(per_by_column),by_column] %>%
.[max_per_by_column>threshold]
datatable_wide <- datatable_alt %>% copy() %>%
.[, max_per_by_column := max(per_by_column),by_column] %>%
.[max_per_by_column<=threshold] %>%
.[, .(id, by_column, unique_by_column_id, per_by_column)] %>%
.[, per_by_column := paste0(var_name, "_", per_by_column)] %>%
dcast(., by_column + unique_by_column_id ~per_by_column, value.var = "id", fill = fill)
out <- list()
out$stats <- stats %>% copy()
out$wide <- datatable_wide %>% copy()
out$try_later <- datatable_alt_try_later %>% copy()
return(out)
}
# Section 2.2: split pattern into threshold+1 columns then compute the pairwise combination of these threshold+1 columns ----------
#split pattern into threshold+1 columns then compute the pairwise combination of these threshold+1 columns
split_pattern_into_tplus1_cols_pairwise_combinations <- function(
datatable, id,string, pattern, threshold_split){
# delete later
# datatable <- datatable_y_wide_step2 %>% copy() %>%
# .[, .(by_column, unique_by_column_id_y)]
# id = "unique_by_column_id_y"
# string = "by_column"
# pattern = " "
# threshold_split = threshold2
# section 1: rename columns & comupute # of occurances of pattern ----
datatable <- datatable %>% copy() %>%
rename_columns(
datatable = .,
current_names = c(id, string),
new_names = c("id", "string")) %>%
.[, string := str_trim(string, side = c("both"))] %>%
.[, n_pattern := str_count(string=string, pattern = pattern)]
# section 2: share statistics ----
paste0("Printing number of pattern: (", pattern, ") occurances in the data.") %>% message_with_lines()
stats <- datatable %>% copy() %>%
.[, .N, n_pattern] %>%
.[order(N)]
stats %>% print()
paste0("threshold_split is currently set to: (", threshold_split, "). threshold_split==n-1. Resulting in (n)*(n-1) (", threshold_split*(threshold_split+1), ") columns.") %>% message_with_lines()
print(threshold_split)
# in case threshold_split > n_pattern; create completely empty columns
max_n_pattern <- stats[, max(n_pattern)]
if(max_n_pattern<threshold_split){
paste0("threshold_split (", threshold_split,") exceeds number of occurances of pattern: (",pattern,"). ",
"Resetting threshold_split to the maximum number of the pattern. ",
"Original threshold_split: (",threshold_split,"). New threshold_split: (",max_n_pattern,")") %>% message_with_lines()
threshold_split <- max_n_pattern
}
# in case threshold_split < n_pattern; create completely empty columns
min_n_pattern <- stats[, min(n_pattern)]
if(min_n_pattern>threshold_split){
paste0("threshold_split (", threshold_split,") is always smaller then the minimum number of occurances of pattern: (",pattern,"). ",
"Resetting threshold_split to the maximum number of the pattern. ",
"Original threshold_split: (",threshold_split,"). New threshold_split: (",max_n_pattern,")") %>% message_with_lines()
threshold_split <- min_n_pattern
}
# section 3: split the columns ----
datatable_try_later <- datatable %>% copy() %>%
.[n_pattern>threshold_split]
datatable_names <- names(datatable)
string_split_colnames <- paste0("s_",c(1:(threshold_split+1)))
ATTEMPTS <- 5
datatable_split <- NULL
attempt <- 0
while_loop_done <- FALSE
while( (while_loop_done==FALSE) && (attempt <= ATTEMPTS) ) {
message(attempt)
if(while_loop_done==FALSE){
if(attempt < (ATTEMPTS-2)){
threshold_split_out <- threshold_split
string_split_colnames <- paste0("s_",c(1:(threshold_split+1)))
try(
datatable_split <- datatable %>% copy() %>%
.[n_pattern<=threshold_split] %>%
dt_separate(
dt_ = .,
col = string,
into = string_split_colnames,
sep = pattern,
fill = "", fixed = T, remove = F), silent = T
)
}
if(attempt == (ATTEMPTS-2)){
threshold_split_out <- threshold_split -1
string_split_colnames2 <- paste0("s_",c(1:(threshold_split_out+1)))
try(
datatable_split <- datatable %>% copy() %>%
.[n_pattern<=threshold_split] %>%
dt_separate(
dt_ = .,
col = string,
into = string_split_colnames2,
sep = pattern,
fill = "", fixed = T, remove = F),
silent = T
)
}
if(attempt == (ATTEMPTS-1)){
threshold_split_out <- threshold_split + 1
string_split_colnames2 <- paste0("s_",c(1:(threshold_split_out+1)))
try(
datatable_split <- datatable %>% copy() %>%
.[n_pattern<=threshold_split] %>%
dt_separate(
dt_ = .,
col = string,
into = string_split_colnames2,
sep = pattern,
fill = "", fixed = T, remove = F), silent = T
)
}
if(attempt == ATTEMPTS){
# try original again to report crash
threshold_split_out <- threshold_split
string_split_colnames <- paste0("s_",c(1:(threshold_split_out+1)))
try(
datatable_split <- datatable %>% copy() %>%
.[n_pattern<=threshold_split] %>%
dt_separate(
dt_ = .,
col = string,
into = string_split_colnames,
sep = pattern,
fill = "", fixed = T, remove = F)
)
}
}
if(is.null(datatable_split)){
attempt <- attempt + 1
}else{
while_loop_done <- TRUE
}
}
datatable_split_out <- datatable_split %>% copy()
names_datatable_split_out <- names(datatable_split_out)
# section 4.1: create a datatable with all column combinations that are in the data----
possible_columns <- create_unordered_nonrepeating_combinations_dt(max=threshold_split_out+1) %>% copy() %>%
.[, A := paste0("_", A)] %>%
.[, B := paste0("_", B)]
# section 4.2: create all possible combinations in the data ----
for(row in 1:nrow(possible_columns)){
print(row)
stringA <- possible_columns[row] %>% .[, A] %>% paste0("s", .)
stringB <- possible_columns[row] %>% .[, B] %>% paste0("s", .)
stringAB <- possible_columns[row] %>% .[, column]
datatable_split_out <- datatable_split_out %>% copy() %>%
rename_columns(
datatable = .,
current_names = c(stringA, stringB),
new_names = c("stringA", "stringB")
) %>%
.[stringA!=""&stringB!="", stringAB := paste(stringA, stringB, sep=" ")] %>%
.[stringA==""|stringB=="", stringAB := ""] %>%
rename_columns(
datatable = .,
current_names = c("stringA", "stringB", "stringAB"),
new_names = c(stringA, stringB, stringAB)
)
}
# section 5: final details to export ----
# keep these columns
keep_these <- c(id, string, "n_pattern") %>% append(possible_columns[, unique(column)])
# rename columns back
datatable_split_out <- datatable_split_out %>% copy() %>%
rename_columns(
datatable = .,
current_names = c("id", "string"),
new_names = c(id, string)) %>%
.[, ..keep_these]
# return
out <- list()
out$threshold_split_used <- threshold_split_out
out$stats <- stats %>% copy()
out$try_later <- datatable_try_later %>% copy()
out$pairwise_split <- datatable_split_out %>% copy()
num <- out$stats %>% .[n_pattern<=threshold_split_out] %>% .[, sum(N)]
den <- out$stats %>% .[, sum(N)]
paste0((num/den)*100, "% of the observations from the datatable were split due to the threshold_split (",threshold_split_out,") provided.") %>% message_with_lines()
return(out)
}
# Section 2.3 perform the pairwise merge & get appropriate indices ------------
pairwise_merge_indices <- function(datatable_x, id_x, col_x,
datatable_y, id_y, col_y,
by_columns, max_index_cutoff=15){
paste0("This pair-wise merge function (pairwise_merge) does the following:",
"1) It sequentially merges two data-sets datatable_x & datatable_y individually on each one of their columns specified in: by_columns (both data-sets must share the columns).",
"2) For each column pair (e.g. column s_1_2 in x & s_2_1 in y), the function reshapes the datatables into wide format.",
"3) If a specific row has a (max_index_cutoff) > (",max_index_cutoff,"), we disconsider that row to avoid over-matching.",
"4) The final output is in wide format and indicates the indices of both data-sets.")
for(col_x in by_columns) {
paste0("Column from data.table x: (",col_x,")") %>% message_with_lines()
datatable_x_tmp <- datatable_x %>% copy() %>%
rename_columns(
datatable = .,
current_names = c(id_x, col_x),
new_names = c("id_x", "by_col")
) %>%
.[, .(id_x, by_col)] %>%
# drop empty rows
.[!((by_col == "") | (by_col == " ") | (by_col == " "))] %>%
.[, index := 1:.N, by_col] %>%
.[, max_index := max(index, na.rm=T), by_col] %>%
.[, index := paste0("x_",index)]
datatable_x_tmp %>% .[, .N, max_index] %>% .[order(max_index)] %>% print()
paste0("max_index cut-off is: (", max_index_cutoff, ")") %>% message_with_lines()
datatable_x_tmp_wide <- datatable_x_tmp %>% copy() %>%
# variable can't show up to more than 15 unique ids
.[max_index<max_index_cutoff] %>%
.[, max_index := NULL] %>%
dcast(., by_col~index, value.var="id_x", fill = "")
for (col_y in by_columns) {
paste0("Column from data.table y: (",col_y,")") %>% message_with_lines()
datatable_y_tmp <- datatable_y %>%
rename_columns(
datatable = .,
current_names = c(id_y, col_y),
new_names = c("id_y", "by_col")
) %>%
.[, .(id_y, by_col)] %>%
# drop empty rows
.[!((by_col == "") | (by_col == " ") | (by_col == " "))] %>%
.[, index := 1:.N, by_col] %>%
.[, max_index := max(index, na.rm=T), by_col] %>%
.[, index := paste0("y_",index)]
datatable_y_tmp %>% .[, .N, max_index] %>% .[order(max_index)] %>% print()
paste0("max_index cut-off is: (", max_index_cutoff, ")") %>% message_with_lines()
datatable_y_tmp_wide <- datatable_y_tmp %>% copy() %>%
# variable can't show up to more than 15 unique ids
.[max_index<max_index_cutoff] %>%
.[, max_index := NULL] %>%
dcast(., by_col~index, value.var="id_y", fill = "")
merge_tmp <- merge(x = datatable_x_tmp_wide,
y = datatable_y_tmp_wide,
by = "by_col",
all = F) %>%
.[, `:=`(by_x = col_x, by_y = col_y)]
if (col_y == by_columns[1]) {
merge_tmp_out <- merge_tmp %>% copy()
} else{
merge_tmp_out <- merge_tmp %>% copy() %>% rbind(merge_tmp_out, ., fill=T)
}
}
if (col_x == by_columns[1]) {
merge_out <- merge_tmp_out %>% copy()
} else{
merge_out <- merge_tmp_out %>% copy() %>% rbind(merge_out, ., fill=T)
}
}
return(merge_out)
}
# create column pairwise combinations ---------
create_unordered_nonrepeating_combinations_dt <- function(max){
strings <- c(1:(max))
CJ(A= strings, B= strings, sorted = T, unique = T) %>%
.[A!=B] %>%
.[, column := paste0("s","_", A,"_", B)] %>%
.[, sum := A + B] %>%
.[order(sum, A)] %>%
return()
}
# perform the pairwise merge & get appropriate indices ------
merge_on_many_columns_and_produce_links <- function(
datatable_x, id_x, col_x, by_columns_x,
datatable_y, id_y, col_y, by_columns_y,
max_index_cutoff=3){
# delete later
# datatable_x = datatable_x_pairs
# datatable_y = datatable_y_pairs
# id_x = "unique_by_column_id_x"
# id_y = "unique_by_column_id_y"
# col_x = "by_column"
# col_y = "by_column"
# by_columns_x = by_columns_x
# by_columns_y = by_columns_y
# max_index_cutoff = threshold_match_cutoff
message_with_lines("Running function: (merge_on_many_columns_and_produce_links)")
paste0("This pair-wise merge function (pairwise_merge) takes two data-sets & produces a data-set linking matched ids from both.",
"Essentially, it does the following:",
"1) It sequentially merges two data-sets datatable_x & datatable_y individually ",
"on each one of their columns specified in: by_columns_x & by_columns_y. ",
"Since there are (",length(by_columns_x),") columns for x and (",length(by_columns_y),") columns for y, ",
"there will be (",length(by_columns_x)*length(by_columns_x),") merges in total. ",
"2) For each column pair (e.g. column s_1_2 in x & s_2_1 in y), the function reshapes the datatables into wide format.",
"3) If a specific row has a (max_index_cutoff) > (",max_index_cutoff,"), we disconsider that row to avoid over-matching.",
"4) The final output indicates the linked indices for both data-sets & the pair that links them.") %>% message_with_lines()