-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path20151027examples3.Rmd
1666 lines (1382 loc) · 65.9 KB
/
20151027examples3.Rmd
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: "Examples for guide"
author: "Thijs"
date: "27 oktober 2015"
output: word_document
---
----------------------------------------------------
```{r, include = TRUE}
library(sdcMicro)
# Set up dataset
data4 <- as.data.frame(cbind(as.factor(c('Urban', 'Urban', 'Urban', 'Urban', 'Rural', 'Urban', 'Urban', 'Urban', 'Urban', 'Urban')),
as.factor(c('Female', 'Female', 'Female', 'Male', 'Female', 'Male', 'Female', 'Male', 'Female', 'Female')),
as.factor(c('Sec in', 'Sec in', 'Prim in', 'Sec com', 'Sec com', 'Sec com', 'Prim com', 'Post-sec', 'Sec in', 'Sec in')),
as.factor(c('Emp', 'Emp', 'Non-LF', 'Emp', 'Unemp', 'Emp', 'Non-LF', 'Unemp', 'Non-LF','Non-LF')),
as.factor(c('yes', 'yes', 'yes', 'yes','yes', 'no', 'no', 'yes', 'no', 'yes')),
c(180, 180, 215, 76, 186, 76, 180, 215, 186, 76)
))
names(data4) <- c('Residence', 'Gender', 'Educ', 'Lstat', 'Health', 'Weights')
sdcInitial <- createSdcObj(dat = data4, keyVars = c('Residence', 'Gender', 'Educ', 'Lstat'), weightVar = 'Weights')
k=3
```
Example 4.1: Calculating f_k using sdcMicro
----------------------------------------------------
```{r}
# Frequency of the particular combination of key variables (keys) in the sample
freq(sdcInitial, type = 'fk')
```
Example 4.2: Calculating the sample and population frequencies using sdcMicro
----------------------------------------------------
```{r, results="hide"}
# Sample frequency of individual's key
freq(sdcInitial, type = 'fk')
# Population frequency of individual's key
freq(sdcInitial, type = 'Fk')
```
Example 4.3: The individual risk slot within the sdcMicro object
----------------------------------------------------
```{r}
sdcInitial@risk$individual
```
----------------------------------------------------
```{r, include = FALSE}
sdcInitial <- localSuppression(sdcInitial, k = 1)
```
Example 4.4: Using the print() function to display observations violating k-anonymity
----------------------------------------------------
```{r}
print(sdcInitial, 'kAnon')
```
Example 4.5: Computing k-anonymity violations for other values of k
----------------------------------------------------
```{r}
k=3
sum(sdcInitial@risk$individual[,2] < k)
```
Example 4.6: l-diversity function in sdcMicro
----------------------------------------------------
```{r}
# Computing l-diversity
sdcInitial <- ldiversity(obj = sdcInitial, ldiv_index = c("Health"), l_recurs_c = 2, missing = NA)
# Output for l-diversity
sdcInitial@risk$ldiversity
```
Example 4.7: Evaluating SUDA Scores for specified variables
----------------------------------------------------
```{r}
# Evaluating SUDA scores for the specified variables
sdcInitial <- suda2(obj = sdcInitial, missing = NA)
# The results are saved in the risk slot of the sdcMicro object
# SUDA scores
sdcInitial@risk$suda2$score
# DIS-SUDA scores
sdcInitial@risk$suda2$disScore
# Summary of DIS-SUDA scores
sdcInitial@risk$suda2
```
Example 4.8: Histogram and density plots of DIS-SUDA scores
----------------------------------------------------
```{r, results='hide'}
# Plot a histogram of disScore
hist(sdcInitial@risk$suda2$disScore, main = 'Histogram of DIS-SUDA scores')
# Density plot
density <- density(sdcInitial@risk$suda2$disScore)
plot(density, main = 'Density plot of DIS-SUDA scores')
```
```{r, include = FALSE}
# Set up dataset
file <- as.data.frame(cbind(c(100, 150, 200), c(1,3,2)))
names(file) <- c('income', 'income2')
sdcObj <- createSdcObj(dat = file, keyVars =c('income', 'income2'), numVars = c('income', 'income2'))
compExp <- c('income', 'income2')
sdcObj@manipNumVars[,'income'] <- c(100, 200, 290)
```
Example 4.9: Example with the function dRisk()
----------------------------------------------------
```{r}
dRisk(obj = sdcObj@origData[,compExp], xm = sdcObj@manipNumVars[,compExp], k = 0.1)
```
Example 4.10: Computing 90 % quantile of variable income
----------------------------------------------------
```{r, results = 'hide'}
# Compute the 90 % quantile for the variable income
quant90 <- quantile(file[,'income'], 0.90, na.rm = TRUE)
# Show the ID of observations with values for income larger than the 90 % quantile
file[(file[, 'income'] >= quant90), 'ID']
```
Example 4.11: Computation of individual risk measures
----------------------------------------------------
```{r}
# Global risk (average reidentification probability)
sdcInitial@risk$global$risk
```
Example 4.12: Computation of expected number of re-identifications
----------------------------------------------------
```{r}
# Global risk (expected number of reidentifications)
sdcInitial@risk$global$risk_ER
```
Example 4.13: Number of individuals with individual risk higher than the threshold 0.05
----------------------------------------------------
```{r}
sum(sdcInitial@risk$individual[,1] >= 0.05)
```
Example 4.14: Computation of household risk and expected number of re-identifications
----------------------------------------------------
```{r, results = 'hide'}
# Household risk
sdcInitial@risk$global$hier_risk
# Household risk (expected number of reidentifications
sdcInitial@risk$global$hier_risk_ER
```
```{r, include = FALSE}
rm(list = ls())
library(sdcMicro)
library(foreign)
fname <- "/Users/thijsbenschop/Copy/World Bank/DHS/Complete/KAZ_1999_DHS_v01_M_subset.dta"
file51 <- read.dta(fname, missing.type = TRUE, convert.factors = TRUE)
file51 <- file51[1:2500,]
names(file51)[which(names(file51) == "HV026")] <- "sizeRes"
names(file51)[which(names(file51) == "HV105")] <- "age"
names(file51)[which(names(file51) == "HV104")] <- "gender"
names(file51)[which(names(file51) == "HV023")] <- "region"
names(file51)[which(names(file51) == "HV003")] <- "ethnicity"
sdcInitial <- createSdcObj(dat = file51, keyVars = c('sizeRes', 'age', 'gender', 'region', 'ethnicity'))
sdcInitialCopy <- sdcInitial
```
Example 5.1: Using the sdcMicro function groupVars() to recode a categorical variable
----------------------------------------------------
```{r}
table(sdcInitial@manipKeyVars$sizeRes)
sdcInitial <- groupVars(obj = sdcInitial, var = c("sizeRes"), before = c("capital, large city", "small city", "town"), after = c("urban", "urban", "urban"))
sdcInitial <- groupVars(obj = sdcInitial, var = c("sizeRes"), before = c("countryside"), after = c("rural"))
table(sdcInitial@manipKeyVars$sizeRes)
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.2: Using the sdcMicro function globalRecode to recode a continuous variable (age)
----------------------------------------------------
```{r}
sdcInitial <- globalRecode(sdcInitial, column = c('age'), breaks = 10 * c(0:10))
table(sdcInitial@manipKeyVars$age)
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.3: Using globalRecode() to create intervals of unequal width
----------------------------------------------------
```{r}
sdcInitial <- globalRecode(sdcInitial, column = c('age'), breaks = c(0, 5, 11, 17, 21, 25, 49, 65, 100))
table(sdcInitial@manipKeyVars$age)
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.4: Constructing right-open intervals for semi-continuous variables using built-in sdcMicro function globalRecode()
----------------------------------------------------
```{r, results='hide'}
sdcInitial <- globalRecode(sdcInitial, column = c('age'), breaks = c(-0.1, 14.9, 65.9, 99.9), labels = c('[0,14)', '[15,65)', '[66,100)'))
table(sdcInitial@manipKeyVars$age)
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.6: Constructing intervals for semi continuous and continuous variables using manual recoding in R
----------------------------------------------------
```{r, results='hide'}
sdcInitial@manipKeyVars$age[sdcInitial@manipKeyVars$age >= 0 &
sdcInitial@manipKeyVars$age < 15] <- 0
sdcInitial@manipKeyVars$age[sdcInitial@manipKeyVars$age >= 15 &
sdcInitial@manipKeyVars$age < 66] <- 1
sdcInitial@manipKeyVars$age[sdcInitial@manipKeyVars$age >= 66 &
sdcInitial@manipKeyVars$age <= 100] <- 2
# Add labels for the new values
sdcInitial@manipKeyVars$age <-ordered(sdcInitial@manipKeyVars$age,
levels = c(0,1,2), labels = c("0-14", "15-65", "66-100"))
# Recalculate risk after manual manipulation
sdcInitial <- calcRisks(sdcInitial)
table(sdcInitial@manipKeyVars$age)
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.7: Top coding and bottom coding in sdcMicro using topBotCoding() function
----------------------------------------------------
```{r, results='hide'}
#top coding
sdcInitial <- topBotCoding(obj = sdcInitial, value = 65, replacement = 65, kind = 'top', column = 'age')
#bottom coding
sdcInitial <- topBotCoding(obj = sdcInitial, value = 5, replacement = 5, kind = 'bottom', column = 'age')
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
#rm(list=ls())
```
Example 5.8: Application of local suppression with and without importance vector
----------------------------------------------------
```{r, error=TRUE}
# local suppression without importance vector
sdcInitial <- localSuppression(sdcInitial, k=5)
print(sdcInitial, 'ls')
##
## gender ....... 0 [ 0 %]
##
## region ....... 0 [ 0 %]
##
## religion ..... 0 [ 0 %]
##
## age .......... 161 [ 1.422 %]
##
## ethnicity..... 0 [ 0 %]
# Undoing the supressions
sdcInitial <- undolast(sdcInitial)
# Local suppression with importance vector to avoid suppressions in the first (gender) and fourth (age) variables
sdcInitial <- localSuppression(sdcInitial, importance = c(5, 1, 1, 5, 5), k = 5)
print(sdcInitial, 'ls')
##
## gender ....... 2 [ 0.018 %]
##
## region ....... 260 [ 2.296 %]
##
## religion ..... 25 [ 0.221 %]
##
## age .......... 0 [ 0 %]
##
## ethnicity..... 8 [ 0.071 %]
```
```{r, include=FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.9: Application of built-in sdcMicro function localSupp()
----------------------------------------------------
```{r, error=TRUE}
# Summary statistics
summary(sdcInitial@risk$individual[,1])
# Number of individuals with individual risk higher than 0.1
sum(sdcInitial@risk$individual[,1] > 0.1)
# local suppression
localSupp(sdcInitial, threshold = 0.1, keyVar = 'ethnicity')
```
```{r, include=FALSE}
#rm(list = ls())
library(sdcMicro)
library(foreign)
fname <- "/Users/thijsbenschop/Copy/World Bank/Guidelines/Case studies/caseA.dta"
file <- read.dta(fname, missing.type = TRUE, convert.factors = TRUE)
selectedKeyVarsHH = c('URBRUR', 'REGION', 'HHSIZE', 'OWNAGLAND', 'RELIG')
file$URBRUR <- as.factor(file$URBRUR)
file$REGION <- as.factor(file$REGION)
file$OWNHOUSE <- as.factor(file$OWNHOUSE)
file$OWNAGLAND <- as.factor(file$OWNAGLAND)
file$RELIG <- as.factor(file$RELIG)
numVarsHH = c('LANDSIZEHA', 'TANHHEXP', 'TFOODEXP', 'TALCHEXP', 'TCLTHEXP', 'THOUSEXP', 'TFURNEXP', 'THLTHEXP', 'TTRANSEXP', 'TCOMMEXP', 'TRECEXP', 'TEDUEXP', 'TRESTHOTEXP', 'TMISCEXP',
'INCTOTGROSSHH', 'INCRMT', 'INCWAGE', 'INCFARMBSN', 'INCNFARMBSN', 'INCRENT', 'INCFIN', 'INCPENSN', 'INCOTHER')
pramVarsHH = c('ROOF', 'TOILET', 'WATER', 'ELECTCON', 'FUELCOOK', 'OWNMOTORCYCLE', 'CAR', 'TV', 'LIVESTOCK')
weightVarHH = c('WGTPOP')
HHVars <- c('IDH', selectedKeyVarsHH, pramVarsHH, numVarsHH, weightVarHH)
fileHH <- file[,HHVars]
fileHH <- fileHH[which(!duplicated(fileHH$IDH)),]
sdcHH <- createSdcObj(dat=fileHH, keyVars=selectedKeyVarsHH, pramVars=pramVarsHH, weightVar=weightVarHH, numVars = numVarsHH)
sdcInitial <- sdcHH
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.9: Manually suppressing values in linked variables
----------------------------------------------------
```{r, error=TRUE}
# Suppress values of rururb in file if region is suppressed
file[is.na(sdcInitial@manipKeyVars$region) & !is.na(sdcInitial@origData$region),'sizRes'] <- NA
```
```{r, include = FALSE}
sdcInitial <- sdcInitialCopy
```
Example 5.10: Suppressing values in linked variables by specifying ghost variables
----------------------------------------------------
```{r, error=TRUE}
# Ghost vars are specified as a list of linkages
ghostVars <- list()
# Each linkage is a list, with the first element the key variable and the second element the linked variable(s)
ghostVars[[1]] <- list()
ghostVars[[1]][[1]] <- "region"
ghostVars[[1]][[2]] <- c("sizeRes")
## create the sdcMicroObj
sdcInitial <- createSdcObj(file, keyVars = keyVars, numVars = numVars, w = w, ghostVars = ghostVars)
# The manpulated ghost variables are in the slot manipGhostVars
sdcInitial@manipGhostVars
```
```{r, include = FALSE}
sdcInitial <- sdcHH
```
Example 5.10: Producing reproducible PRAM results by using set.seed()
----------------------------------------------------
```{r, error=TRUE}
# set seed for random number generation
set.seed(123)
sdcInitial <- pram(obj = sdcInitial)
```
Example 5.11: Selecting variables to apply PRAM
----------------------------------------------------
```{r, error=TRUE}
set.seed(123) # set seed for random number generation
sdcInitial <- pram(obj = sdcInitial, variables = c ("TOILET"))
```
Example 5.12: Specifying minimum values for diagonal entries in PRAM transition matrix
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- pram(obj = sdcInitial, variables = c("TOILET"), pd = c(1, 0, 0, 0))
```
Example 5.13: Minimizing unlikely combinations by applying PRAM within strata
----------------------------------------------------
```{r, error=TRUE}
#Applying PRAM within the strata formed by the variable educ
sdcInitial <- pram(obj = sdcInitial, variables = c("TOILET"), strata_variables = c("REGION"))
```
Example 5.14: Applying microaggregation with sdcMicro function microaggregation()
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- microaggregation(obj = sdcInitial, variables = 'INCTOTGROSSHH', aggr = 3, method = mafast, measure = "mean")
```
Example 5.15: Microaggregation with the Maximum Distance to Average Vector (MDAV) algorithm in sdcMicro
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- microaggregation(obj = sdcInitial, variables = c("INCTOTGROSSHH", "TANHHEXP"), method = "mdav")
```
Example 5.16: Specifying strata variables for microaggregation
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- microaggregation(obj = sdcInitial, variables = c("INCTOTGROSSHH", "TANHHEXP"), method = "mdav", strata_variables = c("REGION"))
```
Example 5.17: Uncorrelated noise addition
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- addNoise(obj = sdcInitial, variables = c('TFOODEXP', 'TALCHEXP', 'TCLTHEXP', 'THOUSEXP', 'TFURNEXP', 'THLTHEXP', 'TTRANSEXP', 'TCOMMEXP', 'TRECEXP', 'TEDUEXP', 'TRESTHOTEXP', 'TMISCEXP'), noise = 0.5, method = "additive")
```
Example 5.18: Correlated noise addition
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- addNoise(obj = sdcInitial, variables = c('TFOODEXP', 'TALCHEXP', 'TCLTHEXP', 'THOUSEXP', 'TFURNEXP', 'THLTHEXP', 'TTRANSEXP', 'TCOMMEXP', 'TRECEXP', 'TEDUEXP', 'TRESTHOTEXP', 'TMISCEXP'), noise = 0.5, method = "correlated2")
```
Example 5.19: Noise addition for outliers using the ëoutdectí method
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- addNoise(obj = sdcInitial, variables = c('TFOODEXP', 'TALCHEXP', 'TCLTHEXP', 'THOUSEXP', 'TFURNEXP', 'THLTHEXP', 'TTRANSEXP', 'TCOMMEXP', 'TRECEXP', 'TEDUEXP', 'TRESTHOTEXP', 'TMISCEXP'), noise = 0.5, method = "outdect")
```
Example 5.20: Noise addition to aggregates and their components
----------------------------------------------------
```{r, error=TRUE}
# add noise to totals (income / expenditures)
sdcInital <- addNoise(noise = 0.5, obj = sdcInitial, variables=c("TANHHEXP", "INCTOTGROSSHH"), method="additive")
# multiply anonymized totals with ratios to obtain anonymized components
compExp <- c('TFOODEXP', 'TALCHEXP', 'TCLTHEXP', 'THOUSEXP', 'TFURNEXP', 'THLTHEXP', 'TTRANSEXP', 'TCOMMEXP', 'TRECEXP', 'TEDUEXP', 'TRESTHOTEXP', 'TMISCEXP')
sdcInital@manipNumVars[,compExp] <- sdcInital @manipNumVars[,"TANHHEXP"] * sdcInital @origData[,compExp]/ sdcInital@origData[,"TANHHEXP"]
# recalculate risks after manually changing values in sdcMicro object
calcRisks(sdcInital)
```
Example 5.21: Rank swapping using sdcMicro
----------------------------------------------------
```{r, error=TRUE}
# set seed for random number generator
set.seed(12345)
# check correlation structure between the variables
cor(file$THOUSEXP, file$TFOODEXP)
# apply rank swapping
rankSwap(sdcInitial, variables = c("TOTHOUS", "TOTFOOD"), missing = NA)
```
Example 5.22: Shuffling using a specified regression equation
----------------------------------------------------
```{r, error=TRUE}
# Evaluate R-squared (goodness-of-fit) of the regression model
summary(lm(file, form = TFOODEXP + TALCHEXP + TCLTHEXP + THOUSEXP + TFURNEXP + THLTHEXP + TTRANSEXP + TCOMMEXP + TRECEXP + TEDUEXP + TRESTHOTEXP + TMISCEXP ~ TANHHEXP + HHSIZE))
# Shuffling using the specified regression equation
sdcInitial <- shuffle(sdcInitial, method='ds', form = TFOODEXP + TALCHEXP + TCLTHEXP + THOUSEXP + TFURNEXP + THLTHEXP + TTRANSEXP + TCOMMEXP + TRECEXP + TEDUEXP + TRESTHOTEXP + TMISCEXP ~ TANHHEXP + HHSIZE)
```
Example 6.1: Using the print function to retrieve the total number of suppressions for each key variable
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- localSuppression(sdcInitial, k = 5, importance = NULL)
print(sdcInitial, 'ls')
```
Example 6.2: Displaying the number of missing values for each categorical key variable in an sdcMicro object
----------------------------------------------------
```{r, error=TRUE}
# Store the names of all categorical key variables in a vector
namesKeyVars <- names(sdcInitial@manipKeyVars)
# Matrix to store the number of missing values (NA) before and after anonymization
NAcount <- matrix(NA, nrow = 2, ncol = length(namesKeyVars))
colnames(NAcount) <- c(paste0('NA', namesKeyVars)) # column names
rownames(NAcount) <- c('initial', 'treated') # row names
# NA count in all key variables (NOTE: only those coded NA are counted)
for(i in 1:length(namesKeyVars))
{
NAcount[1, i] <- sum(is.na(sdcInitial@origData[,namesKeyVars[i]]))
NAcount[2, i] <- sum(is.na(sdcInitial@manipKeyVars[,i]))
}
```
Example 6.3: Computing number of records changed per variable
----------------------------------------------------
```{r, error=TRUE}
# Dataframe to save the number of records changed
recChanged <- rep(0, length(namesKeyVars))
names(recChanged) <- c(paste0('RC', namesKeyVars))
# Count number of records changed
for(j in 1:length(namesKeyVars)) # for all key variables
{
comp <- sdcInitial@origData[namesKeyVars[j]] != sdcInitial@manipKeyVars[namesKeyVars[j]]
temp1 <- sum(comp, na.rm = TRUE) # all changed variables without NAs
temp2 <- sum(is.na(comp)) # if NA, changed, unless NA initially
temp3 <- sum(is.na(sdcInitial@origData[namesKeyVars[j]]) + is.na(sdcInitial@manipKeyVars[j])==2) # both NA, no change, but counted in temp2
recChanged[j] <- temp1 + temp2 - temp3
}
```
Example 6.4: Using dUtility() to compute IL1s data utility measure in sdcMicro
----------------------------------------------------
```{r, error=TRUE}
sdcInitial <- dUtility(sdcInitial)
```
Example 6.5: Calling the IL1S measure from the utility slot of the sdcMicro object ësdcInitialí
----------------------------------------------------
```{r, error=TRUE}
sdcInitial@utility$il1
#[1] 0.05108216
```
Example 6.6: Using dUtility() to compute eigenvalues in sdcMicro
----------------------------------------------------
```{r, error=TRUE}
# Comparison of eigenvalues of continuous variables
dUtility(obj = sdcInitial@origData[,contVars], xm = sdcInitial@manipNumVars[,contVars], method = 'eigen')
#[1] 1.811127e+13
# Comparison of robust eigenvalues of continuous variables
dUtility(obj = sdcInitial@origData[,contVars], xm = sdcInitial@manipNumVars[,contVars], method = 'robeigen')
```
Example 6.7: Comparing the means of continuous variables
----------------------------------------------------
```{r, error=TRUE}
colMeans(sdcInitial@origData[, numVars], na.rm = TRUE)
colMeans(sdcInitial@manipNumVars[, numVars], na.rm = TRUE)
```
Example 6.8: Comparing covariances and correlation matrices of numeric variables
----------------------------------------------------
```{r, error=TRUE}
# untreated data
cov(sdcInitial@origData[, numVars])
cor(sdcInitial@origData[, numVars])
# anonymized data
cov(sdcInitial@manipNumVars[, numVars])
cor(sdcInitial@manipNumVars[, numVars])
```
Example 6.9: Comparing cross tabulations of categorical variables
----------------------------------------------------
```{r, error=TRUE}
# Cross tabulation of the variables region and household size
table(sdcInitial@origData[, c('REGION', 'HHSIZE')])
table(sdcInitial@manipKeyVars[, c('REGION', 'HHSIZE')])
```
Example 6.10: Loading the laeken package for computation of the Gini coefficient
----------------------------------------------------
```{r, error=TRUE}
library(laeken) # for Gini coefficient
```
Example 6.11: Computing the Gini coefficient from the income variable to determine income inequality
----------------------------------------------------
```{r, error=TRUE}
gini(inc = sdcInitial@origData[,sdcInitial@numVars[1]], weights = curW, na.rm=TRUE, alpha = 0.05)$value # Gini coefficient
```
Example 6.12: Constructing a confidence interval around the Gini to evaluate significance of change after anonymization
----------------------------------------------------
```{r, error=TRUE}
gini(inc = sdcInitial@origData[,sdcInitial@numVars[1]], weights = curW, na.rm=TRUE, alpha = 0.05)$ci # confidence interval, 1- alpha
```
Example 6.13: Using regression to evaluate data utility before and after anonymization
----------------------------------------------------
```{r, error=TRUE}
# Mincer equation
# Specify regression formula
Mformula <- 'Mlwage ~ Mgender + Mempstat + Meducy + Mexp + Mexp2'
# Mincer equation variables
Mlwage <- log(cursdc@manipNumVars$wage) # log wage
Mlwage[Mlwage == NaN] <- -Inf
Mempstat <- cursdc@manipKeyVars$empstat=='Paid employee' # TRUE if 'paid employee', else FALSE or NA
Mage <- cursdc@manipKeyVars$age # age in years
Meducy <- cursdc@origData$educy # educy
Mexp <- Mage - Meducy - 6 # experience in years
Mexp[Mexp <= 0] <- 0 # set experience to 0 if negative
Mexp2 <- Mexp^2 # squared experience
Mgender <- cursdc@manipKeyVars$gender # gender dummy
Mwgt <- curW # weight variable for regression
# Create data frame for regression containing the (modified) variables
Mfile <- as.data.frame(cbind(Mlwage, Mempstat, Mexp, Mexp2, Meducy, Mgender, Mwgt, Mage))
colnames(Mfile)[1] <- 'Mlwage'
# Regression for age 15-65
mincer1565temp <- lm(Mformula, data = subset(Mfile, Mfile[,'Mage'] >= 15 & Mfile[,'Mage'] <= 65 & Mfile[,'Mempstat']==TRUE & Mfile[,'Mlwage'] != -Inf), na.action=na.exclude, weights = Mwgt)
# Regression for age 15-25
mincer1525temp <- lm(Mformula, data=subset(Mfile, Mfile[,'Mage'] >= 15 & Mfile[,'Mage'] <= 25 & Mfile[,'Mempstat']==TRUE & Mfile[,'Mlwage'] != -Inf), na.action=na.exclude, weights=Mwgt)
# The objects mincer1565temp and mincer1565temp contain the results of the regressions. To see the coefficients of the regression
mincer1525$coeffficients
mincer1565$coefficients
# Compute the 95 percent confidence interval
confint(obj = mincer1525, level = 0.95)
confint(obj = mincer1565, level = 0.95)
```
Example 6.14: Plotting histograms and kernel densities
----------------------------------------------------
```{r, error=TRUE}
# Plot histograms
# Plot 2 histograms next to one another
par(mfrow = c(1,2))
# Plot histogram before anonymization
hist(sdcObj@origData$INCOME, breaks = (-6:6)*1e7, main = "Hist orig")
# Plot histogram after anonymization (noise addition)
hist(sdcObj@manipNumVars$INCOME, breaks = (-6:6)*1e7, main = "Hist anon")
# Plot densities
# Plot 2 curves next to one another
par(mfrow = c(1,2))
# Plot original density curve
plot(density(sdcObj@origData$INCOME), xlim = c(-6e7, 6e7), ylim = c(0, 6e-6), main = "Density orig")
# Plot density curve after anonymization (noise addition)
plot(density(sdcObj@manipNumVars$INCOME), xlim = c(-6e7, 6e7), lty = 2, main = "Density anon")
```
Example 6.15: Creating boxplots for continuous variables
----------------------------------------------------
```{r, error=TRUE}
boxplot(sdcObj@origData$TOTFOOD, sdcObj@manipNumVars$TOTFOOD, xaxt = 'n', ylab = "Expenditure")
axis(1, at = c(1,2), labels = c('before', 'after'))
```
Example 6.16: Creating multivariate mosaic plots
----------------------------------------------------
```{r, error=TRUE}
# Collecting data of variable WATER before and after anonymization, assigning factor levels for labels in plot
dataWater <- t(cbind(table(factor(sdcHH@origData$WATER, levels = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
labels = c("Pipe (own tap)", "Public standpipe", "Borehole", "Wells
(protected)", "Wells (unprotected)", "Surface water", "Rain water",
"Vendor/truck", "Other"))), table(factor(sdcHH@manipPramVars$WATER,
levels = c(1,2, 3, 4, 5, 6, 7, 8, 9), labels = c("Pipe (own tap)",
"Public standpipe", "Borehole", "Wells (protected)", "Wells
(unprotected)", "Surface water", "Rain water", "Vendor/truck",
"Other")))))
rownames(dataWater) <- c("before", "after")
# Plotting mosaic plot
mosaicplot(dataWater, main = "", color = 2:10, las = 2)
```
Example 6.17: Creating multivariate mosaic plots
----------------------------------------------------
```{r, error=TRUE}
# Mosaic plot multivariate
par(mfrow = c(1,1))
mosaicplot(t(table(factor(sdcHH@origData$ROOF, levels = c(1,2, 3, 4, 5, 9),
labels = c("Concrete/cement/ \n brick/stone", "Wood",
"Bamboo/thatch", "Tiles/shingles",
"Tin/metal sheets", "Other")),
factor(sdcHH@origData$TOILET, levels = c(1,2, 3, 4, 9),
labels = c("Flush \n toilet", "Improved \n pit \n latrine",
"Pit \n latrine", "No \n facility", "Other")))),
main = "Moisaic plot of the variables ROOF and TOILET (before)", las = 2, color =
2:6)
mosaicplot(t(table(factor(sdcHH@manipPramVars$ROOF, levels = c(1,2, 3, 4, 5, 9),
labels = c("Concrete/cement/ \n brick/stone", "Wood",
"Bamboo/thatch", "Tiles/shingles",
"Tin/metal sheets", "Other")),
factor(sdcHH@manipPramVars$TOILET, levels = c(1,2, 3, 4, 9),
labels = c("Flush \n toilet", "Improved \n pit \n latrine",
"Pit \n latrine", "No \n facility", "Other")))),
main = "Moisaic plot of the variables ROOF and TOILET (after)", las = 2, color = 2:6)
```
Example 7.1: Loading required packages
----------------------------------------------------
```{r, error=TRUE}
library(sdcMicro) # loading the sdcMicro package
require(sdcMicro) # loading the sdcMicro package
```
Example 7.2: Displaying help for functions
----------------------------------------------------
```{r, error=TRUE}
?microaggregation # help for microaggregation function
```
Example 7.3: Reading in a STATA file
----------------------------------------------------
```{r, error=TRUE}
setwd("/Users/World Bank") #working directory with data file
fname = "data.dta" # name of data file
library(foreign) # loads required package for read/write function for STATA files
file <- read.dta(fname, missing.type = TRUE, convert.factors = F)
# reads the data into the data frame called file, factors as numeric code
```
Example 7.4: Reading in an Excel file
----------------------------------------------------
```{r, error=TRUE}
setwd("/Users/World Bank") #working directory with data file
fname = "data.csv" # name of data file
file <- read.csv(fname, header = TRUE, sep = ",", dec = ".")
# reads the data into the data frame called file
```
Example 7.5: Reading in an SPSS file
----------------------------------------------------
```{r, error=TRUE}
setwd("/Users/World Bank") #working directory with data file
fname = "data.sav" # name of data file
library(foreign) # loads required package for read/write function for STATA files
file <- read.spss(fname, use.value.labels = FALSE)
# reads the data into the data frame called file, factors as numeric code
```
Example 7.6: Recoding missing values to NA
----------------------------------------------------
```{r, error=TRUE}
file[file[,'toilet'] == 99,'toilet'] <- NA # Recode missing value code 99 to NA for variable toilet
```
Example 7.7: Changing the class of a variable in R
----------------------------------------------------
```{r, error=TRUE}
# Finding out the class of the variable region in the dataframeìfileî
class(file$region)
# Changing the class to factor
file$region <- as.factor(file$region)
```
Example 7.8: Creating an object of class sdcMicroObj for the SDC process
----------------------------------------------------
```{r, error=TRUE}
# Select variables for creating sdcMicro object
# All variable names should correspond to the names in the data file
# selected categorical key variables
selectedKeyVars = c('age', 'gender', 'marital', 'empstat')
# selected linked variables (ghost variables)
selectedGhostVars = c('age', '')
# selected categorical numerical variables
selectedNumVar = c('wage', 'savings')
# weight variable
selectedWeightVar = c('wgt')
# selected pram variables
selectedPramVars = NULL
# household id variable (cluster)
selectedHouseholdID = c('idh')
# stratification variable
selectedStrataVar = c('strata')
# creating the sdcMicro object with the assigned variables
sdcInitial <- createSdcObj(dat = file, keyVars = selectedKeyVars, ghostVars = selectedGhostVars, numVar = selectedNumVar, weightVar = selectedWeightVar, pramVars = selectedPramVars, hhId = selectedHouseholdID, strataVar = selectedStrataVar)
```
Example 7.9: Displaying slot names and accessing slots
----------------------------------------------------
```{r, error=TRUE}
# List names of all slots of sdcMicro object
slotNames(sdcInitial)
## [1] "origData" "keyVars" "pramVars"
## [4] "numVars" "weightVar" "hhId"
## [7] "strataVar" "sensibleVar" "manipKeyVars"
## [10] "manipPramVars" "manipNumVars" "manipStrataVar"
## [13] "originalRisk" "risk" "utility"
## [16] "pram" "localSuppression" "options"
## [19] "additionalResults" "set" "prev"
## [22] "deletedVars"
# Accessing the risk slot
sdcInitial@risk
# List names within the risk slot
names(sdcInitial@risk)
# Accessing the individual risk within the risk slot
sdcInitial@risk$individual
```
Example 7.10: Saving results of applying SDC methods
----------------------------------------------------
```{r, error=TRUE}
# Applying local suppression and reassigning the results to the same sdcMicro object
sdcInitial <- localSuppression(sdcInitial)
# Applying local suppression and assigning the results a new sdcMicro object
sdc1 <- localSuppression(sdcInitial)
```
Example 7.11: Undo last step in SDC process
----------------------------------------------------
```{r, error=TRUE}
# Undo last step in SDC process
sdcInitial <- undolast(sdcInitial)
```
Example 7.12: Create a household level file with unique records (remove duplicates)
----------------------------------------------------
```{r, error=TRUE}
# Create subset of file with only variables measured at household level
fileHH <- file[,HHVars]
# Remove duplicated rows based on the household ID, select uniques / only every household once in fileHH
fileHH <- unique(fileHH, by = c('HID'))
# Dimensions of fileHH (number of households)
dim(fileHH)
```
Example 7.13 Merging anonymized household level variables with individual level variables
----------------------------------------------------
```{r, error=TRUE}
# Subtract manipulated household level variables from the SDC object
HHmanip <- extractManipData(sdcHH)
# Create subset of file with only variables measured at individual level
fileIND <- file[,INDVars]
# Merge the file by using the household ID
fileCombined <- merge(HHmanip, fileIND, by = c('HID'))
```
Example 7.14 Generating the variable household size
----------------------------------------------------
```{r, error=TRUE}
# Sorted by HID
rep(unname(table(file$HID)), unname(table(file$HID)))
# Unsorted
rep(diff(c(1, 1 + which(diff(file$HID) != 0), length(b)+1)), diff(c(1, 1 + which(diff(file$HID) != 0), length(file$HID)+1)))
```
Example 7.15 Changing the order of individuals within households
----------------------------------------------------
```{r, error=TRUE}
# List of householdsizes by household
hhsize <- diff(c(1, 1 + which(diff(file$HID) != 0), length(file$HID) + 1))
# Line numbers randomly assigned within each household
set.seed(123)
dataAnon$INDID <- unlist(lapply(hhsize, function(n){sample(1:n, n, replace = FALSE, prob = rep(1/n, n))}))
# Order the file by HID and INDID (line number)
dataAnon <- dataAnon[order(dataAnon$HID, dataAnon$INDID),]
```
Example 7.16 Changing the order of individuals within households
----------------------------------------------------
```{r, error=TRUE}
n <- length(file$HID) # number of households
set.seed(123) # set seed
file$HIDrandom <- sample(1:n, n, replace = FALSE, prob = rep(1/n, n)) # generate random HID
file <- file1[order(file$regionid, file$HIDrandom),] # sort file by regionid and random HID
file$HIDrandom <- 1:n # renumber the households in randomized order to 1-n
```
Example 9.1: Loading required packages
----------------------------------------------------
```{r, error=TRUE}
# Load required packages
library(foreign) # for read/write function for SPSS
library(sdcMicro) # sdcMicro package with
```
Example 9.2: Loading the data
----------------------------------------------------
```{r, error=TRUE}
# Set working directory
setwd("C:/WorldBank/CaseStudy1/")
# Specify file name
fname <- "case1.dta"
# Read-in file from STATA file
file <- read.dta(fname, convert.factors = F) # factors as numeric code
```
Example 9.3: Number of individuals and number of variables
----------------------------------------------------
```{r, error=TRUE}
dim(file) # Dimensions of file (observations, variables)
colnames(file) # Variable names
```
Example 9.4: Tabulation and summary statistics
----------------------------------------------------
```{r, error=TRUE}
table(file$GENDER, useNA = "ifany") #tabulation of variable gender
summary(file$WSCORE) # summary statistics for variable WSCORE
```
Example 9.5: Recoding missing values codes and ìdonít knowî values
----------------------------------------------------
```{r, error=TRUE}
# Recoding missing values
file[which(file$TOILET == 99), 'TOILET'] <- NA
file[which(file$LITERACY == 9), 'LITERACY'] <- NA
file[which(file$EDUC == 98 | file$EDUC == 99), 'EDUC'] <- NA
# ìDonít know values
# Set "don't know" values to NA
file[which(file$EDULEVEL == 8), 'EDULEVEL'] <- NA
file[which(file$ETHNICITY == 96), 'ETHNICITY'] <- NA
```
Example 9.6: Recoding the variable CHAGED to quarter of years and merging with the variable AGE
----------------------------------------------------
```{r, error=TRUE}
# Supress all age under 5 and replace with CHAGED in quarter years
file$AGE[file$AGE >= 0 & file$AGE < 5] <- floor(file$CHAGED[file$AGE >= 0 & file$AGE < 5] / 91)/4
```
Example 9.7: Generating household size and tabulation
----------------------------------------------------
```{r, error=TRUE}
# Create variable HHSIZE and check the size of households
file$HHSIZE <- rep(unname(table(file$HID)), unname(table(file$HID)))
#Tabulation of the variable HHSIZE
table(file$HHSIZE) / as.numeric(names(table(file$HHSIZE)))
```
Example 9.8: Adding a household and individual ID
----------------------------------------------------
```{r, error=TRUE}
# Create household id and individual id
# Household ID: CLUSTER (cluster number) and HHNO (household number)
file$HID <- file$CLUSTER * 1000 + file$HHNO
# Individual ID: CLUSTER (cluster number), HHNO (household number) and LINENOALL (line number)
file$INDID <- file$HID * 100 + file$LINENOALL
```
Example 9.9: Selecting the variables for the household level anonymization
----------------------------------------------------
```{r, error=TRUE}
# Categorical key variables
selectedKeyVarsHH <- c('AREA', 'REGION', 'RELIGION', 'LANGUAGE', 'ETHNICITY', 'TOILET')
# PRAM variables
PRAMVarsHH <- c('WSCORE')
# Strata variable
selectedStrataVarHH <- c('STRATA')
# Sampling weights (household weight)
weightVarHH <- c('HHWGT')
# All household level variables
HHVars <- c('HID', selectedKeyVarsHH, pramVarsHH, weightVarHH, selectedStrataVarHH)
```
Example 9.10: Taking a subset with only households
----------------------------------------------------
```{r, error=TRUE}
# Take subset of file of only HH variables
fileHH <- file[,HHVars]
# Remove duplicated rows based on HID, select uniques / only every household once in fileHH
fileHH <- unique(fileHH, by=c('INDID'))
dim(fileHH)
```
Example 9.11: Creating a sdcMicro object for the household variables
----------------------------------------------------
```{r, error=TRUE}
# Create initial sdc object for household level variables
sdcHH <- createSdcObj(dat = fileHH, keyVars = selectedKeyVarsHH, weightVar =
weightVarHH, pramVars = PRAMVarsHH, strataVar = selectedStrataVarHH )
```