-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformations.R
1383 lines (911 loc) · 47.3 KB
/
transformations.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
# transformations
#' Equivalise by number of household members.
#'
#'\lifecycle{experimental}
#' Scales a variable dividing it by 'nhhmem'^eq_scale. Where 'nhhmem' is the LIS
#' or LWS variable measuring the number of members in the household.
#'
#' Throws a warning if the function is applied to a person-level variable.
#'
#' @param lissy_files A list of LIS or LWS files
#' @param variable A character vector of length one with the indicator that needs to be transformed.
#' @param eq_scale A real number.
#'
#' @return A list of tibbles with the transformed variable.
#' @example
#' \dontrun{
#' lissy_files <- read_lissy_files(c("fr84h", "fr94h", "fr10h"))
#' transform_equivalise(list_files = lissy_files, variable = "dhi")
#' }
transform_equivalise <- function(lissy_files, variable, eq_scale = 0.5){
copy_attributes <- get_lissy_attributes(lissy_files)
lissy_files <- purrr::imap(.x = lissy_files,
.f = ~implement_equivalise(file = .x,
file_name = .y,
variable = variable,
eq_scale = eq_scale),
variable, eq_scale)
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' Apply equivalise by number of household members
#'
#'\lifecycle{experimental}
#' Applies the equivalisation by number of household members in a file for a single variable.
#'
#' To be used inside transform_equivalise().
#'
#' @param file A LIS or LWS file.
#' @param file_name The name of the LIS or LWS file.
#' @param variable A string with the variable to which equivalisation should be applied.
#' @param eq_scale A real number. Defaults to 0.5. The variable will be equivalized using n_household_members^eq_scale
#' @return A a file with the equivalised variable.
#'
#' @keywords internal
implement_equivalise <- function(file, file_name, variable, eq_scale = 0.5){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
if (variable %in% c(lissyrtools::lis_person_variables,
lissyrtools::lws_person_variables,
lissyrtools::erflis_person_variables) ){
# warning if variable is person-level
warning(glue::glue("'{variable}' is a person-level variable and might not need to be equivalised!"))
}
assertthat::assert_that("nhhmem" %in% names(file),
msg = glue::glue("'nhhmem' could not be found in '{file_name}'."))
if(!is.all.na.or.zero(file[[variable]])){
file[[variable]] <- file[[variable]]/(file[["nhhmem"]]^eq_scale)
}
return(file)
}
#' Equivalise with the OECD scale
#'
#'\lifecycle{experimental}
#' Scales a variable using a weight for the adults (excluding the first one) and
#' children.
#'
#' Throws a warning if the function is applied to a person-level variable.
#'
#' @param lissy_files A list of LIS or LWS files
#' @param variable A character vector of length one with the indicator that needs to be transformed.
#' @param value_other_adults A real number. Defaults to 0.7. The value assigned to the
#' second to last adults in the household.
#' @param value_children A real number. Defaults to 0.7. The value assigned to children
#' in the household.
#'
#' @return A list of tibbles with the transformed variable.
#' @example
#' \dontrun{
#' lissy_files <- read_lissy_files(c("fr84h", "fr94h", "fr10h"))
#' transform_equivalise_oecd(list_files = lissy_files, variable = "dhi")
#' }
transform_equivalise_oecd <- function(lissy_files, variable, value_other_adults = 0.7, value_children = 0.5){
copy_attributes <- get_lissy_attributes(lissy_files)
lissy_files <- purrr::imap(.x = lissy_files,
.f = ~implement_equivalise_oecd(file = .x,
file_name = .y,
variable = variable,
value_other_adults = value_other_adults,
value_children = value_children),
variable, eq_scale)
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' Apply equivalise with the OECD scale
#'
#'\lifecycle{experimental}
#' Applies the equivalisation by number of adults and children in a household.
#'
#' To be used inside transform_equivalise_oecd().
#'
#' @param file A LIS or LWS file.
#' @param file_name The name of the LIS or LWS file.
#' @param variable A string with the variable to which equivalisation should be applied.
#' @param value_other_adults A real number. Defaults to 0.7. The value assigned to the
#' second to last adults in the household.
#' @param value_children A real number. Defaults to 0.7. The value assigned to children
#' in the household.
#'
#' @return A a file with the equivalised variable.
#'
#' @keywords internal
implement_equivalise_oecd <- function(file, file_name, variable, value_other_adults = 0.7, value_children = 0.5){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
if (variable %in% c(lissyrtools::lis_person_variables,
lissyrtools::lws_person_variables,
lissyrtools::erflis_person_variables) ){
# warning if variable is person-level
warning(glue::glue("'{variable}' is a person-level variable and might not need to be equivalised!"))
}
assertthat::assert_that(all(c("nhhmem", "nhhmem13") %in% names(file)),
msg = glue::glue("'nhhmem' and 'nhhmem13' need to be in '{file_name}'."))
if(!is.all.na.or.zero(file[[variable]])){
n_other_adults <- file[["nhhmem"]] - file[["nhhmem13"]] - 1
factor <- 1 + value_other_adults* n_other_adults + file[["nhhmem13"]] * value_children
file[[variable]] <- file[[variable]]/(factor)
}
return(file)
}
#' Recodes zeros into missing values
#'
#'\lifecycle{experimental}
#' Recodes all zeros in the selected variable into missing valuse (NAs).
#'
#' @param lissy_files A list of LIS or LWS files.
#' @param variable A character string with the name of the variable that should be adjusted
#' @return A list of tibbles with the adjusted variable.
transform_zeros_to_na <- function(lissy_files, variable){
copy_attributes <- get_lissy_attributes(lissy_files)
lissy_files <- purrr::imap(.x = lissy_files,
.f = ~implement_zeros_to_na(file = .x,
file_name = .y,
variable),
variable)
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' Apply recoding of zeros into missing values
#'
#'\lifecycle{experimental}
#' Applies the recoding of zeroes into missing values in a file for a single variable.
#'
#' To be used inside transform_zeros_to_na().
#'
#' @param file A LIS or LWS file.
#' @param file_name The name of the LIS or LWS file
#' @param variable A string with the variable to which recoding should be applied.
#' @return A file with the recoded variable.
#'
#' @keywords internal
implement_zeros_to_na <- function(file, file_name, variable){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
if( !all(is.na(file[[variable]])) ){
index_zero <- file[[variable]] == 0 & !is.na(file[[variable]])
file[index_zero, variable] <- NA
}
return(file)
}
#' Adjust aggregates by LIS PPPs
#'
#'\lifecycle{experimental}
#'
#' @description
#' Adjusts an aggregate by both the CPI and PPP.
#'
#' For LWS income variables, it takes into account the reference year of the dataset variables.
#'
#' @param lissy_files A list of LIS or LWS files.
#' @param variable A character string with the name of the variable that should be adjusted.
#' @param database 'lis' or 'lws' to specify which database the files belong to. If NULL (default)
#' the function reads the 'database' attribute from the list in 'lissy_files'.
#' @param path_to_ppp_file A character string indicating where the deflator values
#' can be found. If the value is 'lissyrtools' (default), it will import the data from 'lissyrtools'.
#' These values are equivalent to the ones in: datacenter.org/resources/ppp-deflators/ .
#' Specifying 'lissy' will read them from within the LISSY directory. Any other
#' value requires the full path specification to the deflators file.
#' @param income_variable It is only relevant for LWS files. If the file is
#' LWS and 'income_variable = TRUE', the function will retrieve the deflator for
#' the year in which the income data was collected.
#' This reference year might or might not be the same as the one when the wealth
#' information was collected (i.e. the year of the file - 2010 for 'fr10wh').
#' The default NULL checks the name of the variable against the name of the income
#' variables in LWS files. A vector containing the list of these can be found
#' in lissyrtools::lws_income_variables. Setting the argument to FALSE forces the adjustment
#' to use the same year as the year of the file regardless of the value passed to 'variable'.
#' @return A list of tibbles with the adjusted variable.
#'
#' @example
#' \dontrun{
#' library(dplyr)
#' library(magrittr)
#' lissy_files <- read_lissy_files(c("fr84h", "fr94h", "fr10h"))
#' lissy_files %<>%
#' transform_adjust_by_lisppp(variable = "dhi")
#'}
transform_adjust_by_lisppp <- function(lissy_files, variable, database = NULL, income_variable = NULL, path_to_ppp_file = "lissyrtools"){
if(missing(database)){
database_ <- get_database(lissy_files)
}else{
database_ <- database
}
assertthat::assert_that(database_ %in% c('lis', 'lws', 'erflis', 'i', 'w', 'e'),
msg = glue::glue("Only 'lis', 'lws', 'erflis', 'i', 'w' and 'e' are valid values for databases. Got '{database_}'."))
copy_attributes <- get_lissy_attributes(lissy_files)
lissy_files <- purrr::imap(.x = lissy_files,
.f = function(file, file_name, database, variable, income_variable, ppp_data){
implement_adjust_by_lisppp(file,
file_name,
database = database,
variable = variable,
income_variable = income_variable,
ppp_data = ppp_data)
},
database_,
variable,
income_variable,
ppp_data = import_lisppp_data(path_to_ppp_file))
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' Applies the deflator adjustment to an aggregate
#'
#' \lifecycle{experimental}
#'
#' To be used inside transform_adjust_by_lisppp().
#'
#' @param file A list of LIS or LWS file
#' @param file_name The name of the LIS or LWS file.
#' @param variable A string with the name of the variable to which the adjustment should be applied.
#' @param income_variable Defaults to NULL. Is only relevant for LWS files. If the file is
#' LWS and 'income_variable = TRUE', the function will retrieve the deflator for
#' the year in which the income data was collected. This might not be the same
#' as the year when wealth variables were collected.
#' @param ppp_data An optional file with the deflators. Should be in the same
#' format as the tibble in 'lissyrtools::deflators'. If "lissyrtools" (default) the deflators
#' are imported from the package internal data.
#'
#'
#' @keywords internal
implement_adjust_by_lisppp <- function(file, file_name, database, variable, income_variable = NULL, ppp_data = "lissyrtools"){
assertthat::assert_that(database %in% c('lis', 'lws', 'erflis', 'i', 'w', 'e'),
msg = "Incorrect value in 'database' argument.")
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
if(!is.all.na.or.zero(file[[variable]])){
ccyy_format_bool <- stringr::str_detect(file_name, pattern = "^\\w{2}\\d{2}$")
if(!ccyy_format_bool){
file_name <- change_file_name_format(file_name, to_format = 'ccyy')
}
lisppp <- get_file_lisppp(file_name = file_name, database, variable, income_variable = income_variable, ppp_data = ppp_data)
file[[variable]] <- file[[variable]] / lisppp
}
return(file)
}
#' Recode negative values to zero
#'
#' \lifecycle{experimental}
#' Recodes all negative values to zero for all files in a list.
#'
#' @param lissy_files A list of LIS or LWS files.
#' @param variable A character string with the name of the variable that should be transformed.
#' @return A list of tibbles with the recoded variable.
#'
#' @examples
#' \dontrun{
#' library(dplyr)
#' library(magrittr)
#' lissy_files <- read_lissy_files(c("fr84h", "fr94h", "fr10h"))
#' lissy_files %<>%
#' transform_negative_values_to_zero(variable = "dhi")
#' }
transform_negative_values_to_zero <- function(lissy_files, variable){
copy_attributes <- get_lissy_attributes(lissy_files)
lissy_files <- purrr::imap(.x = lissy_files,
.f = function(file, file_name, variable){
implement_negative_values_to_zero(file, file_name, variable)
},
variable
)
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' Apply recoding negative values to zero
#'
#'\lifecycle{experimental}
#' Applies the recoding of negative values into zeroes in a variable of a single file.
#'
#' To be used inside transform_negative_values_to_zero().
#'
#' @param file A LIS or LWS file.
#' @param file_name The name of the LIS or LWS file
#' @param variable A string with the variable to which recoding should be applied.
#' @return A file with the recoded variable.
#'
#' @keywords internal
implement_negative_values_to_zero <- function(file, file_name, variable){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
file[[variable]] <- dplyr::if_else((file[[variable]]< 0) & !is.na(file[[variable]]),
true = 0,
false = as.numeric(file[[variable]]))
return(file)
}
#' Apply top or bottom coding with log IQR
#'
#'\lifecycle{experimental}
#' Applies an upper or lower limit on variable values using the Interquartile Range (IQR)
#' of the variable transformed with the natural logarithm and a scale factor
#' ('times').
#'
#' If the lissy files passed are at person-level and the variable is household-level,
#' only household heads are used to compute the IQR of the log transformed variable.
#' For person-level variables, all individuals in the file are used.
#'
#' @param lissy_files A list of LIS or LWS files.
#' @param variable A character string with the name of the variable that should be transformed.
#' @param times A numeric indicating the scale factor for IQR. Defaults to 3.
#' @param files_level A string indicating the level of the file. Valid inputs are:
#' 'household', 'h', 'person' or 'p'. If NULL (default), the file level will
#' be retrived from the 'lissy_files' attributes.
#' @param variable_level Level of the variable. Should be either 'household', 'h', 'person' or 'p'.
#' If NULL (default), the function will try to guess the level of the variable.
#' This is done by comparing the value in 'variable' with pre-set lists of variables.
#' @param weight A string with the name of the variable in 'file' that should be
#' used as sample weights.
#' @return A list of tibbles with the recoded variable.
transform_top_code_with_iqr <- function(lissy_files, variable, times = 3, files_level = NULL, variable_level = NULL, weight = NULL){
copy_attributes <- get_lissy_attributes(lissy_files)
if(missing(files_level)){
level_ <- copy_attributes[["level"]]
}else{
level_ <- files_level
}
assertthat::assert_that(!is.null(level_),
msg = "'lissy_files' should have a 'level' attribute or this should be specified in 'files_level' argument.")
lissy_files <- purrr::imap(.x = lissy_files,
.f = ~implement_top_code_with_iqr(file = ..1,
file_name = ..2,
variable = ..3,
times = ..4,
file_level = ..5,
variable_level = ..6,
weight = ..7 )
,variable, times, level_, variable_level, weight
)
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' Apply top or bottom coding with log IQR to a single file
#'
#'\lifecycle{experimental}
#' Applies an upper or lower limit on variable values using the Interquartile Range (IQR)
#' of the variable transformed with the natural logarithm and a scale factor
#' ('times'). For 'household level' variables, the IQR of the log transformed variable is computed using only
#' household heads. For 'person level' variables, all individuals in the file are used.
#'
#' To be used inside transform_top_code_with_iqr() and transform_bottom_code_with_iqr() .
#'
#' @param file A LIS or LWS file.
#' @param file_name A string with the name of the LIS or LWS file.
#' @param variable A string with the variable to which top coding should be applied.
#' @param times A numeric indicating the scale factor for IQR. Defaults to 3.
#' @param file_level A string indicating the level of the file. Valid inputs are:
#' 'household', 'h', 'person' or 'p'.
#' @param variable_level A string with the level of the variable. Should be either 'household' or 'person'.
#' If NULL (default), the function will try to guess the level of the variable.
#' This is done by comparing the value in 'variable' with pre-set lists of variables.
#' @param weight A string with the name of the variable in 'file' that should be
#' used as sample weights.
#'
#' @return A tibble containing the file with the recoded variable.
#'
#' @keywords internal
implement_top_code_with_iqr <- function(file, file_name, variable, times, file_level, variable_level = NULL, weight = NULL){
assertthat::assert_that(file_level %in% c("person", "household", "p", "h"),
msg = "Argument 'file_level' in can only take 'person', 'p', 'household' or 'h' as values.")
if(file_level %in% c("household", "h")){
assertthat::assert_that( is.null(variable_level) || variable_level %in% c("household", "h"),
msg = glue::glue("Household-level files such as '{file_name}' should only have household-level variables. Variable '{variable}' was specified as person-level."))
}
if(file_level %in% c("person", "p")){
implement_top_code_with_iqr_pfile(file, file_name, variable, times, variable_level, weight)
}else{
implement_top_code_with_iqr_hfile(file, file_name, variable, times, weight)
}
}
#' Apply top and bottom coding with log IQR to a level-defined file
#'
#' Lower-level functions used within 'implement_top_code_with_iqr()' and
#' 'implement_bottom_code_with_iqr()'.
#'
#' @param file A tibble or data.frame with a LIS or LWS file.
#' @param file_name A string with the name of the LIS or LWS file.
#' @param variable A string with the variable to which top coding should be applied.
#' @param times A numeric indicating the scale factor for IQR. Defaults to 3.
#' @param variable_level A string with the level of the variable. Should be either 'household' or 'person'.
#' If NULL (default), the function will try to guess the level of the variable.
#' This is done by comparing the value in 'variable' with pre-set lists of variables.
#' @param weight A string with the name of the variable in 'file' that should be
#' used as sample weights.
#'
#' @return A tibble containing the file with the recoded variable.
#'
#' @keywords internal
implement_top_code_with_iqr_pfile <- function(file, file_name, variable, times = 3, variable_level = NULL, weight = NULL){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
var_ <- file[[variable]]
if(!is.all.na.or.zero(var_)){
if(is.null(variable_level)){
variable_level <- check_variable_level(variable)
}else{
assertthat::assert_that(variable_level %in% c("person", "household", "p", "h"),
msg = "Argument 'variable_level' can only take 'person', 'p', 'household' or 'h' as values.")
}
if(is.null(weight) & variable_level %in% c("person", "p")){
weight_var <- "pwgt"
}else if(is.null(weight) & variable_level %in% c("household", "h")){
weight_var <- "hwgt"
}else{
weight_var <- weight
}
assertthat::assert_that(all(var_ >= 0 | is.na(var_)),
msg = glue::glue("Error in '{file_name}'. The variable where top coding with log IQR is applied can not have negative values."))
assertthat::assert_that(weight_var %in% names(file),
msg = glue::glue("'{weight_var}' could not be found in '{file_name}'."))
if(variable_level %in% c("household", "h")){
assertthat::assert_that("relation" %in% names(file),
msg = glue::glue("'relation' could not be found in '{file_name}'."))
missing_values_in_variable_warning(file = file,
file_name = file_name,
variable = "relation")
}
missing_values_in_variable_warning(file = file,
file_name = file_name,
variable = weight_var)
log_var <- dplyr::if_else(var_ > 0,
true = log(var_),
false = 0,
missing = NA_real_)
index_valid_weights <- !is.na(file[[weight_var]]) # this shouldn't be happening, but it happens for some LIS and LWS Japan files
if(variable_level == "household"){
index_hh_head <- get_index_hh_heads(file)
log_var_for_iqr_computation <- log_var[index_valid_weights & index_hh_head]
weights_for_iqr_computation <- file[index_valid_weights & index_hh_head, weight_var, drop = TRUE]
}else{
log_var_for_iqr_computation <- log_var[index_valid_weights]
weights_for_iqr_computation <- file[index_valid_weights, weight_var, drop = TRUE]
}
if(!is.all.na.or.zero(log_var_for_iqr_computation)){
log_third_quartile <- unname(wtd.quantile(log_var_for_iqr_computation,
weights = weights_for_iqr_computation,
probs = 0.75))
log_first_quartile <- unname(wtd.quantile(log_var_for_iqr_computation,
weights = weights_for_iqr_computation,
probs = 0.25))
log_times_iqr <- (log_third_quartile - log_first_quartile) * times
var_ <- dplyr::if_else(log(var_) > (log_third_quartile + log_times_iqr),
true = exp(log_third_quartile + log_times_iqr),
false = var_)
}
file[[variable]] <- var_
}
return(file)
}
#' @rdname implement_top_code_with_iqr_pfile
implement_top_code_with_iqr_hfile <- function(file, file_name, variable, times = 3, weight = NULL){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
var_ <- file[[variable]]
# throw warning if variable_level not "household"
if(!is.all.na.or.zero(var_)){
safe_variable_level <- safely_check_variable_level(variable)
if(!is.null(safe_variable_level[["result"]]) &&
safe_variable_level[["result"]] %in% c("person", "p") ){
warning(glue::glue("The variable '{variable}' is at person-level and the file '{file_name}' is at household-level. The methods used to top code might not be correct."))
}
if(is.null(weight)){
weight_var <- "hwgt"
}else{
weight_var <- weight
}
assertthat::assert_that(all(var_ >= 0 | is.na(var_)),
msg = glue::glue("Error in '{file_name}'. The variable where top coding with log IQR is applied can not have negative values."))
assertthat::assert_that(weight_var %in% names(file),
msg = glue::glue("'{weight_var}' could not be found in '{file_name}'."))
missing_values_in_variable_warning(file = file,
file_name = file_name,
variable = weight_var)
log_var <- dplyr::if_else(var_ > 0,
true = log(var_),
false = 0,
missing = NA_real_)
index_valid_weights <- !is.na(file[[weight_var]]) # this shouldn't be happening, but it happens for some LIS and LWS Japan files
log_var_for_iqr_computation <- log_var[index_valid_weights]
weights_for_iqr_computation <- file[index_valid_weights, weight_var, drop = TRUE]
if(!is.all.na.or.zero(log_var_for_iqr_computation)){
log_third_quartile <- unname(wtd.quantile(log_var_for_iqr_computation,
weights = weights_for_iqr_computation,
probs = 0.75))
log_first_quartile <- unname(wtd.quantile(log_var_for_iqr_computation,
weights = weights_for_iqr_computation,
probs = 0.25))
log_times_iqr <- (log_third_quartile - log_first_quartile) * times
var_ <- dplyr::if_else(log(var_) > (log_third_quartile + log_times_iqr),
true = exp(log_third_quartile + log_times_iqr),
false = var_)
}
file[[variable]] <- var_
}
return(file)
}
#' @rdname transform_top_code_with_iqr
transform_bottom_code_with_iqr <- function(lissy_files, variable, times = 3, files_level = NULL, variable_level = NULL, weight = NULL){
copy_attributes <- get_lissy_attributes(lissy_files)
if(missing(files_level)){
level_ <- copy_attributes[["level"]]
}else{
level_ <- files_level
}
assertthat::assert_that(!is.null(level_),
msg = "'lissy_files' should have a 'level' attribute or this should be specified in 'files_level' argument.")
lissy_files <- purrr::imap(.x = lissy_files,
.f = ~implement_bottom_code_with_iqr(file = ..1,
file_name = ..2,
variable = ..3,
times = ..4,
file_level = ..5,
variable_level = ..6,
weight = ..7 )
,variable, times, level_, variable_level, weight
)
lissy_files <- paste_lissy_attributes(lissy_files, copy_attributes)
return(lissy_files)
}
#' @rdname implement_top_code_with_iqr
implement_bottom_code_with_iqr <- function(file, file_name, variable, times, file_level, variable_level = NULL, weight = NULL){
assertthat::assert_that(file_level %in% c("person", "household", "p", "h"),
msg = "Argument 'file_level' in can only take 'person', 'p', 'household' or 'h' as values.")
if(file_level %in% c("household", "h")){
assertthat::assert_that( is.null(variable_level) || variable_level %in% c("household", "h"),
msg = glue::glue("Household-level files such as '{file_name}' should only have household-level variables. Variable '{variable}' was specified as person-level."))
}
if(file_level %in% c("person", "p")){
implement_bottom_code_with_iqr_pfile(file, file_name, variable, times, variable_level, weight)
}else{
implement_bottom_code_with_iqr_hfile(file, file_name, variable, times, weight)
}
}
#' @rdname implement_top_code_with_iqr_pfile
implement_bottom_code_with_iqr_pfile <- function(file, file_name, variable, times = 3, variable_level = NULL, weight = NULL){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
var_ <- file[[variable]]
if(!is.all.na.or.zero(var_)){
if(is.null(variable_level)){
variable_level <- check_variable_level(variable)
}else{
assertthat::assert_that(variable_level %in% c("person", "household", "p", "h"),
msg = "Argument 'variable_level' can only take 'person', 'p', 'household' or 'h' as values.")
}
if(is.null(weight) & variable_level %in% c("person", "p")){
weight_var <- "pwgt"
}else if(is.null(weight) & variable_level %in% c("household", "h")){
weight_var <- "hwgt"
}else{
weight_var <- weight
}
assertthat::assert_that(all(var_ >= 0 | is.na(var_)),
msg = glue::glue("Error in '{file_name}'. The variable where top coding with log IQR is applied can not have negative values."))
assertthat::assert_that(weight_var %in% names(file),
msg = glue::glue("'{weight_var}' could not be found in '{file_name}'."))
if(variable_level %in% c("household", "h")){
assertthat::assert_that("relation" %in% names(file),
msg = glue::glue("'relation' could not be found in '{file_name}'."))
missing_values_in_variable_warning(file = file,
file_name = file_name,
variable = "relation")
}
missing_values_in_variable_warning(file = file,
file_name = file_name,
variable = weight_var)
log_var <- dplyr::if_else(var_ > 0,
true = log(var_),
false = 0,
missing = NA_real_)
index_valid_weights <- !is.na(file[[weight_var]]) # this shouldn't be happening, but it happens for some LIS and LWS Japan files
if(variable_level == "household"){
index_hh_head <- get_index_hh_heads(file)
log_var_for_iqr_computation <- log_var[index_valid_weights & index_hh_head]
weights_for_iqr_computation <- file[index_valid_weights & index_hh_head, weight_var, drop = TRUE]
}else{
log_var_for_iqr_computation <- log_var[index_valid_weights]
weights_for_iqr_computation <- file[index_valid_weights, weight_var, drop = TRUE]
}
if(!is.all.na.or.zero(log_var_for_iqr_computation)){
log_third_quartile <- unname(wtd.quantile(log_var_for_iqr_computation,
weights = weights_for_iqr_computation,
probs = 0.75))
log_first_quartile <- unname(wtd.quantile(log_var_for_iqr_computation,
weights = weights_for_iqr_computation,
probs = 0.25))
log_times_iqr <- (log_third_quartile - log_first_quartile) * times
if( (log_first_quartile - log_times_iqr) <= 0){
# don't recode 0s to bottom code
# (var_ != 0) is needed, else it is replaced with log(0) = -Inf
var_ <- dplyr::if_else((var_ != 0) & (log(var_) < (log_first_quartile - log_times_iqr)),
true = exp(log_first_quartile - log_times_iqr),
false = var_)
}else{
# recode 0s to bottom code
var_ <- dplyr::if_else( (log(var_) < (log_first_quartile - log_times_iqr)),
true = exp(log_first_quartile - log_times_iqr),
false = var_)
}
}
file[[variable]] <- var_
}
return(file)
}
#' @rdname implement_top_code_with_iqr_pfile
implement_bottom_code_with_iqr_hfile <- function(file, file_name, variable, times = 3, weight = NULL){
assertthat::assert_that(variable %in% names(file),
msg = glue::glue("Variable '{variable}' could not be found in '{file_name}'."))
var_ <- file[[variable]]
# throw warning if variable_level not "household"
if(!is.all.na.or.zero(var_)){
safe_variable_level <- safely_check_variable_level(variable)
if(!is.null(safe_variable_level[["result"]]) &&
safe_variable_level[["result"]] %in% c("person", "p") ){
warning(glue::glue("The variable '{variable}' is at person-level and the file '{file_name}' is at household-level. The methods used to top code might not be correct."))
}
if(is.null(weight)){
weight_var <- "hwgt"
}else{
weight_var <- weight
}
assertthat::assert_that(all(var_ >= 0 | is.na(var_)),
msg = glue::glue("Error in '{file_name}'. The variable where top coding with log IQR is applied can not have negative values."))
assertthat::assert_that(weight_var %in% names(file),
msg = glue::glue("'{weight_var}' could not be found in '{file_name}'."))
missing_values_in_variable_warning(file = file,
file_name = file_name,