-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyproject.Rmd
2218 lines (1669 loc) · 99.2 KB
/
myproject.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: "Baltimore Life Expectancy"
author: "Kayode Sosina"
date: "September 12, 2016"
references:
- URL: http://www.jstor.org/stable/1400528
author:
- family: Dutilleul
given: Pierre
- family: Stockwell
given: Jason
- family: Frigon
given: Dominic
- family: Legendre
given: Pierre
container-title: Journal of Agricultural, Biological, and Environmental Statistics
id: mantel
issued:
month: 6
year: 2000
page: 131-150
publisher: International Biometric Society
title: 'The Mantel Test versus Pearson''s Correlation Analysis: Assessment of the
Differences for Biological and Environmental Studies'
type: article-journal
volume: 5
- URL: http://www.jstor.org/stable/2332142
author:
- family: Moran
given: Patrick Alfred Pierce
container-title: Biometrika
id: moran
issued:
month: 6
year: 1950
page: 17-23
publisher: ' Oxford University Press on behalf of Biometrika Trust'
title: Notes on Continuous Stochastic Phenomena
type: article-journal
volume: 37
- author:
- family: Mantel
given: Nathan
container-title: American Association for Cancer Research.
id: mantel1
issued:
month: 9
year: 1966
title: The Detection of Disease Clustering and a Generalized Regression Approach
type: article-journal
- author:
- family: Fotheringham
given: A. Stewart
- family: Brunsdon
given: Chris
- family: Charlton
given: Martin
container-title: ' Wiley'
id: fother
issued:
year: 2002
title: 'Geographically Weighted Regression: The Analysis of Spatially Varying Relationships'
type: Book
- URL: http://www.who.int/healthinfo/indicators/hsi_indicators_SDG_TechnicalMeeting_December2015_BackgroundPaper.pdf
id: who
issued:
year: 2014
title: An overarching health indicator for the Post-2015 Development Agenda
type: Article
- URL: http://hdr.undp.org/en/content/human-development-index-hdi
id: hdi
title: An overarching health indicator for the Post-2015 Development Agenda
- URL: http://dx.doi.org/10.18637/jss.v063.i17
author:
- family: Gollini
given: Isabella
- family: Lu
given: Binbin
- family: Charlton
given: Martin
- family: Brunsdon
given: Christopher
- family: Harris
given: Paul
container-title: Journal of Statistical softwar
id: gwmodel
issued:
month: 2
year: 2015
title: 'GWmodel: An R Package for Exploring Spatial Heterogeneity Using Geographically
Weighted Models'
type: article-journal
volume: 63
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Housekeeping
-------------------
We need to create folders which will contain the data, plots and text.
```{r directories, include=FALSE}
dir_create <- function(){
dir_names <- c("R code", "Data", "Text", "Plots")
sapply(dir_names, function(x) {
if(!file.exists(x)){
dir.create(x)
}
})
}
dir_create()
```
```{r housekeeping, include=FALSE, message=FALSE, eval=T}
match.package <- function(){
#list of packages that will be used
list.of.packages <- c("ggplot2", "Rcpp", "lubridate", "downloader",
"readr", "readxl", "maptools", "RColorBrewer",
"ggmap", "rgeos", "broom", "rgdal", "grDevices",
"animation", "ade4", "sp", "ape", "geosphere", "dplyr",
"plyr", "pryr", "tidyr", "gstat", "spdep", "spgwr",
"GWmodel", "ModelMap", "acs", "tigris", "gridExtra",
"animation", "devtools", "cvTools")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages) > 0) {
install.packages(new.packages,repos = "http://cran.us.r-project.org")
# stop(paste("Please install the following packages", paste0(new.packages,collapse = " ")))
# print(paste("The following packages are missing", new.packages))
# x <- readline("Would you like to install them now?[y/n] >")
# if (any(x %in% c("y", "n")) & x == "y")
# {
# install.packages(new.packages)
# }
# else if (!any(x %in% c("y", "n")))
# print("Please enter y or n")
# else
# stop(paste("Please install the following packages", paste0(new.packages,collapse = " ")))
}
}
match.package()
```
Data
------------------
We have data from [Baltimore city website](https://data.baltimorecity.gov), [Baltimore Neighborhood Indicators Alliance BNIA-JF](http://bniajfi.org), [Maryland department of planning](http://www.mdp.state.md.us/), and from the [Census Bureau](http://www.census.gov). The data consists of information about life expectancy estimates for each neighbourhood, along with crime, economic development and education informmation, all over a 5 year period (2010-2014). I also have street level, and [block group](https://www.census.gov/geo/reference/gtc/gtc_bg.html) level data.
```{r data_download, include=FALSE, message=FALSE}
setwd(file.path(".", "Data"))
packages <- c("ggplot2","lubridate", "downloader",
"readr", "readxl", "maptools", "RColorBrewer", "ggmap", "devtools")
sapply(packages, library, character.only = T, quietly = T)
Real_Property_Taxes <- "https://data.baltimorecity.gov/api/views/27w9-urtv/rows.csv?accessType=DOWNLOAD"
Parks <- "https://data.baltimorecity.gov/api/views/3r8a-uawz/rows.csv?accessType=DOWNLOAD"
Religious_Buildings <- "https://data.baltimorecity.gov/api/views/kbdc-bpw3/rows.csv?accessType=DOWNLOAD"
Libraries <- "https://data.baltimorecity.gov/api/views/tgtv-wr5u/rows.csv?accessType=DOWNLOAD"
Liquor_Licenses <- "https://data.baltimorecity.gov/api/views/xv8d-bwgi/rows.csv?accessType=DOWNLOAD"
Customer_Service_Requests_311 <- "https://data.baltimorecity.gov/api/views/9agw-sxsr/rows.csv?accessType=DOWNLOAD"
Assisted_Living_Facilities <- "https://data.baltimorecity.gov/api/views/q2vm-e9dp/rows.csv?accessType=DOWNLOAD"
Adult_Day_Care_Facilities <- "https://data.baltimorecity.gov/api/views/yc75-xbrv/rows.csv?accessType=DOWNLOAD"
Nursing_Homes <- "https://data.baltimorecity.gov/api/views/53js-3bkd/rows.csv?accessType=DOWNLOAD"
Census_Profile_by_Neighborhood_Statistical_Areas_2010 <- "https://data.baltimorecity.gov/api/views/5iam-bd6p/rows.csv?accessType=DOWNLOAD"
Census_Demographics_2010 <- "https://data.baltimorecity.gov/api/views/cix3-h4cy/rows.csv?accessType=DOWNLOAD"
Neighborhood_Action_Sense_of_Community_2010 <- "https://data.baltimorecity.gov/api/views/ipje-efsv/rows.csv?accessType=DOWNLOAD"
Real_Property <- "http://gisdata.baltimorecity.gov/datasets/b41551f53345445fa05b554cd77b3732_0.csv"
CSA_to_NSA_2010 <- "http://bniajfi.org/wp-content/uploads/2014/04/CSA-to-NSA-2010.xlsx"
Census_Blocks_and_NSAs_2010 <- "http://bniajfi.org/wp-content/uploads/2014/04/Census-Blocks-and-NSAs-2010.xlsx"
BPD_Part_1_Victim_Based_Crime_Data <- "https://data.baltimorecity.gov/api/views/wsfq-mvij/rows.csv?accessType=DOWNLOAD"
Vacant_Buildings <- "https://data.baltimorecity.gov/api/views/qqcv-ihn5/rows.csv?accessType=DOWNLOAD"
##### All 2010 to 2014 data #####
# Noticed that demo data for 2010-2014 has only partial info
Census_Demographics_2010_to_2014 <- "https://data.baltimorecity.gov/api/views/t7sb-aegk/rows.csv?accessType=DOWNLOAD"
Census_Demographics_2010_complete <- "https://data.baltimorecity.gov/api/views/cix3-h4cy/rows.csv?accessType=DOWNLOAD"
Census_Demographics_2010_and_2012 <- "https://data.baltimorecity.gov/api/views/yp84-wh4q/rows.csv?accessType=DOWNLOAD"
Census_Demographics_2010_and_2013 <- "https://data.baltimorecity.gov/api/views/7pnq-8ebe/rows.csv?accessType=DOWNLOAD"
Children_and_Family_Health_Well_Being_2010_to_2014 <- "https://data.baltimorecity.gov/api/views/rtbq-mnni/rows.csv?accessType=DOWNLOAD"
Housing_and_Community_Development_2010_to_2014 <- "https://data.baltimorecity.gov/api/views/mvvs-32jm/rows.csv?accessType=DOWNLOAD"
Crime_Safety_2010_to_2014 <- "https://data.baltimorecity.gov/api/views/qmw9-b8ep/rows.csv?accessType=DOWNLOAD"
Workforce_and_Economic_Development_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Workforce-2010-2014.xlsx"
Arts_and_Culture_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Arts-2011-2014.xlsx"
Education_and_Youth_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Education-2010-2014.xlsx"
Sustainability_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Sustainability-2010-2014.xlsx"
##### CODEBOOK #####
BNIA_Vital_Signs_Codebook <- "https://data.baltimorecity.gov/api/views/ryvy-9zw6/rows.csv?accessType=DOWNLOAD"
if(!file.exists(file.path("..", "Text","codebook.csv"))){
switch(Sys.info()[['sysname']],
Windows= {download(url = BNIA_Vital_Signs_Codebook, destfile = file.path("..", "Text","codebook.csv"),
# method = "wget",
mode="wb")},
Linux = {download.file(url = BNIA_Vital_Signs_Codebook, destfile = file.path("..", "Text","codebook.csv"),
method = "wget",
mode="wb")},
Darwin = {download.file(url = BNIA_Vital_Signs_Codebook, destfile = file.path("..", "Text","codebook.csv"),
method = "wget",
mode="wb")})
}
##### Downloading the files und save ze dates #####
#### 1 Neighbourhood data ####
# data_path <- file.path(".", "Data")
data_names <- c("census.csv", "child_and_fam_wellbeing.csv", "housing.csv",
"crime.csv", "workforce.xlsx", "culture.xlsx", "edu_and_youth.xlsx",
"sustain.xlsx", "census10.csv", "census12.csv", "census13.csv")
data_urls <- c(Census_Demographics_2010_to_2014, Children_and_Family_Health_Well_Being_2010_to_2014,
Housing_and_Community_Development_2010_to_2014, Crime_Safety_2010_to_2014,
Workforce_and_Economic_Development_2010_to_2014, Arts_and_Culture_2010_to_2014,
Education_and_Youth_2010_to_2014, Sustainability_2010_to_2014, Census_Demographics_2010_complete,
Census_Demographics_2010_and_2012, Census_Demographics_2010_and_2013)
mapply(function(x,y) {
if(!file.exists("raw_data")){
dir.create("raw_data")
}
if(!file.exists(file.path(".", "raw_data",y))){
switch(Sys.info()[['sysname']],
Windows= {download(url = x, destfile = file.path(".", "raw_data",y),
# method = "wget",
mode="wb")},
Linux = {download.file(url = x, destfile = file.path(".", "raw_data",y),
method = "wget",
mode="wb")},
Darwin = {download.file(url = x, destfile = file.path(".", "raw_data",y),
method = "wget",
mode="wb")})
date_downloaded <- now()
write.table(date_downloaded, file.path(".", "raw_data", "date_downloaded.txt"))
}
},data_urls,data_names)
##### 2 Data that could ID Blocks within a Neighbourhood #####
data_names <- c("csa_nsa.xlsx", "blocks_nsa.xlsx","property.csv", "parks.csv", "religious.csv",
"libraries.csv", "cust_311.csv", "real_property.csv","street_crime.csv", "vacants.csv")
#cust_311 has zip, address and neighbourhood
data_urls <- c(CSA_to_NSA_2010,Census_Blocks_and_NSAs_2010,
Real_Property_Taxes, Parks, Religious_Buildings,
Libraries, Customer_Service_Requests_311,Real_Property,
BPD_Part_1_Victim_Based_Crime_Data, Vacant_Buildings)
mapply(function(x,y) {
if(!file.exists("raw_data")){
dir.create("raw_data")
}
v <- list.files(file.path(".", "raw_data"), pattern = "*.csv")
lv <- length(v)
if(!file.exists(file.path("raw_data",y)) & lv < 15){
switch(Sys.info()[['sysname']],
Windows= {download(url = x, destfile = file.path(".", "raw_data",y),
# method = "wget",
mode="wb")},
Linux = {download.file(url = x, destfile = file.path(".", "raw_data",y),
method = "wget",
mode="wb")},
Darwin = {download.file(url = x, destfile = file.path(".", "raw_data",y),
method = "wget",
mode="wb")})
date_downloaded <- now()
write.table(date_downloaded, file.path(".", "raw_data", "date_downloaded.txt"))
if(file.info(file.path("raw_data",y))$size*1e-6 > 30 )
system(paste("gzip", file.path(".", "raw_data",y)))
}
},data_urls,data_names)
#### Shape_files ####
zip_Census_Demographics_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Census.zip"
zip_Children_and_Family_Health_Well_Being_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Health.zip"
zip_Housing_and_Community_Development_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Housing.zip"
zip_Crime_Safety_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Crime.zip"
zip_Workforce_and_Economic_Development_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Workforce.zip"
zip_Arts_and_Culture_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Arts.zip"
zip_Education_and_Youth_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Education.zip"
zip_Sustainability_2010_to_2014 <- "http://bniajfi.org/wp-content/uploads/2016/04/VS-14-Sustainability.zip"
zip_census_block_2010 <- "http://www.mdp.state.md.us/msdc/census/cen2010/maps/tiger10/blk2010.zip" # 2010 shapefile showing block info
zip_census_tract_2010 <- "http://planning.maryland.gov/msdc/census/cen2010/maps/tiger10/ct2010.zip" # 2010 shapefile showing tract info
zip_neighbour <- "https://data.baltimorecity.gov/download/ysi8-7icr/application%2Fzip"
data_names <- c("census.zip", "child_and_fam_wellbeing.zip", "housing.zip",
"crime.zip", "workforce.zip", "culture.zip", "edu_and_youth.zip",
"sustain.zip", "census_tract.zip",
"census_blk.zip",
"neighbour.zip")
data_urls <- c(zip_Census_Demographics_2010_to_2014, zip_Children_and_Family_Health_Well_Being_2010_to_2014,
zip_Housing_and_Community_Development_2010_to_2014, zip_Crime_Safety_2010_to_2014,
zip_Workforce_and_Economic_Development_2010_to_2014, zip_Arts_and_Culture_2010_to_2014,
zip_Education_and_Youth_2010_to_2014, zip_Sustainability_2010_to_2014, zip_census_tract_2010,
zip_census_block_2010,
zip_neighbour)
mapply(function(x,y) {
if(!file.exists("raw_data")){
dir.create("raw_data")
}
if(!file.exists(file.path("raw_data",y))){
switch(Sys.info()[['sysname']],
Windows= {download(url = x, destfile = file.path(".", "raw_data",y),
# method = "wget",
mode="wb")},
Linux = {download.file(url = x, destfile = file.path(".", "raw_data",y),
method = "wget",
mode="wb")},
Darwin = {download.file(url = x, destfile = file.path(".", "raw_data",y),
method = "wget",
mode="wb")})
date_downloaded <- now()
write.table(date_downloaded, file.path("raw_data", "date_downloaded.txt"))
}
},data_urls,data_names)
### Extract the zip files ###
##All except neighbour and block data
sapply(data_names[1:9], function(x){
if(!file.exists("wip")){
dir.create("wip")
}
no_files_expected <- 7*length(data_names)
if (length(list.files(file.path(".","wip"))) < no_files_expected){
unzip(file.path(".","raw_data", x),
# files = grep("*.shp|*.dbf|*.shx",unzip(file.path(".","raw_data", x), list = T)[,1], value = T),
exdir = file.path(".","wip"), junkpaths = T)
}
})
##rename them
sapply(list.files(file.path(".","wip")),
function(x){
file.rename(from =file.path(".","wip", x),
to = file.path(".","wip", tolower(gsub("^.*?_", "", x, ignore.case = T)) ) )
}
)
## Create a sub dir under WIP for each dataset and move the file into it
shape_dirs <- sapply(list.files(file.path(".","wip")), function(x){
strsplit(x, "[.]")[[1]][1]
}
)
sapply(shape_dirs, function(x){
if(!file.exists( file.path(".","wip",x)) ){
dir.create(file.path(".","wip",x))
files_to_copy <- list.files(file.path(".","wip"), pattern= paste0(x,"[.]*"))[-1]
file.copy( paste0(file.path(".","wip", files_to_copy)) ,
file.path(file.path(".","wip", x)) )
file.remove(paste0(file.path(".","wip", files_to_copy)))
}
else if (file.exists( file.path(".","wip",x))){
files_to_del <- list.files(file.path(".","wip"), pattern= paste0(x,"[.]*"))[-1]
file.remove(paste0(file.path(".","wip", files_to_del)))
}
}
)
#Block data
# ifiles <- unzip(file.path(".","raw_data", "census_blk.zip"), list = T)
# ifiles.name <- substr(ifiles[,1][1], 1, nchar(ifiles[,1][1]) - 4)
# if(!file.exists( file.path(".","wip", ifiles.name ) ) & length(list.files(file.path("..","Plots"))) == 0){
# dir.create(file.path(".","wip", ifiles.name ))
# unzip(file.path(".","raw_data", "census_blk.zip"),
# files = grep("*[.]", ifiles[,1], value = T), exdir = file.path(".","wip",ifiles.name), junkpaths = T)
# }
#Neighbourhood data
ifiles <- unzip(file.path(".","raw_data", "neighbour.zip"), list = T)
ifiles.name <- substr(ifiles[,1][1], 1, 5)
if(!file.exists( file.path(".","wip", ifiles.name ) )){
dir.create(file.path(".","wip", ifiles.name ))
unzip(file.path(".","raw_data", "neighbour.zip"),
files = grep("*[.]", ifiles[,1], value = T), exdir = file.path(".","wip",ifiles.name), junkpaths = T)
file.to.del <- list.files(file.path(".","wip", ifiles.name ), pattern = ".shp|.atx", full.names = T)[-2]
# system(paste("rm", file.to.del[1], file.to.del[2]))
}
rm(list = ls())
setwd(file.path(".."))
```
The data fall in three general categories.
1. Street level
2. [Block group](https://www.census.gov/geo/reference/gtc/gtc_bg.html) level
3. [Community statistical area level (CSA)](http://bniajfi.org/faqs/)
###Data Cleaning and interpolation
The following table gives some of the variables used in the model fitting process, which level we originally got the data at and assumptions we made to get it at a street block level
| Variables | Name | Level | Cleaning steps |
|:----------:|:-----------:|:-----------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
| propfemhh | Proportion of households headed by a female with related children under 18 years | Block group | Since the data was at a block group level and we were interested in getting street block level data, we used [Kriging](https://en.wikipedia.org/wiki/Kriging) to [interpolate](https://en.wikipedia.org/wiki/Interpolation) data at new locations (street block locations) using the information from the block group level. The locations for the street blocks were ascertained as the median longitude and latitude of all streets that made up the street block. One of the assumptions made here was that the distribution of the variable (propfemhh) was smooth in the sense that street blocks with such households will tend to be similar. |
| propkids_withinsurance | The proportion of individuals less than 18 years who have health insurance for a given block group | Block group | Here we used the block group value as the value for each street block in that block group. The assumption here was that block groups would tend to be quite homogenous with regard to this variable. |
| racdiv | Racial diversity as calculated per block group | Block group | This variable was not given but was estimated from the block group data on race. Its estimation proceeds as follows calculate the percent of each race, square the percent for each group, sum the squares, subtract the sum from 1.00. Eight groups were used for the index: White, not Hispanic; Black or African American; American Indian and Alaska Native (AIAN); Asian; Native Hawaiian and Other Pacific Islander (NHOPI); two or more races, not Hispanic; some other race, not Hispanic; Hispanic or Latino. This method is based on that used by the census bureau. More information can be found [here](http://www.census.gov/population/cen2000/atlas/censr01-104.pdf). We decided not to interpolate these values for the street blocks but instead used the values from block groups that they belonged to. This was done due to the unique structure of neighborhoods in Baltimore city. |
| propbelow | Proportion of individuals within a block group that lives below the poverty line | Block group | To get the data at the street block level we interpolated values from the block group level. The assumption used here is that the further into a particular neighborhood you go, the more representative each block is of the aggregate level data for this variable. |
| mhhi | Median household income | Block group | We interpolated the values for the street blocks from the block group level data using Kriging. Again this is based on the assumption that the further into a particular neighborhood you go, the more representative each block is of the aggregate level data for this variable. |
| totalincidents | # of crime incidents per street | Street | We aggregated this to get the number of crimes committed per street block |
| prop.vacant | Proportion of vacant homes | Street | We divided the number of vacant homes per street block by the total number of homes in that street block. |
The rest of the variables used in the final model includes: Percentage of Students Suspended or Expelled During School Year (susp); Liquor Outlet density per 1,000 Residents (liquor); and Percent of Residences Heated by Electricity (elheat). Note that all the variables mentioned above were observed at the CSA level. Furthermore, I did not do any interpolation for these variables at the street block level as I felt that the assumptions inherent in the process would be untenable.
```{r analyses_data, echo = F, message=FALSE, warning=F}
##########################
## Warning: this takes a while to run
##########################
#Create all data files to be used during analysis
setwd(file.path(".","Data"))
# stop(print(substr(getwd(), 37, nchar(getwd()))))
#First dataset is Census. 1. 2010-2014 has missing info for 2010, 2012, and 2013
census10.14 <- readr::read_csv(file.path("raw_data", "census.csv"))
census10 <- readr::read_csv(file.path("raw_data", "census10.csv"))
census10.12 <- readr::read_csv(file.path("raw_data", "census12.csv"))
census10.13 <- readr::read_csv(file.path("raw_data", "census13.csv"))
#First rename colums to match
names(census10)[c(1:2,5:6, 8:10,12,13:14, 16:17)] <- c(names(census10.14)[c(1:2,5:7,9,8,10,13:16)])
names(census10)[15] <- "age44_10"
names(census10.13)[1] <- names(census10.14)[1]
#Second merging datasets
library(dplyr);library(lubridate)
#I noticed that some variables have * in front of each figure for hhs10 and mhhi13 in census10.13 so I will replace em
census10.13 %>% dplyr::arrange_(.dots=names(census10.13)[1:20]) %>%
dplyr::mutate(hhs10 = as.numeric(gsub("\\*|\\* |,", "", hhs10)),
mhhi13 = as.numeric(gsub("\\*|\\* |,", "", mhhi13))) -> census10.13
#I noticed that mhhi12 has $ in front of each figure in census10.12 so I will replace em
census10.12 %>% dplyr::arrange_(.dots=names(census10.12)[1:20]) %>%
dplyr::mutate(mhhi12 = gsub("\\$", "", mhhi12), mhhi12 = as.numeric(mhhi12)) -> census10.12
#Check which varaibles are the same across the datasets
census10 %>% arrange_(.dots=names(census10)[1:20]) %>%
select_(.dots = names(census10)[2:20]) %>%
as.data.frame() %>% apply(2, summary) -> c1
census10.12 %>%
select_(.dots = names(census10.12)[2:20]) %>%
as.data.frame() %>% apply(2, summary) -> c2
census10.13 %>%
select_(.dots = names(census10.13)[2:20]) %>%
mutate_each(funs(as.numeric)) %>% apply(2, summary) -> c3
census10.14 %>% arrange_(.dots=names(census10.14)[1:20]) %>%
select_(.dots = names(census10.14)[2:20][-16]) %>% apply(2, summary) -> c4
#IDs which variables are the same, note that I excluded hhs10 from both c2,and c3 since it is NA in c4
# identical(c1,c2);identical(c2,c3);identical(c2[,-16],c4);identical(c3[,-16],c4)
# sapply(1:19, function(x){
# identical(c1[,x],c2[,x])
# })
#So we can join c2(census10.12) and c3(census10.13) on the first 20 variables c.f names(census10.12)[names(census10.12) %in% names(census10.13)]
census10.13$racdiv10 <- as.numeric(census10.12$racdiv10)
census12_14 <- inner_join(census10.12,census10.13) %>%
inner_join(census10.14, by = names(census10.14)[2:20][-16]) %>% #join on 19 variables after we exclude hhs10
dplyr::select(-CSA2010.y,-hhs10.y, CSA2010 = CSA2010.x)
rm(census10.12, census10.13, census10.14, c1,c2,c3,c4)
#### ID which neighborhoods fall into a CSA
##Load data from real properties that contains block info
data <- readr::read_csv(file.path("raw_data", "property.csv.gz"))
#get count of houses per block
data %>% dplyr::group_by(Neighborhood,Block) %>%
dplyr::summarise(count_house = n()) -> houses
dat1 <- subset(data, select = names(data)[c(2:3,6,8,9,11,13:15)])
subset(data, select = c("Block", "Neighborhood", "Location")) -> data
data <- na.omit(data)
new_loc <- sapply(data$Location, function(x) {
y <- substr(x, start = 2, stop = nchar(x) - 1)
strsplit(y, ", ")[[1]]
}
)
new_loc <- t(new_loc)
data <- data.frame(data[,c(1,2)], lon = as.numeric(new_loc[,2]), lat = as.numeric(new_loc[,1]))
dat1$lon <- NA;dat1$lat <- NA
dat1[!is.na(dat1$Neighborhood),] <- data.frame(dat1[!is.na(dat1$Neighborhood),][,1:9],
lon = as.numeric(new_loc[,2]),
lat = as.numeric(new_loc[,1]))
#Step 1
### Check if Lng and Lat fall inside polygons from ESRI Shape file for Child and wellbeing (this has the outcome)
dat.le <- rgdal::readOGR(file.path("wip", "health"), "health", verbose = F)
csa <- as.character(dat.le$CSA2010)
dat.le <- sp::spTransform(dat.le, sp::CRS("+proj=longlat +datum=WGS84")) #SpatialPolygonsDataFrame
# Assignment modified according
sp::coordinates(data) <- ~lon + lat #SpatialPointsDataFrame
real_prop <- data
# Set the projection of the SpatialPointsDataFrame using the projection of the shapefile
sp::proj4string(data) <- sp::proj4string(dat.le)
sp::over(dat.le, data, returnList = T) -> neighbhd_csa #gives which Neighborhood belongs to what CSA
names(neighbhd_csa) <- csa
#Gives a dataframe with cols CSA, Blocks, and Neighborhood so I can match block level info to CSA
neighbhd_csa <- plyr::ldply (neighbhd_csa, data.frame)
clnames <- names(neighbhd_csa)
clnames[1] <- "CSA"
names(neighbhd_csa) <- clnames
#Check if neighborhoods are the same, they should be! (note that the lengths are diff since dat1 has NA, but no matter)
identical(sort(unique(dat1$Neighborhood)), sort(unique(neighbhd_csa$Neighborhood)))
#Careful file size for join without summary is ~2GB!!!
inner_join(neighbhd_csa, dat1) %>%
dplyr::mutate(CityTax = gsub("\\$", "", CityTax), CityTax = as.numeric(CityTax),
StateTax = gsub("\\$", "", StateTax), StateTax = as.numeric(StateTax),
AmountDue = gsub("\\$", "", AmountDue), AmountDue = as.numeric(AmountDue)) %>%
dplyr::group_by(CSA, Neighborhood, Block) %>%
dplyr::summarise(CityTax.med = median(CityTax, na.rm = T), StateTax.med = median(StateTax, na.rm = T),
AmountDue.med = median(AmountDue, na.rm = T), lon.med = median(lon, na.rm = T), lat.med = median(lat)) -> csa.prop
# pryr::object_size(csa.prop)
#Outcome data
health <- readr::read_csv(file.path(".", "raw_data", "child_and_fam_wellbeing.csv"))
clnames <- names(health)
clnames[1] <- "CSA"
names(health) <- clnames
gsub("_[[:digit:]]*","",names(health))[-1] -> variables
variables[variables == "mort1"] <- "mort01"
variables <- sapply(variables, function(x){
substr(x, start = 1, stop = nchar(x) - 2)
})
unname(variables) -> variables
unique(variables) -> var.names
setdiff(names(health), grep(paste0("mort"), names(health), value = T)) ->rm.mort
#Change from short to long
health.long <- lapply(var.names[var.names!= "mort"], function(x){
#get the columns
columns <- grep(paste0(x),rm.mort, value = T)
#get the time in years
time <- sapply(gsub("[^_[:digit:]]","",columns), function(x){
substr(x, start = nchar(x)-1, stop = nchar(x))
}
)
unname(time) -> time
#Select the columns
subset(health, select = c("CSA",columns)) -> dat.h
n <- dim(dat.h)[1]
# print(length(time))
dat.h <- tidyr::gather(dat.h, variable, value, -CSA)
dat.h$time <- rep(as.numeric(time), each = n)
dat.h
# data.frame(tidyr::gather(dat.h, variable, value, -CSA), time = time)
# rbind(cbind(tidyr::gather(dat.h, variable, value, -CSA), time))
})
plyr::ldply(health.long, data.frame) -> health.long
#get the columns
columns <- sapply(strsplit(grep(paste0("mort"),names(health), value = T),"_"),function(x) x[1])
unique(columns) -> columns
health.long2 <- lapply(columns, function(x){
#get the time in years
time <- sapply(strsplit(grep(paste0("^", x, "_"),
names(health), value = T),"_"),function(x) x[2])
time <- as.numeric(time)
#Select the columns
subset(health, select = c("CSA",
grep(paste0("^", x, "_"), names(health), value = T))
) -> dat.h
n <- dim(dat.h)[1]
# print(length(time))
dat.h <- tidyr::gather(dat.h, variable, value, -CSA)
dat.h$time <- rep(as.numeric(time), each = n)
dat.h
# data.frame(tidyr::gather(dat.h, variable, value, -CSA), time = time)
# rbind(cbind(tidyr::gather(dat.h, variable, value, -CSA), time))
})
plyr::ldply(health.long2, data.frame) -> health.long2
health.long <- rbind(health.long, health.long2)
rm(health.long2, columns, rm.mort, var.names, variables, new_loc)
#Merge
health.sub <- subset(health, select = c("CSA", "LifeExp11",
"LifeExp12", "LifeExp13",
"LifeExp14"))
#This will have the same number of rows as csa.prop since block neighborhood combinations are unique
inner_join(csa.prop, health.sub) -> csa.prop.health
rm(csa, dat.le,data, new_loc, neighbhd_csa, dat1)
#Crime data
ifiles <- unzip(file.path("raw_data", "census_blk.zip"), list = T)
ifiles.name <- substr(ifiles[,1][1], 1, nchar(ifiles[,1][1]) - 4)
if(!file.exists( file.path("wip", ifiles.name ) )){
dir.create(file.path("wip", ifiles.name ))
unzip(file.path("raw_data", "census_blk.zip"),
files = grep("*[.]", ifiles[,1], value = T), exdir = file.path("wip",ifiles.name), junkpaths = T)
}
##Load data from crime data that contains street,Neighborhood and Police District info
data <- readr::read_csv(file.path("raw_data", "street_crime.csv.gz"))
names(data)[c(4,11)] <- c("Street",names(data)[4])
dat1 <- data #subset(data, select = -Location)
subset(data, select = c("Street", "Neighborhood", "Location", "CrimeDate")) -> data
data <- data[!is.na(data$Location),]
new_loc <- sapply(data$Location, function(x) {
y <- substr(x, start = 2, stop = nchar(x) - 1)
strsplit(y, ", ")[[1]]
}
)
new_loc <- t(new_loc)
#side note. Records have been geocoded to the hundredth block and not the precise point that the crime took place.
data <- data.frame(data[,c(1,2, 4)], lon = as.numeric(new_loc[,2]), lat = as.numeric(new_loc[,1]))
dat1$lon <- NA;dat1$lat <- NA
dat1[!is.na(dat1$Location),][,-11] <- data.frame(dat1[!is.na(dat1$Location),][,-c(11,13,14)],
lon = as.numeric(new_loc[,2]),
lat = as.numeric(new_loc[,1]))
dat1 <- subset(dat1, select = -Location)
#Step 1
### Check if Lng and Lat fall inside polygons from ESRI Shape file for Child and wellbeing (this has the outcome)
dat.le <- rgdal::readOGR(file.path("wip", "blk2010"), "blk2010", verbose = F)
block <- as.character(dat.le$BLOCK)
dat.le <- sp::spTransform(dat.le, sp::CRS("+proj=longlat +datum=WGS84")) #SpatialPolygonsDataFrame
#
# Assignment modified according
sp::coordinates(data) <- ~lon + lat #SpatialPointsDataFrame
# Set the projection of the SpatialPointsDataFrame using the projection of the shapefile
sp::proj4string(data) <- sp::proj4string(dat.le)
sp::over(dat.le, data, returnList = T) -> block_crime #gives which Neighborhood belongs to what crime block
unlink(file.path("wip", "blk2010"), force = T, recursive = T)
names(block_crime) <- block
#Gives a dataframe with cols Block, Neighborhood and street
block_crime <- plyr::ldply (block_crime, data.frame)
clnames <- names(block_crime)
clnames[1] <- "Blocks"
names(block_crime) <- clnames
block_crime$Neighborhood <- toupper(block_crime$Neighborhood)
block_crime <- block_crime %>%
dplyr::mutate(year = year(as.Date(CrimeDate, "%m/%d/%Y")))
block_crime <- subset(plyr::arrange(block_crime, Neighborhood, Blocks, year, Street, CrimeDate),
select = c(Neighborhood, Blocks, year, Street, CrimeDate))
block_crime <- unique(block_crime)
#Step 2
##Load data from real properties that contains block info
data <- readr::read_csv(file.path("raw_data", "property.csv.gz"))
dat2 <- subset(data, select = names(data)[c(2:3,6,8,9,11,13:15)])
subset(data, select = c("Block", "Neighborhood", "Location")) -> data
data <- na.omit(data)
new_loc <- sapply(data$Location, function(x) {
y <- substr(x, start = 2, stop = nchar(x) - 1)
strsplit(y, ", ")[[1]]
}
)
new_loc <- t(new_loc)
data <- data.frame(data[,c(1,2)], lon = as.numeric(new_loc[,2]), lat = as.numeric(new_loc[,1]))
dat2$lon <- NA;dat2$lat <- NA
dat2[!is.na(dat2$Neighborhood),] <- data.frame(dat2[!is.na(dat2$Neighborhood),][,1:9],
lon = as.numeric(new_loc[,2]),
lat = as.numeric(new_loc[,1]))
# Assignment modified according
sp::coordinates(data) <- ~lon + lat #SpatialPointsDataFrame
# Set the projection of the SpatialPointsDataFrame using the projection of the shapefile
sp::proj4string(data) <- sp::proj4string(dat.le)
sp::over(dat.le, data, returnList = T) -> block_prop #gives which Neighborhood-block belongs to what real property Neighbhd-block
names(block_prop) <- block
#Gives a dataframe with cols Block, Neighborhood and street
block_prop <- plyr::ldply (block_prop, data.frame)
clnames <- names(block_prop)
clnames[1] <- "Blocks"
names(block_prop) <- clnames
block_prop$Neighborhood <- toupper(block_prop$Neighborhood)
block_prop <- subset(plyr::arrange(block_prop, Neighborhood, Blocks, Block), select = c(Neighborhood, Blocks, Block))
block_prop <- unique(block_prop)
# Get which block numeration corresponds to street block in real_prop taxes
dplyr::inner_join(block_crime,block_prop) -> block_crime_pop
dat1$Neighborhood <- toupper(dat1$Neighborhood)
## Need to summarize otherwise the vanilla form is ~7.9 GB
block_crime_pop %>%
inner_join(dat1[,-c(12,13)]) %>% #Removing lon and lat since it is approximate for crime data
inner_join(dat2[,c(1,4:7, 10:11)]) %>%
dplyr::mutate(CityTax = gsub("\\$", "", CityTax), CityTax = as.numeric(CityTax),
StateTax = gsub("\\$", "", StateTax), StateTax = as.numeric(StateTax),
AmountDue = gsub("\\$", "", AmountDue), AmountDue = as.numeric(AmountDue),
TotalIncidents = as.numeric(`Total Incidents`)) %>%
dplyr::group_by(Neighborhood, Block, year) %>%
dplyr::summarise(TotalIncidents = sum(TotalIncidents, na.rm = T),
mean(CityTax, na.rm = T),
mean(StateTax, na.rm = T),
mean(AmountDue, na.rm = T),
median(lon, na.rm = T),
median(lat, na.rm = T)) -> block_crime_pop
#Step 3
##Load data from real properties that contains block info
data <- readr::read_csv(file.path("raw_data", "vacants.csv"))
dat3 <- subset(data, select = names(data)[c(2,4:6)])
subset(data, select = c("BuildingAddress", "Neighborhood", "Location", "NoticeDate")) -> data
data <- na.omit(data)
new_loc <- sapply(data$Location, function(x) {
y <- substr(x, start = 2, stop = nchar(x) - 1)
strsplit(y, ", ")[[1]]
}
)
new_loc <- t(new_loc)
data <- data.frame(data[,c(1,2, 4)], lon = as.numeric(new_loc[,2]), lat = as.numeric(new_loc[,1]))
dat3$lon <- NA;dat3$lat <- NA
data.frame(dat3[!is.na(dat3$BuildingAddress) & !is.na(dat3$Neighborhood) ,][,1:4],
lon = as.numeric(new_loc[,2]),
lat = as.numeric(new_loc[,1])) -> dat3[!is.na(dat3$BuildingAddress) & !is.na(dat3$Neighborhood),]
#Convert Noticedate to date obj and then extract the year
dat3 %>%
dplyr::mutate(year = year(as.Date(NoticeDate, "%m/%d/%Y")),Neighborhood = toupper(Neighborhood)) -> dat3
# Assignment modified according
sp::coordinates(data) <- ~lon + lat #SpatialPointsDataFrame
# Set the projection of the SpatialPointsDataFrame using the projection of the shapefile
sp::proj4string(data) <- sp::proj4string(dat.le)
sp::over(dat.le, data, returnList = T) -> block_vac #gives which Neighborhood-block belongs to what vacant property Neighbhd-block
names(block_vac) <- block
#Gives a dataframe with cols Block, Neighborhood and street
block_vac <- plyr::ldply (block_vac, data.frame)
clnames <- names(block_vac)
clnames[1] <- "Blocks"
names(block_vac) <- clnames
block_vac$Neighborhood <- toupper(block_vac$Neighborhood)
block_vac <- subset(plyr::arrange(block_vac, Neighborhood, Blocks, BuildingAddress, NoticeDate),
select = c(Neighborhood, Blocks, BuildingAddress, NoticeDate))
block_vac <- unique(block_vac)
# Get which block numeration corresponds to street block in real_prop taxes
#Join to real_property taxes dataset by Neighbourhood and block(numerical) to get which street and Neighbourhood correspond to what
#to what Neighbourhood and block in real_property taxes
dplyr::inner_join(block_vac,block_prop) -> block_vac_pop
block_vac_pop %>%
dplyr::inner_join(dat3, by = c("Neighborhood", "BuildingAddress", "NoticeDate")) %>% #Join to vacant_building dataset by street, nbhd, and date
dplyr::group_by(Neighborhood, Block = Block.x, Year = year) %>% #Group by Neighbourhood, block and year to obtain summary stats
dplyr::summarise(Count_vancant = length(BuildingAddress)) -> block_vac_pop
rm(dat.le,dat1, dat2, dat3, block,
new_loc, ifiles, ifiles.name,clnames, data)
##For block_crime_pop and block_vac_pop, I want the "years' variable to rep all the possible years between 2010 and 2016
block_crime_pop -> block_crime_pop1
block_crime_pop1 %>%
dplyr::select(Neighborhood, Block) %>%
unique() -> block_crime_pop1
block_crime_pop1[rep(seq_len(nrow(block_crime_pop1)), each=5),] -> block_crime_pop1
block_crime_pop1$year <- rep(c(2010:2014), n_distinct(block_crime_pop1))
names(block_crime_pop) <- c(names(block_crime_pop)[1:4], "CityTax.avg",
"StateTax.avg", "AmountDue.avg",
"lon.med", "lat.med")
block_crime_pop1 %>%
left_join(block_crime_pop) -> crime_pop
crime_pop_impute <- crime_pop %>%
subset(select = -Block) %>%
dplyr::group_by(Neighborhood, year) %>%
summarise_all(mean, na.rm = T)
# Impute neighbourhood average for the particular year
attach(crime_pop)
crime_pop[is.na(TotalIncidents), ][,c(1,3)] %>%
inner_join(crime_pop_impute) -> crime_pop[is.na(TotalIncidents), ][,-2]
crime_pop[is.na(CityTax.avg), ][,c(1,3)] %>%
inner_join(crime_pop_impute) -> crime_pop[is.na(CityTax.avg), ][,-2]
crime_pop[is.na(StateTax.avg), ][,c(1,3)] %>%
inner_join(crime_pop_impute) -> crime_pop[is.na(StateTax.avg), ][,-2]
crime_pop[is.na(AmountDue.avg), ][,c(1,3)] %>%
inner_join(crime_pop_impute) -> crime_pop[is.na(AmountDue.avg), ][,-2]
#After imputation some years just have missing info
crime_pop %>%
dplyr::mutate(TotalIncidents = ifelse(is.na(TotalIncidents), 0, TotalIncidents),
CityTax.avg = ifelse(is.na(CityTax.avg), 0, CityTax.avg),
StateTax.avg = ifelse(is.na(StateTax.avg), 0, StateTax.avg),
AmountDue.avg = ifelse(is.na(AmountDue.avg), 0, AmountDue.avg) ) -> crime_pop
detach(crime_pop)
block_vac_pop -> block_vac_pop1
block_vac_pop1 %>%
dplyr::select(Neighborhood, Block) %>%
unique() -> block_vac_pop1
block_vac_pop1[rep(seq_len(nrow(block_vac_pop1)), each=5),] -> block_vac_pop1
block_vac_pop1$Year <- rep(c(2010:2014), n_distinct(block_vac_pop1))
names(block_vac_pop) <- c(names(block_vac_pop)[1:3], "Count_vacant")
block_vac_pop1 %>%
left_join(block_vac_pop) -> vac_pop
vac_pop$Count_vacant <- ifelse(is.na(vac_pop$Count_vacant), 0, vac_pop$Count_vacant)
rm(block_crime_pop1, block_vac_pop1,block_crime_pop, block_vac_pop)
rm(block_crime, block_prop, block_vac, crime_pop_impute, csa.prop)
##Create analyses data
names(csa.prop.health) <- tolower(names(csa.prop.health))
names(vac_pop) <- tolower(names(vac_pop))
names(crime_pop) <- tolower(names(crime_pop)) #Note that lat and lon here refer to that gotten from real_prop data
names(houses) <- tolower(names(houses))
#Co-ordinates
csa.prop.health %>%
dplyr::group_by(csa) %>%
dplyr::summarise(lon.med.avg = mean(lon.med), lat.med.avg = mean(lat.med)) -> coord.lon_lat
## 2014
# crime_pop[crime_pop$year == 2014,]
csa.prop.health[,c(1:3, 12)] %>%
left_join(subset(crime_pop, year == 2014, select = -c(lon.med, lat.med))) %>%
left_join(subset(vac_pop, year == 2014)) %>%
dplyr::mutate(count_vacant = as.numeric(ifelse(is.na(count_vacant), 0, count_vacant)))-> health_prop_le_crime_vac_block
health_prop_le_crime_vac_block %>%
inner_join(houses) %>%
dplyr::mutate(prop.vacant = count_vacant/count_house) -> health_prop_le_crime_vac_block
#For any variables that are NA use the neighbourhood average of the csa they belong to for imputation
health_prop_le_crime_vac_block %>%
dplyr::select(-year, -block, -lifeexp14) %>%
dplyr::group_by(csa, neighborhood) %>%
dplyr::summarise( totalincidents = mean(totalincidents, na.rm = T),
citytax.avg = mean(citytax.avg, na.rm = T),
statetax.avg = mean(statetax.avg, na.rm = T),
amountdue.avg = mean(amountdue.avg, na.rm = T),
prop.vacant = mean(prop.vacant, na.rm = T)) -> impute
health_prop_le_crime_vac_block[is.na(health_prop_le_crime_vac_block$totalincidents), c(1:4)] %>%
inner_join(impute) -> health_prop_le_crime_vac_block[is.na(health_prop_le_crime_vac_block$totalincidents),][,-c(5, 10:11)]
rm(impute)
#For any variables that are still NA use the CSA average that they belong to for imputation
health_prop_le_crime_vac_block %>%
dplyr::select(-year, -block, -lifeexp14) %>%
dplyr::group_by(csa) %>%
dplyr::summarise( totalincidents = mean(totalincidents, na.rm = T),
citytax.avg = mean(citytax.avg, na.rm = T),
statetax.avg = mean(statetax.avg, na.rm = T),
amountdue.avg = mean(amountdue.avg, na.rm = T),
prop.vacant = mean(prop.vacant, na.rm = T)) -> impute
health_prop_le_crime_vac_block[is.na(health_prop_le_crime_vac_block$totalincidents), c(1:4)] %>%
inner_join(impute) -> health_prop_le_crime_vac_block[is.na(health_prop_le_crime_vac_block$totalincidents),][,-c(5, 10:11)]
rm(impute)
#Aggregate by CSA
health_prop_le_crime_vac_block %>%
dplyr::select(-year, -block, -neighborhood) %>%
filter(!is.nan(totalincidents)) %>%
# mutate(count_vacant = as.numeric(count_vacant)) %>%
dplyr::group_by(csa) %>%
summarise_all(mean) -> csa.data
census12_14 %>% dplyr::select(csa = CSA2010, tpop = tpop10, racdiv10,mhhi13, femhhs10) %>%