-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhs-analysis.R
2427 lines (2128 loc) · 193 KB
/
dhs-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
library(tidyverse)
library(rdhs)
library(scales)
library(sf)
library(rmapshaper)
library(patchwork)
library(ggrepel)
library(arrow)
library(sfarrow)
library(readxl)
library(Hmisc)
library(tidymodels)
library(readr)
library(viridis)
library(ggpubr)
library(broom)
library(betareg)
library(ggpmisc)
library(kableExtra)
library(xtable)
options(scipen = 9999)
gc()
# https://dhsprogram.com/pubs/pdf/DHSG1/Guide_to_DHS_Statistics_DHS-7_v2.pdf
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
getwd()
dir.create('data/dhs-analysis')
dir.create('data/dhs-analysis/data')
dir.create('data/dhs-analysis/viz')
wd_path = getwd()
load_saved = TRUE
# Setup configuration -----------------------------------------------------
# RData file
if (load_saved == TRUE) {
# Download from https://drive.google.com/file/d/19LuFTTm-C1fikBc64xTpmf_zrNIcsTOd/view?usp=drive_link
# Or from https://uchicago.box.com/s/anw4fxc376dgtgol9tt87tuozipnk0kj
# copy /dhs-source-data into /data folder
load(paste0(wd_path,"/data/dhs-source-data/dhs_data.RData"))
subnat_to_blocks <- read_parquet(paste0(wd_path,'/data/dhs-source-data/blocks_to_dhs.parquet'))
} else {
# Make sure to download the block files (this is done in the complexity-analysis.R script)
if (!file.exists(paste0("data/africa_data.parquet"))) {
curl::multi_download("dsbprylw7ncuq.cloudfront.net/AF/africa_data.parquet", "data/africa_data.parquet", resume = TRUE)
}
if (!file.exists(paste0("data/africa_geodata.parquet"))) {
curl::multi_download("dsbprylw7ncuq.cloudfront.net/AF/africa_geodata.parquet", "data/africa_geodata.parquet", resume = TRUE)
}
}
# Load staging files
# Box.com link with access to staging files:
# https://uchicago.box.com/s/anw4fxc376dgtgol9tt87tuozipnk0kj
# subnat_indicators <- read_csv(paste0(wd_path,'/data/dhs_download.csv'))
# subnat_all <- st_read(paste0(wd_path,'/data/dhs_geographies.geojson'))
# subnat_all_wide <- st_read(paste0(wd_path,'/data/dhs_all_wide.geojson'))
# CHANGE TO DHS USER LOGIN CREDENTIAL
# Follow instructions here: # https://docs.ropensci.org/rdhs/articles/introduction.html
dhs_user_email = 'nmarchio@uchicago.edu'
dhs_project_name = "Identifying neighborhoods and detecting service deficits in sub-Saharan Africa from complete buildings footprint data"
# -------------------------------------------------------------------------
# # UN cached
# if (load_saved == TRUE) {
# un_slums_k <- read_csv(paste0(wd_path,'/data/un_slums_k.csv'))
# un_services_cities_k <- read_csv(paste0(wd_path,'/data/un_services_cities_k.csv'))
# urban_k <- read_csv(paste0(wd_path,'/data/aggregated_urban_k.csv'))
# city_k <- read_csv(paste0(wd_path,'/data/aggregated_city_k.csv'))
# }
#
# # DHS cached
# if (load_saved == TRUE) {
# subnat_all_wide <- st_read(paste0(wd_path,'/data/dhs_all_wide.geojson'))
# k_data_subnat <- read_csv(paste0(wd_path,'/data/k_data_subnational.csv'))
# }
#names(subnat_all_wide)
#sapply(subnat_all_wide, function(X) sum(is.na(X)))
# Check if indicator exists in DHS and MIS
# fulluni_indicators <- dhs_data(surveyIds = c('SN2020MIS','MR2020DHS'),
# breakdown = "subnational")
# Load DHS Survey Data ---------------------------------------------------------
if (load_saved == FALSE) {
# config <- get_rdhs_config()
set_rdhs_config(email = dhs_user_email,
project = dhs_project_name,
cache_path = paste0(wd_path),
timeout = 180)
#Country list
country_list <- c('AGO', 'BEN', 'BWA', 'BFA', 'CMR', 'CPV', 'CAF', 'TCD', 'COG', 'COD', 'CIV', 'GNQ', 'SWZ', 'GAB', 'GMB', 'GHA', 'GIN', 'LSO', 'LBR', 'MLI', 'MRT', 'NAM', 'NER', 'NGA', 'STP', 'SEN', 'SLE', 'ZAF', 'TGO')
# Indicator list
indicator_list <- c('AN_NUTS_W_SHT', 'AN_NUTS_W_THN', 'AN_ANEM_W_ANY', 'CH_ARIS_C_ADV', 'CH_DIAR_C_DIA', 'CH_VACC_C_DP1', 'CH_VACC_C_DP2', 'CH_VACC_C_BAS', 'CH_VACC_C_AP2', 'CN_IYCF_C_4FA', 'CN_IYCF_C_MNA', 'CN_NU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M_ECMR_C_U5M',
'WS_HNDW_H_OBS', 'WS_HNDW_H_SOP', 'WS_HNDW_H_BAS', 'WS_HNDW_H_LTD', 'WS_HNDW_P_OBS', 'WS_HNDW_P_SOP', 'WS_HNDW_P_BAS', 'WS_HNDW_P_LTD', 'WS_TLET_H_IMP', 'WS_TLET_H_NFC', 'WS_TLET_H_BAS', 'WS_TLET_H_LTD', 'WS_TLET_P_IMP', 'WS_TLET_P_NFC', 'WS_TLET_P_BAS', 'WS_TLET_P_LTD', 'WS_TLOC_H_DWL', 'WS_TLOC_P_DWL', 'WS_SRCE_H_IMP', 'WS_SRCE_H_PIP', 'WS_SRCE_H_NIM', 'WS_SRCE_H_IOP', 'WS_SRCE_H_BAS', 'WS_SRCE_H_LTD', 'WS_SRCE_P_IMP', 'WS_SRCE_P_PIP', 'WS_SRCE_P_NIM', 'WS_SRCE_P_IOP', 'WS_SRCE_P_BAS', 'WS_SRCE_P_LTD', 'WS_TIME_H_ONP', 'WS_TIME_H_L30', 'WS_TIME_H_M30', 'WS_TIME_P_ONP', 'WS_TIME_P_L30', 'WS_TIME_P_M30', 'WS_WTRT_H_APP', 'WS_WTRT_P_APP')
indicator_list <- indicator_list %>% unique()
# Configure DHS metadata
meta_tags <- dhs_tags()
meta_surveychar <- dhs_survey_characteristics()
meta_surveys <- dhs_surveys()
meta_indicators <- dhs_indicators() %>%
filter(IndicatorId %in% indicator_list)
dhs_indicator_list <- meta_indicators %>% select(IndicatorId) %>% distinct() %>% pull()
meta_countryids <- dhs_countries() %>%
filter(SubregionName %in% c("Middle Africa","Western Africa","Southern Africa","North Africa")) %>%
filter(UNSTAT_CountryCode %in% country_list)
dhs_country_list <- meta_countryids %>% select(DHS_CountryCode) %>% distinct() %>% pull()
meta_data <- dhs_datasets() %>%
filter(DHS_CountryCode %in% dhs_country_list,
SurveyYear >= 2010,
FileFormat == 'Flat ASCII data (.dat)',
FileType %in% c("Geospatial Covariates","Geographic Data", "Wealth Index",
"Household Member Recode", "Household Recode"))
meta_data_subset <- meta_data %>%
select(any_of(c("SurveyNum","SurveyId","FileType","SurveyYear","DHS_CountryCode","CountryName"))) %>%
mutate(flag = 1) %>%
pivot_wider(.,names_from = FileType, values_from = flag) %>%
filter(!is.na(`Household Member Recode`) & !is.na(`Geographic Data`) & !is.na(`Household Recode`)) %>%
group_by(DHS_CountryCode) %>%
mutate(rank = row_number(desc(SurveyYear))) %>%
ungroup() %>% filter(rank <= 3)
survey_list <- unique(meta_data_subset$SurveyId)
survey_list <- setdiff(survey_list, c("SL2016MIS","AO2011MIS")) # surveys without GIS information
# Download DHS Survey Data
if (!file.exists(paste0(wd_path,'/data/dhs_download.csv'))) {
# subnat_indicators <- dhs_data(surveyIds = survey_list,
# indicatorIds = dhs_indicator_list,
# breakdown = "subnational")
dhs_indicator_chunk <- base::split(dhs_indicator_list, ceiling(seq_along(dhs_indicator_list)/ceiling(length(dhs_indicator_list)/2)))
subnat_indicators_1 <- dhs_data(surveyIds = survey_list,
indicatorIds = dhs_indicator_chunk$`1`,
breakdown = "subnational")
subnat_indicators_2 <- dhs_data(surveyIds = survey_list,
indicatorIds = dhs_indicator_chunk$`2`,
breakdown = "subnational")
subnat_indicators <- rbind(subnat_indicators_1, subnat_indicators_2)
subnat_indicators %>% group_by(IndicatorId) %>% tally() %>% print(n=200)
write_csv(subnat_indicators, paste0(wd_path,'/data/dhs_download.csv'))
# all_indicators <- dhs_data(surveyIds = survey_list,
# indicatorIds = dhs_indicator_list,
# breakdown = "all",
# returnGeometry=TRUE,
# f = 'geoJSON')
#write_csv(subnat_indicators, paste0(wd_path,'/data/dhs_download_micro.csv'))
} else {
subnat_indicators <- read_csv(paste0(wd_path,'/data/dhs_download.csv'))
}
# Pivot DHS data wide
subnat_wide <- subnat_indicators %>%
filter(IsPreferred == 1) %>%
#select(-any_of(c('Indicator','DenominatorUnweighted', 'DenominatorWeighted')))
select(any_of(c('IndicatorId','Value','DenominatorWeighted','DenominatorUnweighted','SurveyId', 'RegionId', 'SurveyYearLabel', 'SurveyType', 'SurveyYear', 'DHS_CountryCode', 'CountryName'))) %>%
distinct() %>% # drops dups in 'GN2012DHS', 'SN2020MIS'
pivot_wider(.,
id_cols = c('SurveyId', 'RegionId', 'SurveyYearLabel', 'SurveyType', 'SurveyYear', 'DHS_CountryCode', 'CountryName'),
names_from = c('IndicatorId'),
values_from = c('Value','DenominatorWeighted','DenominatorUnweighted')) %>%
rename_at(vars(starts_with('Value_')), ~ str_replace(.x,"Value_","")) %>%
rename_at(vars(starts_with('DenominatorWeighted_')), ~ str_replace(.x,"DenominatorWeighted_","dw_")) %>%
rename_at(vars(starts_with('DenominatorUnweighted_')), ~ str_replace(.x,"DenominatorUnweighted_","du_"))
# sapply(subnat_wide, function(X) sum(is.na(X)))
# if (exists('subnat_all') && is.data.frame(get('subnat_all'))) {
# survey_list <- setdiff(unique(meta_data_subset$SurveyId),unique(subnat_all$SurveyId))
# survey_list <- setdiff(survey_list, c("SL2016MIS","AO2011MIS"))
# } else {
# survey_list <- unique(meta_data_subset$SurveyId)
# survey_list <- setdiff(survey_list, c("SL2016MIS","AO2011MIS"))
# }
# Download DHS region boundaries
if (!file.exists(paste0(wd_path,'/data/dhs_geographies.geojson'))) {
# Download boundaries
for (i in survey_list) {
print(i)
geo <- download_boundaries(surveyId = i, method = "sf", server_sleep = 10)
geo <- geo$sdr_subnational_boundaries
print(names(geo))
geo <- geo %>%
ms_simplify(., keep = 0.05, keep_shapes = TRUE) %>%
mutate(SurveyId = i)
if (exists('subnat_all') && is.data.frame(get('subnat_all'))) {
subnat_all <- rbind(subnat_all, geo)
} else {
subnat_all <- geo
}
}
st_write(subnat_all, paste0(wd_path,'/data/dhs_geographies.geojson'), delete_dsn = TRUE)
} else {
subnat_all <- st_read(paste0(wd_path,'/data/dhs_geographies.geojson'))
}
# Throw an error if DHS geographies are missing for a survey in survey_list
stopifnot(setequal(survey_list, subnat_all %>% st_drop_geometry() %>% select(SurveyId) %>% unique() %>% pull()))
# Join DHS data and DHS region boundaries
if (!file.exists(paste0(wd_path,'/data/dhs_all_wide.geojson'))) {
# subnat_all_wide <- st_read(paste0(wd_path,'/data/dhs_all_wide.geojson'))
subnat_all_wide <- subnat_all %>%
left_join(., subnat_wide, by = c('SurveyId'='SurveyId','REG_ID'='RegionId')) %>%
filter(!is.na(DHS_CountryCode)) %>%
select(-any_of(c('REGNOTES', 'CNTRYNAMEF', 'CNTRYNAMES', 'DHSREGFR', 'DHSREGSP'))) %>%
left_join(., meta_countryids %>% select(ISO2_CountryCode, ISO3_CountryCode) %>% distinct(),
by = c('ISO' = 'ISO2_CountryCode')) #%>%
# mutate(HC_WIXQ_P_LOW_2ND = HC_WIXQ_P_LOW + HC_WIXQ_P_2ND,
# HC_WIXQ_P_LOW_4TH = HC_WIXQ_P_LOW + HC_WIXQ_P_2ND + HC_WIXQ_P_MID + HC_WIXQ_P_4TH,
# HC_PPRM_H_37P = HC_PPRM_H_34P + HC_PPRM_H_56P + HC_PPRM_H_7PP,
# ED_EDAT_B_NED_PR = ED_EDAT_B_NED + ED_EDAT_B_SPR + ED_EDAT_B_CPR,
# ED_EDAT_B_SC = ED_EDAT_B_SSC + ED_EDAT_B_CSC)
sapply(subnat_all_wide , function(X) sum(is.na(X)))
st_write(subnat_all_wide, paste0(wd_path,'/data/dhs_all_wide.geojson'), delete_dsn = TRUE)
} else {
subnat_all_wide <- st_read(paste0(wd_path,'/data/dhs_all_wide.geojson'))
}
# Construct DHS region to MNP block crosswalk
if (!file.exists(paste0(wd_path,'/data/blocks_to_dhs.parquet'))) {
sf_use_s2(FALSE)
subnat_to_blocks <- purrr::map_dfr(.x = unique(subnat_all_wide$SurveyId), .f = function(i) {
print(i)
subnat_surveyid <- subnat_all_wide %>% filter(SurveyId == i) %>%
st_cast("POLYGON") %>% st_make_valid() %>%
select(ISO3_CountryCode,DHS_CountryCode,SurveyId,SurveyYear,REGCODE,REG_ID,REGNAME,CNTRYNAMEE,DHSREGEN)
country_iso <- subnat_surveyid %>% st_drop_geometry() %>% select(ISO3_CountryCode) %>% distinct() %>% pull()
# iso_blocks <- st_read_parquet(paste0('/Users/nm/Downloads/blocks/blocks_',country_iso,'.parquet')) %>%
# st_make_valid() %>% mutate(is_valid = st_is_valid(geometry)) %>%
# filter(is_valid == TRUE) %>% select(-any_of('is_valid'))
iso_blocks <- arrow::open_dataset(paste0('data/africa_geodata.parquet')) %>%
select(block_id, gadm_code, country_code, geometry) %>%
filter(country_code %in% c(country_iso)) %>%
read_sf_dataset() %>%
st_set_crs(4326) %>%
st_make_valid() # %>% mutate(is_valid = st_is_valid(geometry)) %>%
#filter(is_valid == TRUE) %>% select(-any_of('is_valid'))
print('within join')
iso_blocks_within <- iso_blocks %>%
st_join(., subnat_surveyid, join = st_within, left = FALSE)
print('intersect join')
iso_blocks_intersect <- iso_blocks %>%
filter(!(block_id %in% unique(iso_blocks_within$block_id))) %>%
st_join(., subnat_surveyid, largest = TRUE, left = FALSE)
iso_blocks_xwalk <- rbind(iso_blocks_within %>% st_drop_geometry(),
iso_blocks_intersect %>% st_drop_geometry())
})
write_parquet(subnat_to_blocks, paste0(wd_path,'/data/blocks_to_dhs.parquet'))
#write_csv(subnat_to_blocks, paste0(wd_path,'/data/blocks_to_dhs.csv'))
} else {
subnat_to_blocks <- read_parquet(paste0(wd_path,'/data/blocks_to_dhs.parquet'))
#subnat_to_blocks <- read_csv(paste0(wd_path,'/data/blocks_to_dhs.csv'))
}
# Aggregate MNP data to DHS regions using subnat_to_blocks crosswalk
if (!file.exists(paste0(wd_path,'/data/k_data_subnational.csv'))) {
k_data <- read_parquet(paste0('data/africa_data.parquet')) %>%
mutate(region_core_urban = case_when(class_urban_hierarchy == "1 - Core urban" ~ landscan_population_un, TRUE ~ as.numeric(0)),
region_peripheral_urban = case_when(class_urban_hierarchy == "2 - Peripheral urban" ~ landscan_population_un, TRUE ~ as.numeric(0)),
region_peri_urban = case_when(class_urban_hierarchy== "3 - Peri-urban" ~ landscan_population_un, TRUE ~ as.numeric(0)),
region_non_urban = case_when(class_urban_hierarchy == "4 - Non-urban" ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_1 = case_when(k_labels == '1' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_2 = case_when(k_labels == '2' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_3 = case_when(k_labels == '3' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_4 = case_when(k_labels == '4' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_5 = case_when(k_labels == '5' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_6 = case_when(k_labels == '6' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_7 = case_when(k_labels == '7' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_8 = case_when(k_labels == '8' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_9 = case_when(k_labels == '9' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_10plus = case_when(k_labels == '10+' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_off_network = case_when(k_labels == 'Off-network' ~ landscan_population_un, TRUE ~ as.numeric(0)))
agg_list <- c("region_core_urban", "region_peripheral_urban", "region_peri_urban", "region_non_urban", "k_complexity_average", "block_area_m2", "block_hectares", "block_area_km2", "block_perimeter_meters", "building_area_m2", "building_count", "parcel_count", "k_complexity", "landscan_population_un",
"population_k_1", "population_k_2", "population_k_3", "population_k_4", "population_k_5", "population_k_6", "population_k_7", "population_k_8", "population_k_9", "population_k_10plus", "population_off_network",
"bldg_area_count_bin_01_0.50__log10_3.2", "bldg_area_count_bin_02_0.75__log10_5.6", "bldg_area_count_bin_03_1.00__log10_10", "bldg_area_count_bin_04_1.25__log10_17.8", "bldg_area_count_bin_05_1.50__log10_31.6", "bldg_area_count_bin_06_1.75__log10_56.2", "bldg_area_count_bin_07_2.00__log10_100", "bldg_area_count_bin_08_2.25__log10_177.8", "bldg_area_count_bin_09_2.50__log10_316.2", "bldg_area_count_bin_10_2.75__log10_562.3", "bldg_area_count_bin_11_3.00__log10_1000", "bldg_area_count_bin_12_3.25__log10_1778.3", "bldg_area_count_bin_13_3.50__log10_3162.3", "bldg_area_count_bin_14_3.75__log10_5623.4", "bldg_area_count_bin_15_4.00__log10_10000", "bldg_area_m2_bin_01_0.50__log10_3.2", "bldg_area_m2_bin_02_0.75__log10_5.6", "bldg_area_m2_bin_03_1.00__log10_10", "bldg_area_m2_bin_04_1.25__log10_17.8", "bldg_area_m2_bin_05_1.50__log10_31.6", "bldg_area_m2_bin_06_1.75__log10_56.2", "bldg_area_m2_bin_07_2.00__log10_100", "bldg_area_m2_bin_08_2.25__log10_177.8", "bldg_area_m2_bin_09_2.50__log10_316.2", "bldg_area_m2_bin_10_2.75__log10_562.3", "bldg_area_m2_bin_11_3.00__log10_1000", "bldg_area_m2_bin_12_3.25__log10_1778.3", "bldg_area_m2_bin_13_3.50__log10_3162.3", "bldg_area_m2_bin_14_3.75__log10_5623.4", "bldg_area_m2_bin_15_4.00__log10_10000")
k_data_subnat <- subnat_to_blocks %>%
left_join(., k_data, by = c('block_id'='block_id')) %>%
mutate(k_complexity_average = k_complexity*landscan_population_un) %>%
group_by(REG_ID, DHS_CountryCode, SurveyId) %>%
summarize_at(vars(all_of(agg_list)), list(sum)) %>%
ungroup() %>%
mutate(k_complexity_average = k_complexity_average/landscan_population_un)
rm(k_data)
gc()
write_csv(k_data_subnat, paste0(wd_path,'/data/k_data_subnational.csv'))
} else {
k_data_subnat <- read_csv(paste0(wd_path,'/data/k_data_subnational.csv'))
}
}
# Load UN Data Sources ---------------------------------------------------------
if (load_saved == FALSE) {
# Urban Population Living in Slums by Country or Area 2000-2020
un_slums <- read_csv(paste0('data/un-habitat/urban_population_in_slums_2020.csv')) %>%
filter(!is.na(country_code)) %>%
mutate(percent_2020_coalesced = coalesce(percent_2020, percent_2018, percent_2016, percent_2014),
percent_2020_coalesced = percent_2020_coalesced/100) %>%
select(country_code, percent_2020_coalesced)
# Population with Improved Water, Improved Sanitation and Other Urban Basic Services in Cities, Selected Countries (Percent)
# https://data.unhabitat.org/pages/access-to-basic-services-in-cities-and-urban-areas
un_services_cities <- read_xlsx(path = paste0('data/un-habitat/population_with_services_city.xlsx'), sheet = 'data')%>%
select_all(~gsub("\\s+|\\.|\\/|,|\\*|-", "_", .)) %>%
rename_all(list(tolower)) %>% filter(m49class %in% c('Sub-Saharan Africa','Western Asia and Northern Africa')) %>%
group_by(country, city_region) %>%
mutate(most_recent = row_number(desc(year))) %>%
ungroup() %>%
filter(most_recent == 1) %>%
mutate(city_region_id = paste0(tolower(str_replace_all(iconv(country, from = 'UTF-8', to = 'ASCII//TRANSLIT'), "[[:punct:]]|\\s+", "_")),'_::_',
tolower(str_replace_all(iconv(city_region, from = 'UTF-8', to = 'ASCII//TRANSLIT'), "[[:punct:]]|\\s+", "_")))) %>%
mutate(match_code = case_when( city_region_id == 'angola_::_luanda' ~ 'ghsl_3050', city_region_id == 'benin_::_cotonou' ~ 'ghsl_2078',
city_region_id == 'benin_::_djouguo' ~ 'ghsl_2354', city_region_id == 'benin_::_porto_novo' ~ 'ghsl_2101',
city_region_id == 'botswana_::_francistown' ~ 'ghsl_3706', city_region_id == 'botswana_::_gaborone' ~ 'ghsl_3587',
city_region_id == 'burkina_faso_::_ouagadougou' ~ 'ghsl_1799', city_region_id == 'burundi_::_bujumbura' ~ 'ghsl_4078',
city_region_id == 'cameroon_::_bafoussam' ~ 'ghsl_2901', city_region_id == 'cameroon_::_douala' ~ 'ghsl_2850',
city_region_id == 'cameroon_::_garoua' ~ 'ghsl_3071', city_region_id == 'cameroon_::_yaound_e' ~ 'ghsl_2961',
city_region_id == 'central_african_republic_::_bangui' ~ 'ghsl_3363', city_region_id == 'chad_::_n_djam_ena' ~ 'ghsl_3186',
city_region_id == 'comoros_::_moroni' ~ 'ghsl_5588',
#city_region_id == 'congo_::_brazaville' ~ 'ghsl_3211', city_region_id == 'gabon_::_libreville' ~ 'ghsl_2834',
city_region_id == 'congo_::_brazzaville' ~ 'ghsl_3211', city_region_id == 'gabon_::_libreville_port_gentil' ~ 'ghsl_2834',
city_region_id == 'congo_drc_::_kinshasa' ~ 'ghsl_3209', city_region_id == 'cote_d_ivoire_::_abidjan' ~ 'ghsl_1675',
city_region_id == 'ethiopia_::_addis_ababa' ~ 'ghsl_5134', city_region_id == 'ethiopia_::_awasa' ~ 'ghsl_5126',
city_region_id == 'ethiopia_::_gonder' ~ 'ghsl_4847', city_region_id == 'ethiopia_::_mekele' ~ 'ghsl_5210', city_region_id == 'ethiopia_::_nazret' ~ 'ghsl_5246',
city_region_id == 'gambia_::_banjul' ~ 'ghsl_1455', city_region_id == 'ghana_::_accra' ~ 'ghsl_1910',
city_region_id == 'ghana_::_kumasi' ~ 'ghsl_1785', city_region_id == 'ghana_::_takoradi' ~ 'ghsl_1779',
city_region_id == 'guinea_::_bok_e' ~ 'ghsl_1497', city_region_id == 'guinea_::_conakry' ~ 'ghsl_1502',
city_region_id == 'guinea_::_faranah' ~ 'ghsl_1527', city_region_id == 'guinea_::_kankan' ~ 'ghsl_1539',
city_region_id == 'guinea_::_kindia' ~ 'ghsl_1512', city_region_id == 'guinea_::_lab_e' ~ 'ghsl_1515',
city_region_id == 'guinea_::_mamou' ~ 'ghsl_1518', city_region_id == 'guinea_::_n_z_er_ekor_e' ~ 'ghsl_1545',
city_region_id == 'guinea_bissau_::_bafat_a' ~ 'ghsl_1492', city_region_id == 'guinea_bissau_::_gab_u' ~ 'ghsl_1498',
city_region_id == 'guinea_bissau_::_sab' ~ 'ghsl_1477', city_region_id == 'kenya_::_kisumu' ~ 'ghsl_4608',
city_region_id == 'kenya_::_mombasa' ~ 'ghsl_5329', city_region_id == 'kenya_::_nairobi' ~ 'ghsl_4808',
city_region_id == 'kenya_::_nakuru' ~ 'ghsl_4729', city_region_id == 'lesotho_::_maseru' ~ 'ghsl_3631',
city_region_id == 'liberia_::_monrovia' ~ 'ghsl_1526', city_region_id == 'madagascar_::_antananarivo' ~ 'ghsl_5792',
city_region_id == 'malawi_::_blantyre' ~ 'ghsl_4558', city_region_id == 'malawi_::_lilongwe' ~ 'ghsl_4495',
city_region_id == 'malawi_::_mzuzu_city' ~ 'ghsl_4526', city_region_id == 'malawi_::_zomba_city' ~ 'ghsl_4589',
city_region_id == 'mali_::_bamako' ~ 'ghsl_1553', city_region_id == 'mauritania_::_nouakchott' ~ 'ghsl_1474',
city_region_id == 'mozambique_::_maputo' ~ 'ghsl_4220', city_region_id == 'namibia_::_windhoek' ~ 'ghsl_3260',
city_region_id == 'niger_::_niamey' ~ 'ghsl_2067', city_region_id == 'nigeria_::_abuja' ~ 'ghsl_2565',
city_region_id == 'nigeria_::_akure' ~ 'ghsl_2312', city_region_id == 'nigeria_::_damaturu' ~ 'ghsl_2981',
city_region_id == 'nigeria_::_effon_alaiye' ~ 'ghsl_2284', city_region_id == 'nigeria_::_ibadan' ~ 'ghsl_2189',
city_region_id == 'nigeria_::_kano' ~ 'ghsl_2717', city_region_id == 'nigeria_::_lagos' ~ 'ghsl_2125',
city_region_id == 'nigeria_::_zaria' ~ 'ghsl_2625', city_region_id == 'rwanda_::_kigali' ~ 'ghsl_4172',
city_region_id == 's~ao_tom_e_and_pr_incipe_::_s~ao_tom_e' ~ 'ghsl_2485', city_region_id == 'senegal_::_dakar' ~ 'ghsl_1452',
city_region_id == 'sierra_leone_::_freetown' ~ 'ghsl_1507', city_region_id == 'south_africa_::_capetown' ~ 'ghsl_3268',
city_region_id == 'south_africa_::_durban' ~ 'ghsl_3868', city_region_id == 'south_africa_::_port_elizabeth' ~ 'ghsl_3505',
city_region_id == 'south_africa_::_pretoria' ~ 'ghsl_3698', city_region_id == 'south_africa_::_west_rand' ~ 'ghsl_3673',
city_region_id == 'eswatini_::_manzini' ~ 'ghsl_4080', city_region_id == 'tanzania_::_arusha' ~ 'ghsl_4800',
city_region_id == 'tanzania_::_dar_es_salaam' ~ 'ghsl_5222', city_region_id == 'togo_::_lom_e' ~ 'ghsl_2020',
city_region_id == 'uganda_::_kampala' ~ 'ghsl_4427', city_region_id == 'zambia_::_chingola' ~ 'ghsl_3786',
city_region_id == 'zambia_::_lusaka' ~ 'ghsl_3798', city_region_id == 'zambia_::_ndola' ~ 'ghsl_3859',
city_region_id == 'zimbabwe_::_bulawayo' ~ 'ghsl_3777', city_region_id == 'zimbabwe_::_harare' ~ 'ghsl_4171',
TRUE ~ as.character(''))) %>%
filter(match_code != '')
agg_list <- c("k_complexity_average", "block_area_m2", "block_hectares", "block_area_km2", "block_perimeter_meters", "building_area_m2", "building_count", "parcel_count", "k_complexity", "landscan_population_un", "population_k_1", "population_k_2", "population_k_3", "population_k_4", "population_k_5", "population_k_6", "population_k_7", "population_k_8", "population_k_9", "population_k_10plus", "population_off_network", "bldg_area_count_bin_01_0.50__log10_3.2", "bldg_area_count_bin_02_0.75__log10_5.6", "bldg_area_count_bin_03_1.00__log10_10", "bldg_area_count_bin_04_1.25__log10_17.8", "bldg_area_count_bin_05_1.50__log10_31.6", "bldg_area_count_bin_06_1.75__log10_56.2", "bldg_area_count_bin_07_2.00__log10_100", "bldg_area_count_bin_08_2.25__log10_177.8", "bldg_area_count_bin_09_2.50__log10_316.2", "bldg_area_count_bin_10_2.75__log10_562.3", "bldg_area_count_bin_11_3.00__log10_1000", "bldg_area_count_bin_12_3.25__log10_1778.3", "bldg_area_count_bin_13_3.50__log10_3162.3", "bldg_area_count_bin_14_3.75__log10_5623.4", "bldg_area_count_bin_15_4.00__log10_10000", "bldg_area_m2_bin_01_0.50__log10_3.2", "bldg_area_m2_bin_02_0.75__log10_5.6", "bldg_area_m2_bin_03_1.00__log10_10", "bldg_area_m2_bin_04_1.25__log10_17.8", "bldg_area_m2_bin_05_1.50__log10_31.6", "bldg_area_m2_bin_06_1.75__log10_56.2", "bldg_area_m2_bin_07_2.00__log10_100", "bldg_area_m2_bin_08_2.25__log10_177.8", "bldg_area_m2_bin_09_2.50__log10_316.2", "bldg_area_m2_bin_10_2.75__log10_562.3", "bldg_area_m2_bin_11_3.00__log10_1000", "bldg_area_m2_bin_12_3.25__log10_1778.3", "bldg_area_m2_bin_13_3.50__log10_3162.3", "bldg_area_m2_bin_14_3.75__log10_5623.4", "bldg_area_m2_bin_15_4.00__log10_10000")
urban_k <- read_parquet(paste0(wd_input,'/africa_data.parquet')) %>%
filter(class_urban_hierarchy %in% c("1 - Core urban", "2 - Peripheral urban", "3 - Peri-urban")) %>%
mutate(population_k_1 = case_when(k_labels == '1' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_2 = case_when(k_labels == '2' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_3 = case_when(k_labels == '3' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_4 = case_when(k_labels == '4' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_5 = case_when(k_labels == '5' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_6 = case_when(k_labels == '6' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_7 = case_when(k_labels == '7' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_8 = case_when(k_labels == '8' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_9 = case_when(k_labels == '9' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_10plus = case_when(k_labels == '10+' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_off_network = case_when(k_labels == 'Off-network' ~ landscan_population_un, TRUE ~ as.numeric(0))) %>%
mutate(k_complexity_average = k_complexity*landscan_population_un) %>%
group_by(country_code) %>%
summarize_at(vars(all_of(agg_list)), list(sum)) %>% # , na.rm = TRUE
ungroup() %>%
mutate(k_complexity_average = k_complexity_average/landscan_population_un)
un_slums_k <- un_slums %>%
left_join(., urban_k, by = c('country_code'='country_code'))
city_k <- read_parquet(paste0('data/africa_data.parquet')) %>%
mutate(population_k_1 = case_when(k_labels == '1' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_2 = case_when(k_labels == '2' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_3 = case_when(k_labels == '3' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_4 = case_when(k_labels == '4' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_5 = case_when(k_labels == '5' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_6 = case_when(k_labels == '6' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_7 = case_when(k_labels == '7' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_8 = case_when(k_labels == '8' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_9 = case_when(k_labels == '9' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_k_10plus = case_when(k_labels == '10+' ~ landscan_population_un, TRUE ~ as.numeric(0)),
population_off_network = case_when(k_labels == 'Off-network' ~ landscan_population_un, TRUE ~ as.numeric(0))) %>%
mutate(k_complexity_average = k_complexity*landscan_population_un) %>%
group_by(urban_id, urban_center_name, urban_country_name) %>%
summarize_at(vars(all_of(agg_list)), list(sum), na.rm = TRUE) %>%
ungroup() %>%
mutate(k_complexity_average = k_complexity_average/landscan_population_un)
un_services_cities_k <- city_k %>%
inner_join(., un_services_cities,
by = c('urban_id'='match_code')) %>%
filter(!is.nan(k_complexity_average)) %>%
#select(urban_id, urban_center_name, country_name, region, m49class, country, city_region, city_region_id, year, number_of_cases, total_improved_water , access_to_basic_drinking_water_services , total_improved_sanitation , access_to_basic_sanitation_services , basic_hand_washing_facility , durable_housing_durable_floor_material , durable_housing_durable_wall_material , durable_housing_durable_roof_material , sufficient_living_area , other_basic_services_telephone , other_basic_services_mobile_phone , other_basic_services_electricity , type_of_main_cooking_fuel_clean_fuel_total_clean_fuel , solid_fuel , source, most_recent, k_complexity_average, landscan_population_un, population_k_1, population_k_2, population_k_3, population_k_4, population_k_5, population_k_6, population_k_7, population_k_8, population_k_9, population_k_10plus, population_off_network) %>%
#drop_na(total_improved_water, total_improved_sanitation, access_to_basic_drinking_water_services, access_to_basic_sanitation_services, durable_housing_durable_floor_material, durable_housing_durable_wall_material, sufficient_living_area, other_basic_services_electricity, type_of_main_cooking_fuel_clean_fuel_total_clean_fuel, solid_fuel) %>%
#drop_na(improved_water_sources_piped_water_sources_piped_water, improved_water_sources_piped_water_sources_public_tap, improved_water_sources_piped_water_sources_total_piped, improved_water_sources_non_piped_water_sources_borehole_tubewell, improved_water_sources_non_piped_water_sources_protected_well, improved_water_sources_non_piped_water_sources_protected_spring, improved_water_sources_non_piped_water_sources_rainwater, improved_water_sources_non_piped_water_sources_delivered_water, improved_water_sources_non_piped_water_sources_packaged_water, improved_water_sources_non_piped_water_sources_total_non_piped, total_improved_water, access_to_basic_drinking_water_services, improved_sanitation_facilities_sewered_facilities_connection_to_sewerage, improved_sanitation_facilities_non_sewered_facilities_vip_toilet_facility, improved_sanitation_facilities_non_sewered_facilities_flush_septic, improved_sanitation_facilities_non_sewered_facilities_flush_to_pit_latrine, improved_sanitation_facilities_non_sewered_facilities_pit_latrine_with_slab, improved_sanitation_facilities_non_sewered_facilities_total_non_sewered, total_improved_sanitation, access_to_basic_sanitation_services, durable_housing_durable_floor_material, durable_housing_durable_wall_material, durable_housing_durable_roof_material, sufficient_living_area, other_basic_services_mobile_phone, other_basic_services_electricity, type_of_main_cooking_fuel_clean_fuel_electricity, type_of_main_cooking_fuel_clean_fuel_lpg_natural_gas, type_of_main_cooking_fuel_clean_fuel_total_clean_fuel, solid_fuel) %>%
filter(#landscan_population_un >= 200000,
year >= 2010)
write_csv(urban_k, paste0(wd_path,'/data/aggregated_urban_k.csv'))
write_csv(un_slums_k, paste0(wd_path,'/data/un_slums_k.csv'))
write_csv(city_k, paste0(wd_path,'/data/aggregated_city_k.csv'))
write_csv(un_services_cities_k, paste0(wd_path,'/data/un_services_cities_k.csv'))
}
# -------------------------------------------------------------------------
# Analyze data ------------------------------------------------------------
# Join k data and DHS data
subnat_all_wide_k <- subnat_all_wide %>%
filter(SurveyId != 'SN2020MIS') %>% # survey with many missing
inner_join(., k_data_subnat, by = c('REG_ID'='REG_ID','SurveyId'='SurveyId','DHS_CountryCode'='DHS_CountryCode'))
# indicators_list_wide <- c('FP_NADM_W_UNT', 'FP_NADM_W_MNT', 'CM_ECMR_C_NNR', 'CM_ECMR_C_PNR', 'CM_ECMR_C_IMR', 'CM_ECMR_C_CMR', 'CM_ECMR_C_U5M', 'RH_DELP_C_DHF', 'CH_VACC_C_DP1', 'CH_VACC_C_DP2', 'CH_VACC_C_BAS', 'CH_VACC_C_AP2', 'CH_ARIS_C_ADV', 'CH_DIAR_C_DIA', 'CN_NUTS_C_HA3', 'CN_NUTS_C_HA2', 'CN_NUTS_C_WH3', 'CN_NUTS_C_WH2', 'CN_NUTS_C_WA3', 'CN_NUTS_C_WA2', 'CN_IYCF_C_4FA', 'CN_IYCF_C_MNA', 'CN_ANMC_C_ANY', 'ML_NETP_H_ITN', 'ML_NETP_H_IT2', 'ML_ITNA_P_ACC', 'ML_NETU_P_IT1', 'ML_NETC_C_IT1', 'ML_NETW_W_IT1', 'CO_MOBB_W_MOB', 'ED_EDAT_W_NED', 'ED_EDAT_W_SPR', 'ED_EDAT_W_CPR', 'ED_EDAT_W_SSC', 'ED_EDAT_W_CSC', 'ED_EDAT_W_HGH', 'ED_EDAT_W_PRI', 'ED_EDAT_W_SEC', 'ED_EDAT_W_MYR', 'ED_EDAT_M_PRI', 'ED_EDAT_M_SEC', 'ED_EDAT_M_MYR', 'ED_EDAT_B_NED', 'ED_EDAT_B_SPR', 'ED_EDAT_B_CPR', 'ED_EDAT_B_SSC', 'ED_EDAT_B_CSC', 'ED_EDAT_B_HGH', 'ED_EDAT_B_PRI', 'ED_EDAT_B_SEC', 'ED_EDAT_B_MYR', 'ED_NARP_W_FEM', 'ED_NARP_M_MAL', 'ED_NARP_B_BTH', 'ED_NARP_B_GPI', 'ED_GARP_B_GPI', 'ED_NARS_W_FEM', 'ED_NARS_M_MAL', 'ED_NARS_B_BTH', 'ED_NARS_B_GPI', 'ED_GARS_B_GPI', 'ED_EDUC_W_PRI', 'ED_ED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LN', 'HC_CKFL_P_SLD', 'HC_ELEC_P_ELC', 'HC_ELEC_P_NEL', 'HC_FLRM_P_ETH', 'HC_FLRM_P_NAT', 'WS_HNDW_H_BAS', 'WS_HNDW_H_SOP', 'WS_TLOC_H_DWL', 'WS_TLET_H_BAS', 'WS_TLET_H_IMP', 'WS_TLET_H_NFC', 'WS_SRCE_H_BAS', 'WS_SRCE_H_IMP', 'WS_SRCE_H_IOP', 'WS_SRCE_H_LTD', 'WS_SRCE_H_NIM', 'WS_SRCE_H_PIP', 'WS_TIME_H_L30', 'WS_TIME_H_M30', 'WS_TIME_H_ONP', 'HC_CKPL_H_HSE', 'HC_CKFL_H_CLN', 'HC_CKFL_H_SLD', 'HC_ELEC_H_ELC', 'HC_ELEC_H_NEL', 'HC_FLRM_H_ETH', 'HC_FLRM_H_NAT')
subnat_all_wide_k %>% st_drop_geometry() %>%
select(DHSREGEN, REGCODE, CountryName, DHS_CountryCode) %>% distinct() %>% nrow()
subnat_all_wide_k %>% st_drop_geometry() %>%
select(CountryName, DHS_CountryCode) %>% distinct() %>% nrow()
subnat_all_wide_k %>% st_drop_geometry() %>%
select(SurveyId) %>% distinct() %>% nrow()
subnat_all_wide_k %>% st_drop_geometry() %>%
select(SVYYEAR) %>% distinct()
# 238 administrative regions across 22 countries and 40 unique surveys taking place between 2010 and 2021, producing 367 unique survey observations
subnat_all_wide_k <- subnat_all_wide_k %>% filter(!is.na(k_complexity)) %>%
mutate(population_k_1_3 = population_k_1 + population_k_2 + population_k_3,
population_k_4_plus = population_k_4 + population_k_5 + population_k_6 + population_k_7 + population_k_8 + population_k_9 + population_k_10plus + population_off_network) %>%
mutate(across(all_of(indicators_list_wide), .fns = ~./100)) %>%
mutate(region_non_urban_share = region_non_urban/(region_core_urban+region_peripheral_urban+region_peri_urban+region_non_urban))
# mutate(across(c(CM_ECMR_C_IMR, RH_DELP_C_DHF, ED_EDAT_B_NED, ED_EDAT_B_CPR, ED_EDAT_B_SSC, ED_EDAT_B_CSC, ED_EDAT_B_HGH, ED_EDAT_B_MYR, ED_LITR_W_LIT, WS_TIME_H_ONP, WS_TIME_P_ONP, WS_SRCE_H_IOP, WS_SRCE_P_IOP, WS_SRCE_P_IMP, WS_SRCE_H_BAS, WS_SRCE_P_BAS, WS_SRCE_H_LTD, WS_SRCE_P_LTD, WS_TLET_H_IMP, WS_TLET_P_IMP, WS_TLET_H_BAS, WS_TLET_H_LTD, WS_TLET_P_BAS, WS_TLET_P_LTD, HC_ELEC_H_ELC, HC_ELEC_P_ELC, HC_FLRM_H_NAT, HC_FLRM_P_NAT, HC_FLRM_H_ETH, HC_FLRM_P_ETH, HC_PPRM_H_12P, HC_PPRM_H_34P, HC_PPRM_H_56P, HC_PPRM_H_7PP, HC_PPRM_H_MNP, HC_WIXQ_P_LOW, HC_WIXQ_P_2ND, HC_WIXQ_P_MID, HC_WIXQ_P_4TH, HC_WIXQ_P_HGH, HC_WIXQ_P_LOW_2ND, HC_WIXQ_P_LOW_4TH, HC_WIXQ_P_LOW_2ND, HC_WIXQ_P_LOW_4TH, HC_PPRM_H_37P, ED_EDAT_B_NED_PR, ED_EDAT_B_SC),
# .fns = ~./100))
names(subnat_all_wide_k )
sapply(subnat_all_wide_k, function(X) sum(is.na(X)))
custom_labels <- list(
'column_var' = c('EM_OCCP_M_AGR', 'EM_OCCP_M_MNS', 'EM_OCCP_M_MNU', 'EM_OCCP_M_PRO', 'EM_OCCP_W_AGR', 'EM_OCCP_W_DOM', 'EM_OCCP_W_MNU', 'EM_OCCP_W_PRO', 'HC_WIXQ_P_LOW', 'HC_WIXQ_P_2ND', 'HC_WIXQ_P_MID', 'HC_WIXQ_P_4TH', 'HC_WIXQ_P_HGH', 'HC_WIXQ_P_GNI', 'HC_HEFF_H_CMP', 'HC_HEFF_H_FRG', 'HC_HEFF_H_MPH', 'HC_HEFF_H_TLV', 'HC_TRNS_H_CAR', 'ED_EDAT_B_MYR', 'ED_EDAT_M_MYR', 'ED_EDAT_W_MYR', 'ED_EDA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_SRCE_H_BAS', 'WS_SRCE_H_IMP', 'WS_SRCE_H_IOP', 'WS_SRCE_H_LTD', 'WS_SRCE_H_NIM', 'WS_SRCE_H_PIP', 'WS_TIME_H_L30', 'WS_TIME_H_M30', 'WS_TIME_H_ONP', 'HC_CKPL_H_HSE', 'HC_CKFL_H_CLN', 'HC_CKFL_H_SLD', 'HC_ELEC_H_ELC', 'HC_ELEC_H_NEL', 'HC_FLRM_H_ETH', 'HC_FLRM_H_NAT'),
'order' = c(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),
'positive_dim' = c(0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0),
'unit' = c('Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Households', 'Households', 'Households', 'Households', 'Households', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Population', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households', 'Households'),
'household_duplicate' = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
'category' = c("Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Economic Wellbeing", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Education and Literacy", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Children and Women's Health", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Water, Sanitation and Hygiene", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics", "Household Characteristics"),
'subcategory' = c("Livelihoods", "Livelihoods", "Livelihoods", "Livelihoods", "Livelihoods", "Livelihoods", "Livelihoods", "Livelihoods", "Wealth", "Wealth", "Wealth", "Wealth", "Wealth", "Wealth", "Household effects", "Household effects", "Household effects", "Household effects", "Household effects", "Education", "Education", "Education", "Education", "Education", "Education", "Education", "Education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's education", "Women's health", "Women's health", "Women's health", "Children's health", "Children's health", "Children's health", "Children's health", "Children's health", "Children's health", "Children's health", "Children's health", "Children's health", "Children's health", "Handwashing", "Handwashing", "Sanitation", "Sanitation", "Sanitation", "Sanitation", "Water", "Water", "Water", "Water", "Water", "Water", "Water", "Water", "Water", "Crowding", "Crowding", "Crowding", "Crowding", "Crowding", "Crowding", "Cooking", "Cooking", "Cooking", "Electricity", "Electricity", "Floor materials", "Floor materials", "Handwashing", "Handwashing", "Sanitation", "Sanitation", "Sanitation", "Sanitation", "Water", "Water", "Water", "Water", "Water", "Water", "Water", "Water", "Water", "Cooking", "Cooking", "Cooking", "Electricity", "Electricity", "Floor materials", "Floor materials")
) %>% as_tibble()
dhs_dict_df <- dhs_indicators() %>%
select(Definition, MeasurementType, ShortName, IndicatorId, Level1, Level2, Level3, Label) %>%
rename_all(list(tolower)) %>%
relocate(indicatorid, definition, label, level1, level2, level3, shortname, measurementtype) %>%
left_join(., custom_labels, by = c('indicatorid' = 'column_var')) %>%
filter(!is.na(order)) %>%
arrange(order)
# Correlations table ------------------------------------------------------
streets_dhs_regions <- read_csv('data/streets_dhs_regions.csv') %>%
mutate(vehicular_highway_km = highway_length_meters*0.001,
region_area_km2 = region_area_m2*1e-6,
street_density_ratio_km_to_km2 = vehicular_highway_km/region_area_km2)
subnat_all_wide_k <- subnat_all_wide_k %>%
left_join(., streets_dhs_regions %>% select(REG_ID, street_density_ratio_km_to_km2),
by = c('REG_ID'='REG_ID'))
# DHS subnational data vs population weighted K
(cor_dhs <- rcorr(subnat_all_wide_k %>% st_drop_geometry() %>%
select_at(c('k_complexity_average', indicators_list_wide)) %>%
relocate(all_of(c('k_complexity_average', indicators_list_wide))) %>% as.matrix(),
#select(k_complexity_average, CM_ECMR_C_IMR, RH_DELP_C_DHF, ED_EDAT_B_NED, ED_EDAT_B_CPR, ED_EDAT_B_SSC, ED_EDAT_B_CSC, ED_EDAT_B_HGH, ED_EDAT_B_MYR, ED_LITR_W_LIT, WS_TIME_H_ONP, WS_TIME_P_ONP, WS_SRCE_H_IOP, WS_SRCE_P_IOP, WS_SRCE_P_IMP, WS_SRCE_H_BAS, WS_SRCE_P_BAS, WS_SRCE_H_LTD, WS_SRCE_P_LTD, WS_TLET_H_IMP, WS_TLET_P_IMP, WS_TLET_H_BAS, WS_TLET_H_LTD, WS_TLET_P_BAS, WS_TLET_P_LTD, HC_ELEC_H_ELC, HC_ELEC_P_ELC, HC_FLRM_H_NAT, HC_FLRM_P_NAT, HC_FLRM_H_ETH, HC_FLRM_P_ETH, HC_PPRM_H_12P, HC_PPRM_H_34P, HC_PPRM_H_56P, HC_PPRM_H_7PP, HC_PPRM_H_MNP, HC_WIXQ_P_LOW, HC_WIXQ_P_2ND, HC_WIXQ_P_MID, HC_WIXQ_P_4TH, HC_WIXQ_P_HGH, HC_WIXQ_P_LOW_2ND, HC_WIXQ_P_LOW_4TH, HC_WIXQ_P_GNI) %>% as.matrix(),
type=c('spearman')) %>% tidy() %>% filter(column2 == 'k_complexity_average') %>%
inner_join(., dhs_dict_df , by = c('column1' = 'indicatorid')) %>%
rename(column_var = column1) %>%
select(column_var, category, subcategory, definition, label, estimate, n, p.value, level1, level2, level3, shortname, measurementtype, order, positive_dim, unit, household_duplicate) %>%
arrange(order) %>%
mutate(universe = 'Regions', source = 'DHS') %>% as.data.frame() %>%
rename(column_label = definition))
(cor_dhs_2 <- rcorr(subnat_all_wide_k %>% st_drop_geometry() %>%
select_at(c('street_density_ratio_km_to_km2', indicators_list_wide)) %>%
relocate(all_of(c('street_density_ratio_km_to_km2', indicators_list_wide))) %>% as.matrix(),
type=c('spearman')) %>% tidy() %>% filter(column2 == 'street_density_ratio_km_to_km2') %>%
inner_join(., dhs_dict_df, by = c('column1' = 'indicatorid')) %>%
select(column1, estimate, n, p.value) %>%
rename(column_var = column1,
estimate_street_density = estimate,
n_street_density = n,
p.value_street_density = p.value))
(cor_dhs_log <- rcorr(subnat_all_wide_k %>% st_drop_geometry() %>%
select_at(c('k_complexity_average', indicators_list_wide)) %>%
relocate(all_of(c('k_complexity_average', indicators_list_wide))) %>%
mutate_all(log) %>%
mutate_all(function(x) ifelse(is.infinite(x), 0, x)) %>%
mutate_all(function(x) ifelse(is.na(x), 0, x)) %>%
mutate_all(function(x) ifelse(is.nan(x), 0, x)) %>%
as.matrix(),
type=c('spearman')) %>% tidy() %>% filter(column2 == 'k_complexity_average') %>%
inner_join(., dhs_dict_df, by = c('column1' = 'indicatorid')) %>%
select(column1, estimate, n, p.value) %>%
rename(column_var = column1,
log_v_log_k_complexity = estimate,
n_log_v_log_k_complexity = n,
p.value_log_v_log_k_complexity = p.value))
(cor_dhs_urban <- rcorr(subnat_all_wide_k %>% st_drop_geometry() %>%
filter(region_non_urban_share < .5) %>%
select_at(c('k_complexity_average', indicators_list_wide)) %>%
relocate(all_of(c('k_complexity_average', indicators_list_wide))) %>% as.matrix(),
#select(k_complexity_average, CM_ECMR_C_IMR, RH_DELP_C_DHF, ED_EDAT_B_NED, ED_EDAT_B_CPR, ED_EDAT_B_SSC, ED_EDAT_B_CSC, ED_EDAT_B_HGH, ED_EDAT_B_MYR, ED_LITR_W_LIT, WS_TIME_H_ONP, WS_TIME_P_ONP, WS_SRCE_H_IOP, WS_SRCE_P_IOP, WS_SRCE_P_IMP, WS_SRCE_H_BAS, WS_SRCE_P_BAS, WS_SRCE_H_LTD, WS_SRCE_P_LTD, WS_TLET_H_IMP, WS_TLET_P_IMP, WS_TLET_H_BAS, WS_TLET_H_LTD, WS_TLET_P_BAS, WS_TLET_P_LTD, HC_ELEC_H_ELC, HC_ELEC_P_ELC, HC_FLRM_H_NAT, HC_FLRM_P_NAT, HC_FLRM_H_ETH, HC_FLRM_P_ETH, HC_PPRM_H_12P, HC_PPRM_H_34P, HC_PPRM_H_56P, HC_PPRM_H_7PP, HC_PPRM_H_MNP, HC_WIXQ_P_LOW, HC_WIXQ_P_2ND, HC_WIXQ_P_MID, HC_WIXQ_P_4TH, HC_WIXQ_P_HGH, HC_WIXQ_P_LOW_2ND, HC_WIXQ_P_LOW_4TH, HC_WIXQ_P_GNI) %>% as.matrix(),
type=c('spearman')) %>% tidy() %>% filter(column2 == 'k_complexity_average') %>%
inner_join(., dhs_dict_df, by = c('column1' = 'indicatorid')) %>%
rename(column_var = column1) %>%
as.data.frame() %>%
select(column_var, estimate, n, p.value) %>%
rename(estimate_urban = estimate,
n_urban = n,
p.value_urban = p.value))
(cor_dhs_urban_2 <- rcorr(subnat_all_wide_k %>% st_drop_geometry() %>%
filter(region_non_urban_share < .5) %>%
select_at(c('street_density_ratio_km_to_km2', indicators_list_wide)) %>%
relocate(all_of(c('street_density_ratio_km_to_km2', indicators_list_wide))) %>% as.matrix(),
type=c('spearman')) %>% tidy() %>% filter(column2 == 'street_density_ratio_km_to_km2') %>%
inner_join(., dhs_dict_df, by = c('column1' = 'indicatorid')) %>%
rename(column_var = column1) %>%
as.data.frame() %>%
select(column_var, estimate, n, p.value) %>%
rename(estimate_urban_street_density = estimate,
n_urban_street_density = n,
p.value_urban_street_density = p.value))
(cor_dhs <- cor_dhs %>%
left_join(., cor_dhs_urban, by = c('column_var' = 'column_var')) %>%
left_join(., cor_dhs_2, by = c('column_var' = 'column_var')) %>%
left_join(., cor_dhs_urban_2, by = c('column_var' = 'column_var')) %>%
left_join(., cor_dhs_log, by = c('column_var' = 'column_var')) %>%
relocate(column_var, category, subcategory, column_label, label, estimate, n, p.value, estimate_urban, n_urban, p.value_urban))
(cor_dhs_trim <- cor_dhs %>%
filter(household_duplicate == 0))
cor_dhs_trim <- cor_dhs_trim %>%
mutate(larger_coefficient = case_when(abs(estimate_street_density) > abs(estimate) ~ 'Street density', TRUE ~ as.character('k-complexity')),
larger_coefficient_urban = case_when(abs(estimate_urban_street_density) > abs(estimate_urban) ~ 'Street density', TRUE ~ as.character('k-complexity')),
larger_coefficient_k_complexity = case_when(abs(estimate_street_density) < abs(estimate) ~ 1, TRUE ~ 0),
larger_coefficient_k_complexity_urban = case_when(abs(estimate_urban_street_density) < abs(estimate_urban) ~ 1, TRUE ~ 0),
larger_coefficient_street_density = case_when(abs(estimate_street_density) > abs(estimate) ~ 1, TRUE ~ 0),
larger_coefficient_street_density_urban = case_when(abs(estimate_urban_street_density) > abs(estimate_urban) ~ 1, TRUE ~ 0),
not_significant_street_density = case_when( p.value_street_density > .01 ~ 1, TRUE ~ 0),
not_significant_k_complexity = case_when(p.value > .01 ~ 1, TRUE ~ 0),
not_significant_street_density_urban = case_when( p.value_urban_street_density > .01 ~ 1, TRUE ~ 0),
not_significant_k_complexity_urban = case_when(p.value_urban > .01 ~ 1, TRUE ~ 0),
indicator_count = 1)
(insig_street_density <- cor_dhs_trim %>% filter(not_significant_street_density == 1) %>%
filter(p.value_street_density >= .05) %>%
select(subcategory, label, estimate_street_density, n_street_density, p.value_street_density))
(cor_summary_streets_v_k <- cor_dhs_trim %>% summarize_at(vars(indicator_count,
larger_coefficient_k_complexity, larger_coefficient_street_density,
not_significant_street_density, not_significant_k_complexity,
larger_coefficient_k_complexity_urban, larger_coefficient_street_density_urban,
not_significant_street_density_urban, not_significant_k_complexity_urban), list(sum)) %>%
pivot_longer(cols = everything()) %>%
mutate(share = value / nrow(cor_dhs_trim)))
#cor_dhs %>% select(label, estimate, n, p.value, level1, level2, column_var) %>% as_tibble() %>% print(n = 200)
# write_csv(cor_dhs %>% as_tibble(),
# '/Users/nm/Desktop/dhs_corr.csv')
# Urban Population Living in Slums by Country 2018 vs population weighted K
(cor_unslums <- rcorr(un_slums_k %>% select(k_complexity_average, percent_2020_coalesced) %>% as.matrix(),
type=c('spearman')) %>% tidy() %>%
rename(column_var = column1) %>% select(column_var, estimate, n, p.value) %>%
mutate(column_label = case_when(column_var == 'percent_2020_coalesced' ~ "Proportion of country's urban population living in slum households",
TRUE ~ as.character('')),
universe = 'Urban areas',
source = 'UN-Habitat') %>% as.data.frame())
# UN Habitat Services Data vs population weighted K (at city level)
(cor_unhab_1 <- rcorr(un_services_cities_k %>% select(k_complexity_average, improved_water_sources_non_piped_water_sources_total_non_piped, improved_sanitation_facilities_non_sewered_facilities_total_non_sewered, solid_fuel, improved_water_sources_piped_water_sources_piped_water, improved_sanitation_facilities_sewered_facilities_connection_to_sewerage, type_of_main_cooking_fuel_clean_fuel_total_clean_fuel) %>% as.matrix(),
type=c('spearman')) %>%
tidy() %>% filter(column2 == 'k_complexity_average') %>%
rename(column_var = column1) %>%
select(column_var, estimate, n, p.value) %>%
mutate(column_label = case_when(column_var == 'improved_water_sources_non_piped_water_sources_total_non_piped' ~ 'Percentage of population with non-piped water sources (borehole/tubewell, protected well/spring, delivered/packaged)', # (borehole, tubewell, protected well, protected spring, rainwater, delivered water, bottled and sached water)
column_var == 'improved_sanitation_facilities_non_sewered_facilities_total_non_sewered' ~ 'Percentage of population with non-sewered facilities (composting toilet, flush septic, pit latrines)', # (composting toilet, ventilated improved pit, flush septic, flush to pit latrine, pit latrine with slab)
column_var == 'solid_fuel' ~ 'Percentage of population with solid fuel (coal, lignite, charcoal, wood, straw, shrub, grass, etc.)',
column_var == 'improved_water_sources_piped_water_sources_piped_water' ~ 'Percentage of population with piped water into dwelling or plot (piped water, public tap)',
column_var == 'improved_sanitation_facilities_sewered_facilities_connection_to_sewerage' ~ 'Percentage of population with improved sanitation facilities with connection to sewerage',
column_var == 'type_of_main_cooking_fuel_clean_fuel_total_clean_fuel' ~ 'Percentage of population with clean fuel (electricity, LPG, natural gas, biogas)',
TRUE ~ as.character('')),
universe = 'Cities',
source = 'UN-Habitat') %>% as.data.frame() )
(cor_unhab_2 <- rcorr(un_services_cities_k %>% select(k_complexity_average,
durable_housing_durable_floor_material,
durable_housing_durable_roof_material,
other_basic_services_telephone,
other_basic_services_mobile_phone,
other_basic_services_electricity
#durable_housing_durable_wall_material, sufficient_living_area
) %>% as.matrix(),
type=c('spearman')) %>%
tidy() %>% filter(column2 == 'k_complexity_average') %>%
rename(column_var = column1) %>%
select(column_var, estimate, n, p.value) %>%
mutate(column_label = case_when(
column_var == 'durable_housing_durable_floor_material' ~ 'Percentage of population with durable floor material',
column_var == 'durable_housing_durable_roof_material' ~ 'Percentage of population with durable roof material',
column_var == 'other_basic_services_telephone' ~ 'Percentage of population with telephone',
column_var == 'other_basic_services_mobile_phone' ~ 'Percentage of population with mobile phone',
column_var == 'other_basic_services_electricity' ~ 'Percentage of population with electricity',
TRUE ~ as.character(''))) %>%
mutate(universe = 'Cities',
source = 'UN-Habitat') %>% as.data.frame() )
cor_un <- rbind(cor_unslums, cor_unhab_1, cor_unhab_2) %>%
mutate(p.value = round(p.value,8)) %>%
# mutate(column_group = case_when(
# column_var %in% c('HC_PPRM_H_12P', 'HC_PPRM_H_34P', 'HC_PPRM_H_56P', 'HC_PPRM_H_7PP', 'HC_PPRM_H_MNP') ~ 'Crowding',
# column_var %in% c('ED_EDAT_B_NED', 'ED_EDAT_B_CPR', 'ED_EDAT_B_SSC', 'ED_EDAT_B_CSC', 'ED_EDAT_B_HGH', 'ED_EDAT_B_MYR', 'ED_LITR_W_LIT') ~ 'Education',
# column_var %in% c('CM_ECMR_C_IMR', 'RH_DELP_C_DHF') ~ 'Health',
# column_var %in% c('HC_FLRM_H_NAT', 'HC_FLRM_P_NAT', 'HC_FLRM_H_ETH', 'HC_FLRM_P_ETH', 'solid_fuel', 'type_of_main_cooking_fuel_clean_fuel_total_clean_fuel', 'durable_housing_durable_floor_material', 'durable_housing_durable_roof_material') ~ 'Housing',
# column_var %in% c('WS_TLET_H_IMP', 'WS_TLET_P_IMP', 'WS_TLET_H_BAS', 'WS_TLET_H_LTD', 'WS_TLET_P_BAS', 'WS_TLET_P_LTD', 'improved_sanitation_facilities_non_sewered_facilities_total_non_sewered', 'improved_sanitation_facilities_sewered_facilities_connection_to_sewerage') ~ 'Sanitation',
# column_var %in% c('percent_2020_coalesced') ~ 'Slums',
# column_var %in% c('HC_ELEC_H_ELC', 'HC_ELEC_P_ELC', 'other_basic_services_telephone', 'other_basic_services_mobile_phone', 'other_basic_services_electricity') ~ 'Utilities',
# column_var %in% c('WS_TIME_H_ONP', 'WS_TIME_P_ONP', 'WS_SRCE_H_IOP', 'WS_SRCE_P_IOP', 'WS_SRCE_P_IMP', 'WS_SRCE_H_BAS', 'WS_SRCE_P_BAS', 'WS_SRCE_H_LTD', 'WS_SRCE_P_LTD', 'improved_water_sources_non_piped_water_sources_total_non_piped', 'improved_water_sources_piped_water_sources_piped_water') ~ 'Water',
# column_var %in% c('HC_WIXQ_P_LOW', 'HC_WIXQ_P_2ND', 'HC_WIXQ_P_MID', 'HC_WIXQ_P_4TH', 'HC_WIXQ_P_HGH', 'HC_WIXQ_P_LOW_2ND', 'HC_WIXQ_P_LOW_4TH', 'HC_WIXQ_P_GNI') ~ 'Wealth',
# TRUE ~ as.character(''))) %>%
relocate(column_label, estimate, p.value, n, universe, source, column_var)
cor_un %>% select(column_label, estimate, p.value, n, universe, source) %>% as_tibble() %>% print(n = 100, width = 200)
rm(cor_unslums, cor_unhab_1, cor_unhab_2)
write_excel_csv(cor_un, paste0(wd_path,'/data/dhs-analysis/data/correlations_table_un.csv'))
write_excel_csv(cor_dhs, paste0(wd_path,'/data/dhs-analysis/data/correlations_table_dhs.csv'))
# Show the correlation with pop density, building metrics, (hypothesis is these will have a weaker relationship)
# Look at the correlation -- scatter and annotate big outliers
# Regressions and Predictions tables --------------------------------------
# rcorr(subnat_all_wide_k %>% st_drop_geometry() %>%
# mutate(landscan_population_un_density_hectare = replace_na(landscan_population_un/block_hectares,0),
# building_to_block_area_ratio = replace_na(building_area_m2/block_area_m2,0),
# average_building_area_m2 = replace_na(building_area_m2/building_count,0),
# region_total = region_core_urban + region_peripheral_urban + region_peri_urban + region_non_urban,
# region_urban = region_core_urban + region_peripheral_urban,
# region_urban_share = region_urban/region_total,
# average_pop_per_building = replace_na(landscan_population_un/building_count,0)) %>%
# select(all_of(c('k_complexity_average', 'region_urban_share', 'average_building_area_m2', 'building_to_block_area_ratio', 'landscan_population_un_density_hectare', 'average_pop_per_building'))) %>%
# as.matrix(),
# type=c('spearman')) %>%
# tidy() %>% filter(column2 == 'k_complexity_average')
sections <- c("SurveyYear", "SurveyId", "REG_ID" ,"DHSREGEN", "CNTRYNAMEE")
# specifications <- c('k_complexity_average', 'region_nonurban_share', 'landscan_population_un_density_hectare', 'building_to_block_area_ratio', 'average_building_area_m2')
# specifications <- c('k_complexity_average', 'building_to_block_area_ratio', 'average_building_area_m2', 'block_area_m2', 'average_pop_per_building')
specifications <- c('k_complexity_average', 'street_density_ratio_km_to_km2', 'region_urban_share', 'share_building_count_under_31m2', 'building_to_block_area_ratio', 'landscan_population_un_density_hectare') # , 'average_pop_per_building'
# average buildings size, pod density,
reg_data <- subnat_all_wide_k %>% st_drop_geometry() %>%
mutate(landscan_population_un_density_hectare = replace_na(landscan_population_un/block_hectares,0),
building_to_block_area_ratio = replace_na(building_area_m2/block_area_m2,0),
average_building_area_m2 = replace_na(building_area_m2/building_count,0),
average_pop_per_building = replace_na(landscan_population_un/building_count,0),
share_building_count_under_31m2 = replace_na((bldg_area_count_bin_01_0.50__log10_3.2+bldg_area_count_bin_02_0.75__log10_5.6+bldg_area_count_bin_03_1.00__log10_10+bldg_area_count_bin_04_1.25__log10_17.8)/building_count,0),
share_population_4plus = replace_na((population_k_4 + population_k_5 + population_k_6 + population_k_7 + population_k_8 + population_k_9 + population_k_10plus + population_off_network) /landscan_population_un,0) ) %>%
mutate(region_total = region_core_urban + region_peripheral_urban + region_peri_urban + region_non_urban,
region_urban = region_core_urban + region_peripheral_urban,
region_urban_share = region_urban/region_total,
region_periurban_share = region_peri_urban/region_total,
region_nonurban_share = region_non_urban/region_total,
region_conurban_share = (region_urban+region_peri_urban)/region_total) %>%
rowwise() %>%
select(all_of(c(sections, specifications)),
all_of(contains(cor_dhs %>% select(column_var) %>% pull()))
#cor_dhs %>% select(column_var) %>% pull()
)
unique(cor_dhs$measurementtype)
cor_list <- cor_dhs %>%
#filter(!(column_var %in% c("HC_WIXQ_P_LOW_2ND", "HC_WIXQ_P_LOW_4TH", 'CM_ECMR_C_IMR', 'ED_EDAT_B_CPR', 'ED_EDAT_B_HGH', 'ED_EDAT_B_CSC', 'ED_EDAT_B_MYR', 'HC_PPRM_H_MNP', 'HC_WIXQ_P_GNI'))) %>%
#filter(source == 'DHS') %>%
filter(measurementtype %in% c("Percent", "Ratio", "Rate")) %>%
select(column_var, column_label, estimate, p.value ) %>%
distinct() %>% as.list()
if (exists("combined_reg_output")) {rm(combined_reg_output)}
if (exists("combined_pred_output")) {rm(combined_pred_output)}
for (i in seq_along(unique(cor_list$column_var))) {
#for (i in seq_along(c('ED_LITR_W_LIT', 'WS_TLET_H_IMP', 'WS_SRCE_H_IOP', 'HC_WIXQ_P_HGH'))) {
print(paste0('Progress: ',i,' - ',round(i/length(cor_list$column_var),4)*100,'%'))
print(cor_list %>% pluck(1, i))
print(cor_list %>% pluck(2, i))
print(cor_list %>% pluck(3, i))
reg_data_i <- reg_data %>%
rename_with( ~ 'dv', all_of(cor_list %>% pluck(1, i))) %>% # all of warning
rename_with( ~ 'dv_denom', all_of(paste0('dw_',cor_list %>% pluck(1, i)))) %>% # all of warning
mutate_at(vars(c('dv','dv_denom')), as.numeric) %>%
filter_at(vars(dv, dv_denom), all_vars(!is.na(.))) %>%
mutate(dv = case_when(dv == 0 ~ .0001,
dv == 1 ~ .9999,
TRUE ~ dv)) %>%
mutate(dv_numer = round(dv*dv_denom,0),
dv_target = dv_numer,
dv_nontarget = dv_denom - dv_numer) %>%
#select_all(~gsub("\\s+|\\.|\\/", "_", .)) %>%
#rename_all(list(tolower)) %>%
mutate(country = paste0(tolower(gsub("\\s+|\\.|'|\\/", "_", CNTRYNAMEE))))
if(nrow(reg_data_i) == 0) next
reg_data_i <- reg_data_i %>%
cbind(., scale( reg_data_i %>%
select(all_of(c(specifications))), center = TRUE, scale = TRUE) %>% as.data.frame() %>%
rename_with(., .fn = ~ paste0("norm_", .x),
.cols = everything()))
country_dummies <- reg_data_i %>%
arrange(SurveyYear) %>%
select(country) %>%
distinct() %>%
mutate(keep_countries = row_number())
country_fixed_effects <- country_dummies %>% filter(keep_countries > 1) %>% select(country) %>% mutate_at(vars(country), list(as.character)) %>% mutate(country = paste0('country_',country)) %>% pull()
country_dummies_drop <- country_dummies %>% filter(keep_countries == 1) %>% select(country) %>% mutate_at(vars(country), list(as.character)) %>% mutate(country = paste0('country_',country)) %>% pull()
reg_data_i <- reg_data_i %>%
recipe( ~ .) %>% step_dummy(country, one_hot = TRUE) %>% prep() %>% bake(NULL) %>% select(-one_of(country_dummies_drop)) %>%
#mutate(dummy = 1) %>% tidyr::spread(country, dummy, fill = 0) %>% select(-one_of(country_dummies_drop)) %>%
distinct()
# Binomial model
binomial_model <- linear_reg() %>% set_engine("glm", family = binomial(link = "logit"))
binomial_single <- binomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'k_complexity_average'))))
binomial_countries <- binomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'k_complexity_average', country_fixed_effects))))
binomial_controls <- binomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', specifications, country_fixed_effects))))
binomial_single_imp <- binomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'norm_k_complexity_average'))))
binomial_countries_imp <- binomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'norm_k_complexity_average', country_fixed_effects))))
binomial_controls_imp <- binomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', purrr::map_chr(specifications, ~ paste0("norm_", .)), country_fixed_effects))))
# Quasibinomial model
quasibinomial_model <- linear_reg() %>% set_engine("glm", family = quasibinomial(link = "logit"))
quasibinomial_single <- quasibinomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'k_complexity_average'))))
quasibinomial_countries <- quasibinomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'k_complexity_average', country_fixed_effects))))
quasibinomial_controls <- quasibinomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', specifications, country_fixed_effects))))
quasibinomial_single_imp <- quasibinomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'norm_k_complexity_average'))))
quasibinomial_countries_imp <- quasibinomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', 'norm_k_complexity_average', country_fixed_effects))))
quasibinomial_controls_imp <- quasibinomial_model %>% fit(reg_data_i %>% select(dv_target, dv_nontarget) %>% as.matrix() ~ ., data = reg_data_i %>% select_at(all_of(c('dv_target', 'dv_nontarget', purrr::map_chr(specifications, ~ paste0("norm_", .)), country_fixed_effects))))
# Beta model
beta_single <- betareg(formula = dv ~ k_complexity_average, weights = dv_denom, data = reg_data_i )
beta_countries <- betareg(formula = as.formula(paste('dv', paste(c('k_complexity_average', country_fixed_effects), collapse=" + "), sep=" ~ ")), weights = dv_denom, data = reg_data_i)
beta_controls <- betareg(formula = as.formula(paste('dv', paste(c(specifications, country_fixed_effects), collapse=" + "), sep=" ~ ")), weights = dv_denom, data = reg_data_i)
beta_single_imp <- betareg(formula = dv ~ k_complexity_average, weights = dv_denom, data = reg_data_i )
beta_countries_imp <- betareg(formula = as.formula(paste('dv', paste(c('norm_k_complexity_average', country_fixed_effects), collapse=" + "), sep=" ~ ")), weights = dv_denom, data = reg_data_i)
beta_controls_imp <- betareg(formula = as.formula(paste('dv', paste(c(purrr::map_chr(specifications, ~ paste0("norm_", .)), country_fixed_effects), collapse=" + "), sep=" ~ ")), weights = dv_denom, data = reg_data_i)
# logistic regression is best for proportional data when dv is binomial
# beta regression is appropriate when exact distribution of dv is unknown
# quasibinomial model is best when dv is over-dispersed (doesn't follow assumed binomial variance)
dv_var = cor_list %>% pluck(1, i)
dv_label = cor_list %>% pluck(2, i)
dv_correl = cor_list %>% pluck(3, i)
reg_output <- rbind(
tidy(binomial_single, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% mutate(distribution = 'binomial', predictors = 'k', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(binomial_single) %>% mutate(pseudo.r.squared = 1 - (deviance / null.deviance)) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(binomial_single_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(binomial_countries, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% mutate(distribution = 'binomial', predictors = 'k_fe', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(binomial_countries) %>% mutate(pseudo.r.squared = 1 - (deviance / null.deviance)) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(binomial_countries_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(binomial_controls, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% mutate(distribution = 'binomial', predictors = 'k_controls_fe', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(binomial_controls) %>% mutate(pseudo.r.squared = 1 - (deviance / null.deviance)) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(binomial_controls_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(beta_single, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(-one_of('component')) %>% mutate(distribution = 'beta', predictors = 'k', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(beta_single) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(beta_single_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(beta_countries, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(-one_of('component')) %>% mutate(distribution = 'beta', predictors = 'k_fe', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(beta_countries) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(beta_countries_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(beta_controls, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(-one_of('component')) %>% mutate(distribution = 'beta', predictors = 'k_controls_fe', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(beta_controls) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(beta_controls_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(quasibinomial_single, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% mutate(distribution = 'quasibinomial', predictors = 'k', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(quasibinomial_single) %>% mutate(pseudo.r.squared = 1 - (deviance / null.deviance)) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(quasibinomial_single_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(quasibinomial_countries, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% mutate(distribution = 'quasibinomial', predictors = 'k_fe', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(quasibinomial_countries) %>% mutate(pseudo.r.squared = 1 - (deviance / null.deviance)) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(quasibinomial_countries_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate)),
tidy(quasibinomial_controls, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% mutate(distribution = 'quasibinomial', predictors = 'k_controls_fe', dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(glance(quasibinomial_controls) %>% mutate(pseudo.r.squared = 1 - (deviance / null.deviance)) %>% select(pseudo.r.squared, df.null, logLik, AIC, BIC, df.residual, nobs)) %>%
cbind(., tidy(quasibinomial_controls_imp, conf.int = TRUE) %>% mutate_if(is.numeric, round, 7) %>% select(estimate) %>% rename(importance = estimate))
) # %>% filter(term == 'k_complexity_average')
reg_output <- reg_output %>%
mutate(estimate_log_odds = comma(exp(estimate)))
if (exists("combined_reg_output")) {
combined_reg_output <- rbind(combined_reg_output, reg_output)
} else {
combined_reg_output <- reg_output
}
# reg_output_trunc <- reg_output %>% filter(term == 'k_complexity_average')
pred_output <- reg_data_i %>%
select(SurveyYear, SurveyId, REG_ID, DHSREGEN, CNTRYNAMEE, dv, dv_numer, dv_denom) %>%
mutate(dv_var = dv_var, dv_label = dv_label, dv_correl = dv_correl) %>%
bind_cols(predict(binomial_single, reg_data_i) %>% rename(pred_binomial_k = .pred),
predict(binomial_countries, reg_data_i) %>% rename(pred_binomial_k_fe = .pred),
predict(binomial_controls, reg_data_i) %>% rename(pred_binomial_k_fe_controls = .pred),
predict(quasibinomial_single, reg_data_i) %>% rename(pred_quasibinomial_k = .pred),
predict(quasibinomial_countries, reg_data_i) %>% rename(pred_quasibinomial_k_fe = .pred),
predict(quasibinomial_controls, reg_data_i) %>% rename(pred_quasibinomial_k_fe_controls = .pred),
data.frame(.pred = predict(beta_single, reg_data_i ) %>% as.vector()) %>% rename(pred_beta_k = .pred),
data.frame(.pred = predict(beta_countries, reg_data_i ) %>% as.vector()) %>% rename(pred_beta_k_fe = .pred),
data.frame(.pred = predict(beta_controls, reg_data_i ) %>% as.vector()) %>% rename(pred_beta_k_fe_controls = .pred))
if (exists("combined_pred_output")) {
combined_pred_output <- rbind(combined_pred_output, pred_output)
} else {
combined_pred_output <- pred_output
}
}
combined_reg_output <- combined_reg_output %>%
mutate(expected_sign = case_when(term == 'k_complexity_average' ~
sign(estimate)==sign(dv_correl))) %>%
relocate(distribution, predictors, dv_var, dv_label, dv_correl, term, estimate, estimate_log_odds, importance, p.value, expected_sign, pseudo.r.squared)
write_excel_csv(combined_pred_output, paste0(wd_path,'/data/dhs-analysis/data/predictions_table.csv'))
write_excel_csv(combined_reg_output , paste0(wd_path,'/data/dhs-analysis/data/regression_table.csv'))
rm(reg_data_i, reg_output, pred_output)
rm(binomial_controls, binomial_countries, binomial_single, binomial_model,
beta_single, beta_countries, beta_controls,
quasibinomial_controls, quasibinomial_countries, quasibinomial_single, quasibinomial_model)
#rm(reg_data_i, reg_output, combined_reg_output, pred_output, combined_pred_output)
pred_summary <- combined_pred_output %>%
mutate(pred_binomial_k = pred_binomial_k * dv_denom,
pred_beta_k = pred_beta_k * dv_denom,
pred_quasibinomial_k = pred_quasibinomial_k * dv_denom) %>%
group_by(CNTRYNAMEE, dv_var, dv_label, dv_correl) %>%
summarize_at(vars(dv_numer, dv_denom,
pred_binomial_k, pred_beta_k, pred_quasibinomial_k), list(sum)) %>%
ungroup() %>%
mutate(pred_binomial_k = pred_binomial_k / dv_denom,
pred_beta_k = pred_beta_k / dv_denom,
pred_quasibinomial_k = pred_quasibinomial_k / dv_denom) %>%
mutate(dv = dv_numer / dv_denom,
resid_binomial_k = abs(dv - pred_binomial_k),
resid_beta_k = abs(dv - pred_beta_k),
resid_quasibinomial_k = abs(dv - pred_quasibinomial_k))
#combined_pred_output 'predictions_table'
#combined_reg_output 'regression_table'
# binom.test(x = sum(reg_data_i$dv_numer), n = sum(reg_data_i$dv_denom)) %>% tidy()%>% mutate_if(is.numeric, round, 7)
# one unit increase in the predictor X leads to an increase (or decrease) in the odds (probability an event will occur/1-probability event will occur) by a factor of eβ where β is the regression coefficient for X.
# https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5860877/#:~:text=The%20logistic%20regression%20model%20is,of%20a%20logit%20link%20function.
# PCA Prep ----------------------------------------------------------------
sections <- c("SurveyYear", "SurveyId", "REG_ID", "REGCODE", "DHSREGEN", "CNTRYNAMEE", "ISO")
complexity_features <- c('k_complexity_average', 'street_density_ratio_km_to_km2', "landscan_population_un_density_hectare", "building_to_block_area_ratio", "average_building_area_m2", "region_urban_share", "region_nonurban_share", "population_k_1", "population_k_2", "population_k_3", "population_k_4", "population_k_5", "population_k_6", "population_k_7", "population_k_8", "population_k_9", "population_k_10plus", "population_off_network", "bldg_area_count_bin_01_0.50__log10_3.2", "bldg_area_count_bin_02_0.75__log10_5.6", "bldg_area_count_bin_03_1.00__log10_10", "bldg_area_count_bin_04_1.25__log10_17.8", "bldg_area_count_bin_05_1.50__log10_31.6", "bldg_area_count_bin_06_1.75__log10_56.2", "bldg_area_count_bin_07_2.00__log10_100", "bldg_area_count_bin_08_2.25__log10_177.8", "bldg_area_count_bin_09_2.50__log10_316.2", "bldg_area_count_bin_10_2.75__log10_562.3", "bldg_area_count_bin_11_3.00__log10_1000", "bldg_area_count_bin_12_3.25__log10_1778.3")
dhs_features <- cor_dhs %>% select(column_var) %>% pull()
dhs_latex_labels <- list(
indicatorid = c("EM_OCCP_M_AGR", "EM_OCCP_M_MNS", "EM_OCCP_M_MNU", "EM_OCCP_M_PRO", "EM_OCCP_W_AGR", "EM_OCCP_W_DOM", "EM_OCCP_W_MNU", "EM_OCCP_W_PRO", "HC_WIXQ_P_LOW", "HC_WIXQ_P_2ND", "HC_WIXQ_P_MID", "HC_WIXQ_P_4TH", "HC_WIXQ_P_HGH", "HC_WIXQ_P_GNI", "HC_HEFF_H_CMP", "HC_HEFF_H_FRG", "HC_HEFF_H_MPH", "HC_HEFF_H_TLV", "HC_TRNS_H_CAR", "ED_EDAT_B_MYR", "ED_EDAT_M_MYR", "ED_EDAT_W_MYR", "ED_EDAT_B_NED", "ED_EDAT_B_SEC", "ED_EDAT_B_HGH", "ED_NARP_B_BTH", "ED_NARS_B_BTH", "ED_GARS_B_GPI", "ED_LITR_W_LIT", "ED_LITY_W_LIT", "ED_LITY_W_NRD", "ED_NARP_W_FEM", "ED_NARS_W_FEM", "ED_EDUC_W_SEH", "ED_EDAT_W_NED", "ED_EDAT_W_SEC", "ED_EDAT_W_HGH", "ED_MDIA_W_3MD", "ED_MDIA_W_N3M", "CO_MOBB_W_BNK", "CO_MOBB_W_MOB", "AN_NUTS_W_THN", "FP_NADM_W_MNT", "RH_DELP_C_DHF", "CM_ECMR_C_CMR", "CM_ECMR_C_IMR", "CM_ECMR_C_PNR", "CM_ECMR_C_U5M", "CH_VACC_C_BAS", "CN_IYCF_C_4FA", "CN_NUTS_C_HA2", "CN_NUTS_C_WA2", "CN_NUTS_C_WH2", "CN_ANMC_C_ANY", "WS_SRCE_P_BAS", "WS_SRCE_P_IMP", "WS_SRCE_P_IOP", "WS_SRCE_P_LTD", "WS_SRCE_P_NIM", "WS_SRCE_P_PIP", "WS_TIME_P_L30", "WS_TIME_P_M30", "WS_TIME_P_ONP", "WS_TLOC_P_DWL", "WS_TLET_P_BAS", "WS_TLET_P_IMP", "WS_TLET_P_NFC", "WS_HNDW_P_BAS", "WS_HNDW_P_SOP", "HC_PPRM_H_MNP", "HC_OLDR_H_3GN", "HC_PPRM_H_12P", "HC_PPRM_H_34P", "HC_PPRM_H_56P", "HC_PPRM_H_7PP", "HC_CKPL_P_HSE", "HC_CKFL_P_CLN", "HC_CKFL_P_SLD", "HC_ELEC_P_ELC", "HC_ELEC_P_NEL", "HC_FLRM_P_ETH", "HC_FLRM_P_NAT"),
latex_label = c("% of men employed in agriculture", "% of men employed in skilled manual labor", "% of men employed in unskilled manual labor", "% of men employed in prof., technical, mgmt.", "% of women employed in agriculture", "% of women employed in domestic labor", "% of women employed in unskilled manual labor", "% of women employed in prof., technical, mgmt.", "% in the lowest wealth quintile", "% in the second wealth quintile", "% in the middle wealth quintile", "% in the fourth wealth quintile", "% in the highest wealth quintile", "Wealth index Gini coefficient", "% of households possessing a computer", "% of households possessing a refrigerator", "% of households possessing a mobile telephone", "% of households possessing a television", "% of households possessing a private car", "Median years of education (both sexes)", "Median years of education (males)", "Median years of education (females)", "% of age 6+ with no education", "% of age 6+ who attended secondary school", "% of age 6+ who attended higher education", "Net primary school attendance rate", "Net secondary school attendance rate", "Gross parity index for gross secondary school", "% of women who are literate", "% of young women who are literate", "% of young women who cannot read at all", "Net primary school female attendance rate", "Net secondary school female attendance rate", "% of women with secondary or higher education", "% of females age 6+ with no education", "% of females age 6+ who attended secondary school", "% of females age 6+ who attended higher education", "% of women w/weekly access to newspaper, TV, radio", "% of women with no access to mass media", "% of women who have a bank account", "% of women who own a mobile phone", "% of women who are thin with sub-18.5 BMI", "% of married women met need for family planning", "% of live births delivered at a health facility", "Child mortality rate", "Infant mortality rate", "Postneonatal mortality rate", "Under-five mortality rate", "% of 12-23 month old who received all 8 basic vaccinations", "% of children age 6-23 months fed 5+ food groups", "% of children stunted (below -2 SD of height for age)", "% of children underweight (below -2 SD of weight for age)", "% of children wasted (below -2 SD of weight for height)", "% of children under age 5 classified as having any anemia", "% of population with basic water service", "% of population using an improved water source", "% of population with improved water source on premises", "% of population with limited water service", "% of population using an unimproved water source", "% of population using water piped into dwelling", "% of population with water under 30 min. round trip", "% of population with water over 30 min. round trip", "% of population with water on the premises", "% of population with sanitation facility in own dwelling", "% of population with basic sanitation service", "% of population with an improved sanitation facility", "% of population using open defecation", "% of population with soap & water for handwashing", "% of population with soap available for handwashing", "Mean persons per sleeping room", "% of households with 3 generations", "% of households with 1-2 persons per sleeping room", "% of households with 3-4 persons per sleeping room", "% of households with 5-6 persons per sleeping room", "% of households with 7 + persons per sleeping room", "% of population cooking in the house", "% of population using clean fuel for cooking", "% of population using solid fuel for cooking", "% of population with electricity", "% of population with no electricity", "% of population with earth/sand floors", "% of population with natural floors")
) %>% as.data.frame()
subnat_pca <- subnat_all_wide_k %>% st_drop_geometry() %>%
mutate(landscan_population_un_density_hectare = landscan_population_un/block_hectares,
building_to_block_area_ratio = replace_na(building_area_m2/block_area_m2,0),
average_building_area_m2 = replace_na(building_area_m2/building_count,0),
region_total = region_core_urban + region_peripheral_urban + region_peri_urban + region_non_urban,
region_urban = region_core_urban + region_peripheral_urban,
region_urban_share = region_urban/region_total,
region_nonurban_share = region_non_urban/region_total) %>%
mutate(across(all_of(c('population_k_1', 'population_k_2', 'population_k_3', 'population_k_4', 'population_k_5', 'population_k_6', 'population_k_7', 'population_k_8', 'population_k_9', 'population_k_10plus', 'population_off_network')),
.fns = ~ .x / landscan_population_un)) %>%
mutate(across(all_of(c("bldg_area_count_bin_01_0.50__log10_3.2", "bldg_area_count_bin_02_0.75__log10_5.6", "bldg_area_count_bin_03_1.00__log10_10", "bldg_area_count_bin_04_1.25__log10_17.8", "bldg_area_count_bin_05_1.50__log10_31.6", "bldg_area_count_bin_06_1.75__log10_56.2", "bldg_area_count_bin_07_2.00__log10_100", "bldg_area_count_bin_08_2.25__log10_177.8", "bldg_area_count_bin_09_2.50__log10_316.2", "bldg_area_count_bin_10_2.75__log10_562.3", "bldg_area_count_bin_11_3.00__log10_1000", "bldg_area_count_bin_12_3.25__log10_1778.3", "bldg_area_count_bin_13_3.50__log10_3162.3", "bldg_area_count_bin_14_3.75__log10_5623.4", "bldg_area_count_bin_15_4.00__log10_10000")),
.fns = ~ .x / building_count)) %>%
select(all_of(c(sections, complexity_features, 'landscan_population_un')),
all_of(dhs_features)) %>%
mutate(row_na = rowSums(is.na(select(., all_of(dhs_features))))) %>%
group_by(CNTRYNAMEE, REGCODE) %>%
mutate(rank_recent = row_number(desc(SurveyYear)),
rank_na = row_number(-desc(row_na))) %>%
ungroup() %>%
#filter(rank_recent == 1) %>%
#filter(rank_na == 1) %>%
select(-one_of(c('rank_recent','rank_na','row_na')))
sapply(subnat_pca , function(X) sum(is.na(X)))
pca_missing <- colSums(is.na(subnat_pca)) %>% as.data.frame() %>% tibble::rownames_to_column(., 'column_var' ) %>% rename(missing_count = 2)
pca_notmissing <- colSums(!is.na(subnat_pca)) %>% as.data.frame() %>% tibble::rownames_to_column(., 'column_var' ) %>% rename(nonmissing_count = 2)
exclude_from_pca_list <- pca_missing %>%
filter(missing_count > 120) %>% select(column_var) %>% pull()
#filter(missing_count >= 70) %>% select(column_var) %>% pull()
subnat_pca <- subnat_pca %>%
select(-one_of(exclude_from_pca_list,
dhs_dict_df %>% filter(household_duplicate == 1) %>% select(indicatorid) %>% pull())
) %>%
drop_na()
pca_in <- subnat_pca %>%
select(-one_of(sections,
'landscan_population_un',
complexity_features))
(num_dhs_indicators <- length(names(pca_in)))
nrow(pca_in)
# List of PCA vars:
# "EM_OCCP_M_AGR", "EM_OCCP_M_MNS", "EM_OCCP_M_PRO", "EM_OCCP_W_AGR", "EM_OCCP_W_PRO", "HC_WIXQ_P_LOW", "HC_WIXQ_P_2ND", "HC_WIXQ_P_MID", "HC_WIXQ_P_4TH", "HC_WIXQ_P_HGH", "HC_WIXQ_P_GNI", "HC_HEFF_H_FRG", "HC_HEFF_H_MPH", "HC_HEFF_H_TLV", "HC_TRNS_H_CAR", "ED_EDAT_B_MYR", "ED_EDAT_M_MYR", "ED_EDAT_W_MYR", "ED_EDAT_B_NED", "ED_EDAT_B_SEC", "ED_EDAT_B_HGH", "ED_LITR_W_LIT", "ED_LITY_W_LIT", "ED_LITY_W_NRD", "ED_EDUC_W_SEH", "ED_EDAT_W_NED", "ED_EDAT_W_SEC", "ED_EDAT_W_HGH", "ED_MDIA_W_3MD", "ED_MDIA_W_N3M", "FP_NADM_W_MNT", "RH_DELP_C_DHF", "CM_ECMR_C_CMR", "CM_ECMR_C_IMR", "CM_ECMR_C_PNR", "CM_ECMR_C_U5M", "CH_VACC_C_BAS", "CN_IYCF_C_4FA", "CN_NUTS_C_HA2", "CN_NUTS_C_WA2", "CN_NUTS_C_WH2", "CN_ANMC_C_ANY", "WS_TLET_P_BAS", "WS_TLET_P_IMP", "WS_TLET_P_NFC", "WS_SRCE_P_BAS", "WS_SRCE_P_IMP", "WS_SRCE_P_IOP", "WS_SRCE_P_LTD", "WS_SRCE_P_NIM", "WS_SRCE_P_PIP", "WS_TIME_P_L30", "WS_TIME_P_M30", "WS_TIME_P_ONP", "HC_PPRM_H_MNP", "HC_OLDR_H_3GN", "HC_PPRM_H_12P", "HC_PPRM_H_34P", "HC_PPRM_H_56P", "HC_PPRM_H_7PP", "HC_CKPL_P_HSE", "HC_CKFL_P_CLN", "HC_CKFL_P_SLD", "HC_ELEC_P_ELC", "HC_ELEC_P_NEL", "HC_FLRM_P_ETH", "HC_FLRM_P_NAT"
# ISO Table ---------------------------------------------------------------
iso_table <- subnat_pca %>% rename(Country = CNTRYNAMEE) %>% select(ISO, Country) %>% distinct() %>% arrange(ISO) %>%
mutate(Country = gsub(pattern = 'Congo Democratic Republic', replacement= 'DR Congo', x = Country))
# Select PCA input variables ----------------------------------------------