-
Notifications
You must be signed in to change notification settings - Fork 1
/
RATScreenerRMD.Rmd
1778 lines (1415 loc) · 95.6 KB
/
RATScreenerRMD.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
---
output:
html_document:
toc: true
toc_float: true
code_folding: hide
highlight: monochrome
css: custom.css
---
![](./data/images/rats_title.png)
*This project was conducted as part of the University of Pennsylvania’s Master of Urban Spatial Analytics/Smart Cities Practicum in Spring 2023, which was taught by Michael Fichman and Matt Harris. In addition to Michael and Matt, we would like to thank Ren Massari, Peter Casey, and Kevin Wilson of The Lab at DC for their support and guidance on this project.*
**[View RATScreener Web App](https://henryfeinstein.github.io/musa-rats/site/)** | **[View RATScreener Github Repository](https://github.com/henryfeinstein/musa-rats)** | **[Return to MUSA 801 Projects page](https://pennmusa.github.io/MUSA_801.io/)**
```{r message=FALSE, warning=FALSE, include=FALSE}
#setup
# Rmarkdown global setting
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(message = FALSE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(cache = TRUE)
knitr::opts_chunk$set(fig.align = 'center')
#----------------------------------------------------------------------------------------------------------
# Import libraries
library(tidyverse)
library(tidycensus)
library(sf)
library(spdep)
library(caret)
library(ckanr)
library(FNN)
library(grid)
library(gridExtra)
library(ggcorrplot)# plot correlation plot
library(corrplot)
library(corrr) # another way to plot correlation plot
library(kableExtra)
library(jtools) # for regression model plots
library(ggstance) # to support jtools plots
library(ggpubr) # plotting R^2 value on ggplot point scatter
library(broom.mixed) # needed for effects plots
library(knitr)
library(rmarkdown)
library(RSocrata)
library(viridis)
library(ggplot2)
library(stargazer)
library(XML)
library(data.table)
library(ggpmisc)
library(patchwork)
library(spatstat)
library(raster)
library(classInt) # for KDE and ML risk class intervals
library(tableHTML)
library(exactextractr)
library(sp)
library(units)
library(lubridate)
library(pscl)
library(cvms)
library(yardstick)
library(plotROC)
library(gganimate)
library(gifski)
library(randomForest)
library(caret)
library(e1071) #SVM
library(pscl) # Zero-inflated
library(gbm) #Gradient Boosting
library(rpart) # Decision Tree
library(irr)
library(MLmetrics)
library(riem)
library(rjson)
#----------------------------------------------------------------------------------------------------------
# Temp
source("https://raw.githubusercontent.com/urbanSpatial/Public-Policy-Analytics-Landing/master/functions.r")
root.dir = "https://github.com/henryfeinstein/musa-rats/blob/main/data/"
# Etc
options(scipen=999)
options(tigris_class = "sf")
#----------------------------------------------------------------------------------------------------------
# functions
st_c <- st_coordinates
st_coid <- st_centroid
plotTheme <- theme(
plot.title =element_text(size=12),
plot.subtitle = element_text(size=8),
plot.caption = element_text(size = 6),
axis.text.x = element_text(size = 10, angle = 45, hjust = 1),
axis.text.y = element_text(size = 10),
axis.title.y = element_text(size = 10),
# Set the entire chart region to blank
panel.background=element_blank(),
plot.background=element_blank(),
#panel.border=element_rect(colour="#F0F0F0"),
# Format the grid
panel.grid.major=element_line(colour="#D0D0D0",size=.2),
axis.ticks=element_blank())
mapThememin <- function(base_size = 10, title_size = 12, small_size = 8) {
theme(
text = element_text( color = "black"),
plot.title = element_text(size = title_size, colour = "black", hjust = 0.5),
plot.subtitle=element_text(size = base_size, colour = "black", hjust = 0.5, face="italic"),
plot.caption=element_text(size = small_size, colour = "black", hjust = 0.5),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
strip.text.x = element_text(size = small_size, face="italic"),
strip.text.y = element_text(size = small_size, face="italic"),
strip.background = element_rect(colour="transparent", fill="transparent"),
legend.title = element_text(size = small_size),
legend.text = element_text(size = small_size),
legend.key.size = unit(0.4, "cm"))
}
mapThememin2 <- function(base_size = 8, title_size = 10, small_size = 6) {
theme(
text = element_text( color = "black"),
plot.title = element_text(size = title_size, colour = "black", hjust = 0.5),
plot.subtitle=element_text(size = base_size, colour = "black", hjust = 0.5, face="italic"),
plot.caption=element_text(size = small_size, colour = "black", hjust = 0.5),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
strip.text.x = element_text(size = base_size),
strip.text.y = element_text(size = base_size),
strip.background = element_rect(colour="transparent", fill="transparent"),
legend.title = element_text(size = small_size),
legend.text = element_text(size = small_size),
legend.key.size = unit(0.25, "cm"))
}
corTheme <- function(base_size = 10, title_size = 12, small_size = 8){
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
text = element_text(size = 10),
panel.background = element_rect(fill = greyPalette5[1]),
axis.title.x = element_text(size = small_size),
axis.title.y = element_text(size = small_size),
plot.subtitle = element_text(hjust = 0.5, size = base_size),
plot.title = element_text(hjust = 0.5, size = title_size),
plot.caption=element_text(size = small_size, colour = "black", hjust = 0.5),
strip.background = element_rect(colour="transparent", fill="transparent"))
}
corTheme2 <- function(base_size = 10, title_size = 12, small_size = 8){
theme(axis.text = element_text(size = small_size),
text = element_text(size = 10),
panel.background = element_rect(fill = greyPalette5[1]),
axis.title.x = element_text(size = small_size),
axis.title.y = element_text(size = small_size),
plot.subtitle = element_text(hjust = 0.5, size = base_size, face="italic"),
plot.title = element_text(hjust = 0.5, size = title_size),
plot.caption=element_text(size = small_size, colour = "black", hjust = 0.5),
strip.background = element_rect(colour="transparent", fill="transparent"),
strip.text.x = element_text(size = small_size, face="italic"),
strip.text.y = element_text(size = small_size, face="italic"))
}
corTheme3 <- function(base_size = 9, title_size = 11, small_size = 7){
theme(axis.text = element_text(size = small_size),
text = element_text(size = 10),
panel.background = element_rect(fill = greyPalette5[1]),
axis.title.x = element_text(size = small_size),
axis.title.y = element_text(size = small_size),
plot.subtitle = element_text(hjust = 0.5, size = base_size, face="italic"),
plot.title = element_text(hjust = 0.5, size = title_size),
plot.caption=element_text(size = small_size, colour = "black", hjust = 0.5))
}
corTheme4 <- function(base_size = 9, title_size = 11, small_size = 7){
theme(axis.text = element_text(size = small_size),
text = element_text(size = 10),
panel.background = element_rect(fill = greyPalette5[1]),
axis.title.x = element_text(size = small_size),
axis.title.y.right = element_text(size = small_size),
plot.subtitle = element_text(hjust = 0.5, size = base_size, face="italic"),
plot.title = element_text(hjust = 0.5, size = title_size),
plot.caption=element_text(size = small_size, colour = "black", hjust = 0.5))
}
q5 <- function(variable) {as.factor(ntile(variable, 5))}
q <- function(variable) {as.factor(ntile(variable, 5))}
qBr <- function(df, variable, rnd) {
if (missing(rnd)) {
as.character(quantile(round(df[[variable]],0),
c(.01,.2,.4,.6,.8), na.rm=T))
} else if (rnd == FALSE | rnd == F) {
as.character(formatC(quantile(df[[variable]],
c(.01,.2,.4,.6,.8), na.rm=T),
digits = 3))
}
}
qBr2 <- function(df, variable, rnd) {
if (missing(rnd)) {
as.character(quantile(round(df[[variable]]*100,0)/100,
c(.01,.2,.4,.6,.8), na.rm=T))
} else if (rnd == FALSE | rnd == F) {
as.character(formatC(quantile(df[[variable]],
c(.01,.2,.4,.6,.8), na.rm=T),
digits = 3))
}
}
qBr3 <- function(df, variable, rnd) {
if (missing(rnd)) {
as.character(round(quantile(round(df[[variable]]*1000000,0),
c(.01,.2,.4,.6,.8), na.rm=T)),0)
} else if (rnd == FALSE | rnd == F) {
as.character(formatC(quantile(df[[variable]],
c(.01,.2,.4,.6,.8), na.rm=T),
digits = 3))
}
}
substrRight <- function(x, n){
substr(x, nchar(x)-n+1, nchar(x))
}
nn_function <- function(measureFrom,measureTo,k) {
measureFrom_Matrix <- as.matrix(measureFrom)
measureTo_Matrix <- as.matrix(measureTo)
nn <- get.knnx(measureTo, measureFrom, k)$nn.dist
output <- as.data.frame(nn) %>%
rownames_to_column(var = "thisPoint") %>%
gather(points, point_distance, V1:ncol(.)) %>%
arrange(as.numeric(thisPoint)) %>%
group_by(thisPoint) %>%
summarize(pointDistance = mean(point_distance)) %>%
arrange(as.numeric(thisPoint)) %>%
dplyr::select(-thisPoint) %>%
pull()
return(output)
}
myCrossValidate <- function(dataset, id, dependentVariable, indVariables) {
allPredictions <- data.frame()
cvID_list <- unique(dataset[[id]])
for (i in cvID_list) {
thisFold <- i
cat("This hold out fold is", thisFold, "\n")
fold.train <- filter(dataset, dataset[[id]] != thisFold) %>% as.data.frame() %>%
dplyr::select(id, geometry, indVariables, dependentVariable)
fold.test <- filter(dataset, dataset[[id]] == thisFold) %>% as.data.frame() %>%
dplyr::select(id, geometry, indVariables, dependentVariable)
regression <-
glm(countMVTheft ~ ., family = "poisson",
data = fold.train %>%
dplyr::select(-geometry, -id))
thisPrediction <-
mutate(fold.test, Prediction = predict(regression, fold.test, type = "response"))
allPredictions <-
rbind(allPredictions, thisPrediction)
}
return(st_sf(allPredictions))
}
#----------------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------------
# LoadAPI
census_api_key("4bbe4bead4e5817f6a6b79e62c5bea69e77f1887", overwrite = TRUE)
```
## Abstract
Rats thrive in cities. However, the feeling is not mutual according to city residents. In 2021, DC’s 311 Service received over 11,000 requests for rodent inspection and abatement. As inspection requests continue to increase after a pandemic-induced spike in rat populations, inspection departments are inundated with requests for treatment [1]. However, inspection and treatment require resources: personnel, time, and money. With over half of the inspection requests in DC not finding evidence of rats, the inspection and treatment process is costly to the city.
This project explores the spatial and time patterns related to vermin infestation in order to develop a predictive model for estimating the probability of rat detection in a given area of Washington, DC. The information provided by the tool will allow city health and vermin inspectors to prioritize exterior inspections of properties suspected of vermin infestation based on the actual likelihood of rodents being detected. We aim to create a proof-of-concept infestation forecast that will be used as the basis of an inspection optimization data system and web app, which will allow for more targeted and efficient inspections.
## 1. Introduction: Context & Use Case
Municipal rodent management is a critical part of local government operations. In many cities, rodent infestation is persistent and can have detrimental impacts on the public infrastructure, local economy, overall health and well-being of both residents and the environment [2]. Cities face the monumental challenge of conducting large-scale rodent management, responding to resident complaints, and educating the public on the cause of rodent infestations.
This project aims to develop a screening tool that prioritizes DC 311 requests for rodent inspection based on the likelihood of rat detection on a given block. The goal of this work is to more effectively distribute resources used for inspection and treatment with the hopes of freeing up resources for other rodent management needs. The ultimate goal is to aid in the abatement of DC’s rat infestation issues.
### 1.1: Understanding Urban Vermin Infestations
Norway rats, also known as brown rats, are the most common species found in U.S. cities. These rats are commonly associated with sanitation problems in cities. While this reputation is accurate, rats are also behind many other problems that occur in urban areas. Rodents can cause structural issues by burrowing in streets or buildings, causing property damage that can result in the loss of businesses and homes. Rats also cause power outages, internet blackouts, and fires by gnawing on gas lines or electrical wires. Finally, they also pose a risk to public health and well-being as they can contaminate food, carry diseases, and spread pathogens [1].
Cities, with their large and dense human populations, provide optimal habitats for rats. Colonies of rats can stretch across entire city blocks. Rats utilize human-made infrastructure by traveling via sewer systems or utility lines to reach neighboring buildings. Food is the most important resource that cities provide to rats. They often explore their territories for new food sources at night when there is less human activity. City residents know that residential and commercial trash cans and dumpsters are often not tightly secured, making them prime opportunities for rats to find food. Ultimately, human behaviors and food waste are a main driving force behind urban rat infestations [3].
### 1.2: DC's Current Rat Infestation Abatement Approach
The Distric of Columbia Department of Health (DC Health) is responsible for the city’s rodent control program. Currently, DC Health aims to protect public health by reducing rodent activity through a combination of proactive surveys, inspections, baiting, enforcement, community outreach and distribution of educational materials. This work is performed by the Rodent and Vector Control Division, but relies on interagency cooperation.
DC’s business-as-usual approach relies on professional knowledge and ad-hoc decision-making on a daily basis. Residents can request inspections from DC Health and the Rodent and Vector Control Division by submitting reports through 311. When a request is received, DC Health inspectors are sent to the location of the call to inspect and treat any infestations. However, there are more inspection requests than inspectors can handle on a daily basis. There is currently no formal prioritization of inspection requests.This strategy allows for inefficiencies in terms of employee time and financial resources, limiting the benefits of the inspection services to the public.
### 1.3: Our Approach to Improving Rat Inspection Efficiency
Our project aims to disrupt the current inefficiencies in inspection services by developing an inspection optimization system, called RATScreener. The RATScreener system will be based on a predictive model that forecasts the likelihood of infestation based on a range of spatial, population, and built environment variables. This system will assign probabilities of infestation to specific blocks and provide an overview of hotspot areas in DC.
This approach will allow the inspection office to prioritize incoming requests and understand the probability of actual infestations. DC Health inspectors can then make more informed decisions, target inspections to areas of high infestation probability, and reduce strain on limited resources within the department.
### 1.4: RATScreener Overview
We present an overview of the modeling process behind RATScreener below. Our process began by collecting data and assigning variables to each block in DC. We then run our model and calculate predictions for each block, which are then categorized by priority based on the probability of rat detection. As new requests come in, RATScreener identifies the block in which the address is located and assigns a priority level based on the block’s risk of rat detection. Finally, a list of prioritized requests is presented to inspectors via the RATScreener app.
![An overview of the process behind RATScreener](.data/images/rats_process.png)
## 2. Exploratory Analysis
In the exploratory analysis phase of this project, we aim to identify the patterns of rat infestation across time and space. Our analysis attempts to understand the spatial process associated with infestation and the relationships between built environment, spatial, and population variables.
### 2.1: Processing Rat Inspection Outcomes as the Dependent Variable
The primary independent variable that the RATScreener model is trying to predict is whether a given 311 request for a rat inspection will lead to the discovery and treatment of an actual infestation. DC Health provided a dataset of all rat inspection requests placed through DC’s 311 Service between 2015 and 2018. The dataset includes the address the request was placed at, administrative information, and field notes from the resulting inspection.
A text analysis was performed on the field notes to assign each 311 request to a “rats found/no rats found” binary variable. The analysis detected words such as “baited,” “treatment,” and “treated” to indicate that rat activity was identified, and phrases such as “no evidence,” “no rat burrows,” or “no rat activity” as indications that no evidence of rats was found. The resulting binary variable is used as the independent variable for the remainder of the analysis.
As previously mentioned, rat colonies tend to be limited by barriers in the built environment such as roads and other impervious surfaces. Because of this, rat inspections typically cover an entire block, not just the address that the 311 request came from. In order to have the modeling process reflect this approach to treatment, the RATScreener tool predicts the likelihood of rat infestation at the city block level. After creating city block polygons using DC Open Data's [Street Centerlines shapefile](https://opendata.dc.gov/datasets/DCGIS::street-centerlines-2013/explore?location=38.894921%2C-77.025952%2C12.88), the binary variable described above was translated to a block-level binary variable of whether rats had been found anywhere on that block in the past. This process yielded 5,243 city blocks in DC which are used for the remainder of the analysis.
In addition to the 311 data shown above, DC Health provided us with a dataset of 100 inspections performed across the city at locations which were not connected to a 311 request. This secondary dataset is used later in the analysis for additional validation and to better understand how reliant the models are on patterns seen in 311 data specifically, rather than the underlying data of actual rat infestation.
### 2.2: Exploring Risk of Rat Infestation
```{r message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
# Load rat infestation dataset and spatialize
Rats <- read.csv("./data/rats_to_blocks.csv.gz", header = TRUE) %>%
na.omit() %>%
st_as_sf(.,coords=c("LONGITUDE","LATITUDE"),crs=4326) %>%
st_transform('ESRI:102685') %>%
mutate(month = month(ymd_hms(SERVICEORDERDATE)),
year = year(ymd_hms(SERVICEORDERDATE)),
serviceday = ymd(substr(SERVICEORDERDATE,1,10))) %>%
dplyr::select(P0010001, index_right, SERVICEORDERDATE, INSPECTIONDATE, SERVICENOTES, serviceday, WARD, week, year, month, calls, activity, geometry)
# load street centerlines from DC open data
centerlines <- st_read("./data/Street_Centerlines_2013/Street_Centerlines_2013.geojson") %>%
st_transform("ESRI:102685") %>%
filter(ROADTYPE == "Street")
# convert street centerlines to block polygons
blocks <- as.data.frame(st_collection_extract(st_polygonize(st_union(centerlines)))) %>%
dplyr::mutate(block_id = row_number()) %>%
st_as_sf()
boundary <- st_union(blocks)
# spatial join to assign each rat datapoint to a block polygon
rats_block_join <- st_join(Rats, blocks)
# count observations per block for mapping
block_dat <- left_join(blocks, rats_block_join %>%
st_drop_geometry() %>%
group_by(block_id) %>%
dplyr::summarize(inspection_count = n(),
rats_found_yn = ifelse(1 %in% activity, 1, 0),
rats_found_count = sum(activity))) %>%
dplyr::mutate(inspection_count = replace_na(inspection_count, 0),
rats_found_yn = replace_na(rats_found_yn, 0),
rats_found_count = replace_na(rats_found_count, 0),
area_acres = as.numeric(st_area(.)) / 43560) %>%
dplyr::mutate(found = case_when(rats_found_yn == "0" ~ "not_found",
rats_found_yn == "1" ~ "found"))
# count of inspections map
count_inspections <- ggplot() + geom_sf(data = block_dat, aes(fill = inspection_count), color = "transparent") +
scale_fill_gradient(low = "#e3b1b1", high = "#E91C1C", name = "Count") +
labs(title = "Count of Inspections by Block",
subtitle = "",
caption = "") +
mapThememin2()
# count of rats found per block map
count_rats <- ggplot() + geom_sf(data = block_dat, aes(fill = rats_found_count), color = "transparent") +
scale_fill_gradient(low = "#e3b1b1", high = "#E91C1C", name = "Count") +
labs(title = "Number of Rat Detection Instances by Block",
subtitle = "",
caption = "") +
mapThememin2()
# any rats found y/n per block map
rats_yn <- ggplot() +
geom_sf(data = block_dat, aes(fill = found), color = "transparent") +
scale_fill_manual(values = c("not_found" = "#e3b1b1", "found" = "#E91C1C"), name = "Outcome") +
labs(title = "Blocks by Binary Found/Not Found Variable",
subtitle = "",
caption = "") +
mapThememin2()
# rat ID rate per block map
rat_id <- ggplot() + geom_sf(data = block_dat, aes(fill = rats_found_count / inspection_count), color = "transparent") +
scale_fill_gradient(low = "#e3b1b1", high = "#E91C1C", name = "Detection Rate") +
labs(title = "Rat ID Rate (Count of Rats Found / Number of Inspections) \nby Block",
subtitle = "",
caption = "") +
mapThememin2()
grid.arrange(count_inspections, count_rats, rats_yn, rat_id, ncol = 2)
```
When viewing the distribution of 311 inspection requests and the outcomes of those requests, a clear pattern emerges. As the maps above show, inspections requests and rat infestations in 311 data are heavily concentrated in the center of DC, which is also the densest part of the city. This pattern is unsurprising given that human density drives rat population increase through the increased presence of food and garbage. One particularly variable to examine is what we call here the "Rat ID Rate," which gives the percentage of all 311 inspection requests that actually result in evidence of rats being identified for a given block. The patterns in Rat ID Rate generally follow the overall patterns in where rats are being seen, suggesting that 311 calls are in fact responding at least to some extent to the reality of rat distribution throughout the city.
### 2.3: Independent Variables
```{r load and join indepdent vars, message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
Data311 <-
rbind(st_read("./data/311_City_Service_Requests_in_2015.geojson") %>%
st_transform('ESRI:102685') %>%
filter(SERVICECODEDESCRIPTION == "Alley Cleaning" | SERVICECODEDESCRIPTION == "Curb and Gutter Repair" | SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" | SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" | SERVICECODEDESCRIPTION == "Dead Animal Collection" | SERVICECODEDESCRIPTION == "Illegal Dumping" | SERVICECODEDESCRIPTION == "Pothole" | SERVICECODEDESCRIPTION == "Sanitation Enforcement" | SERVICECODEDESCRIPTION == "Street Cleaning" | SERVICECODEDESCRIPTION == "Trash Collection - Missed" | SERVICECODEDESCRIPTION == "Yard Waste - Missed") %>%
dplyr::select(SERVICECODEDESCRIPTION, SERVICEORDERDATE, INSPECTIONDATE, LATITUDE, LONGITUDE, WARD) %>%
mutate(TYPE = case_when(SERVICECODEDESCRIPTION == "Alley Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Dead Animal Collection" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Illegal Dumping" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Sanitation Enforcement" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Street Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Trash Collection - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Yard Waste - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Curb and Gutter Repair" ~ "Infrastructure_issues",
SERVICECODEDESCRIPTION == "Pothole" ~ "Infrastructure_issues",
),
month = month(ymd_hms(SERVICEORDERDATE)),
serviceday = ymd(substr(SERVICEORDERDATE,1,10))
) %>%
filter(month >= 8),
st_read("./data/311_City_Service_Requests_in_2016.geojson") %>%
st_transform('ESRI:102685') %>%
filter(SERVICECODEDESCRIPTION == "Alley Cleaning" | SERVICECODEDESCRIPTION == "Curb and Gutter Repair" | SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" | SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" | SERVICECODEDESCRIPTION == "Dead Animal Collection" | SERVICECODEDESCRIPTION == "Illegal Dumping" | SERVICECODEDESCRIPTION == "Pothole" | SERVICECODEDESCRIPTION == "Sanitation Enforcement" | SERVICECODEDESCRIPTION == "Street Cleaning" | SERVICECODEDESCRIPTION == "Trash Collection - Missed" | SERVICECODEDESCRIPTION == "Yard Waste - Missed") %>%
dplyr::select(SERVICECODEDESCRIPTION, SERVICEORDERDATE, INSPECTIONDATE, LATITUDE, LONGITUDE, WARD) %>%
mutate(TYPE = case_when(SERVICECODEDESCRIPTION == "Alley Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Dead Animal Collection" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Illegal Dumping" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Sanitation Enforcement" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Street Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Trash Collection - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Yard Waste - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Curb and Gutter Repair" ~ "Infrastructure_issues",
SERVICECODEDESCRIPTION == "Pothole" ~ "Infrastructure_issues",
),
month = month(ymd_hms(SERVICEORDERDATE)),
serviceday = ymd(substr(SERVICEORDERDATE,1,10))
),
st_read("./data/311_City_Service_Requests_in_2017.geojson") %>%
st_transform('ESRI:102685') %>%
filter(SERVICECODEDESCRIPTION == "Alley Cleaning" | SERVICECODEDESCRIPTION == "Curb and Gutter Repair" | SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" | SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" | SERVICECODEDESCRIPTION == "Dead Animal Collection" | SERVICECODEDESCRIPTION == "Illegal Dumping" | SERVICECODEDESCRIPTION == "Pothole" | SERVICECODEDESCRIPTION == "Sanitation Enforcement" | SERVICECODEDESCRIPTION == "Street Cleaning" | SERVICECODEDESCRIPTION == "Trash Collection - Missed" | SERVICECODEDESCRIPTION == "Yard Waste - Missed") %>%
dplyr::select(SERVICECODEDESCRIPTION, SERVICEORDERDATE, INSPECTIONDATE, LATITUDE, LONGITUDE, WARD) %>%
mutate(TYPE = case_when(SERVICECODEDESCRIPTION == "Alley Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Dead Animal Collection" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Illegal Dumping" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Sanitation Enforcement" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Street Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Trash Collection - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Yard Waste - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Curb and Gutter Repair" ~ "Infrastructure_issues",
SERVICECODEDESCRIPTION == "Pothole" ~ "Infrastructure_issues",
),
month = month(ymd_hms(SERVICEORDERDATE)),
serviceday = ymd(substr(SERVICEORDERDATE,1,10))
),
st_read("./data/311_City_Service_Requests_in_2018.geojson") %>%
st_transform('ESRI:102685') %>%
filter(SERVICECODEDESCRIPTION == "Alley Cleaning" | SERVICECODEDESCRIPTION == "Curb and Gutter Repair" | SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" | SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" | SERVICECODEDESCRIPTION == "Dead Animal Collection" | SERVICECODEDESCRIPTION == "Illegal Dumping" | SERVICECODEDESCRIPTION == "Pothole" | SERVICECODEDESCRIPTION == "Sanitation Enforcement" | SERVICECODEDESCRIPTION == "Street Cleaning" | SERVICECODEDESCRIPTION == "Trash Collection - Missed" | SERVICECODEDESCRIPTION == "Yard Waste - Missed") %>%
dplyr::select(SERVICECODEDESCRIPTION, SERVICEORDERDATE, INSPECTIONDATE, LATITUDE, LONGITUDE, WARD) %>%
mutate(TYPE = case_when(SERVICECODEDESCRIPTION == "Alley Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - Nuisance Odor Complaints" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "DOEE - General Environmental Concerns" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Dead Animal Collection" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Illegal Dumping" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Sanitation Enforcement" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Street Cleaning" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Trash Collection - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Yard Waste - Missed" ~ "Trash_issues",
SERVICECODEDESCRIPTION == "Curb and Gutter Repair" ~ "Infrastructure_issues",
SERVICECODEDESCRIPTION == "Pothole" ~ "Infrastructure_issues",
),
month = month(ymd_hms(SERVICEORDERDATE)),
serviceday = ymd(substr(SERVICEORDERDATE,1,10))
) %>%
filter(month < 8)
)
## Ward
# Ward <- st_read("./data/Wards.geojson") %>%
# st_transform('ESRI:102685') %>%
# dplyr::select(ward_name = NAME,
# ward_pop_15 = POP_2011_2015)
## Census blocks
# Census_blocks <- st_read("./data/Census_Blocks__2010.geojson") %>%
# st_transform('ESRI:102685')
# Address Points
addresses <- read.csv("./data/Address_Points.csv", header = TRUE) %>%
st_as_sf(., coords = c("X", "Y"), crs = 4326, agr = "constant") %>%
st_transform('ESRI:102685')
## Community Garden Polygons
comm_gardens <- st_read("./data/Community_Garden_Areas.geojson") %>%
st_transform('ESRI:102685')
## CAMA Commercial
cama_comm <- read.csv("./data/Computer_Assisted_Mass_Appraisal_-_Commercial.csv", header = TRUE)
## CAMA Condominium
cama_condo <- read.csv("./data/Computer_Assisted_Mass_Appraisal_-_Condominium.csv", header = TRUE)
## CAMA Residential
cama_res <- read.csv("./data/Computer_Assisted_Mass_Appraisal_-_Residential.csv", header = TRUE)
## Construction Permits 2015
const_permits15 <- read.csv("./data/Construction_Permits_in_2015.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant")
## Construction Permits 2016
const_permits16 <- read.csv("./data/Construction_Permits_in_2016.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant")
## Joining construction permits
const_permits_all <- rbind(read.csv("./data/Construction_Permits_in_2015.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant") %>%
mutate(month = month(APPLICATIONDATE)) %>%
filter(month >= 8) %>%
dplyr::select(-month),
read.csv("./data/Construction_Permits_in_2016.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant"),
read.csv("./data/Construction_Permits_in_2017.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant"),
read.csv("./data/Construction_Permits_in_2018.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant")%>%
mutate(month = month(APPLICATIONDATE)) %>%
filter(month < 8) %>%
dplyr::select(-month)) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant") %>%
st_transform('ESRI:102685')
## Public Trash Cans
trash_cans <- read.csv("./data/Litter_Cans.csv", header = TRUE) %>%
st_as_sf(., coords = c("X", "Y"), crs = 4326, agr = "constant") %>%
st_transform('ESRI:102685')
## National Parks
nat_parks <- st_read("./data/National_Parks.geojson") %>%
st_transform('ESRI:102685')
## Parks and Rec Parks
dc_parks <- st_read("./data/Parks_and_Recreation_Areas.geojson") %>%
st_transform('ESRI:102685')
## Sidewalk Grates (Sewer)
sewer_grates <- read.csv("./data/Sidewalk_Grates_2019.csv", header = TRUE) %>%
st_as_sf(., coords = c("X", "Y"), crs = 4326, agr = "constant") %>%
st_transform('ESRI:102685')
## Storm Drains (Markers)
storm_drains <- read.csv("./data/Storm_Drain_Marker_Installations.csv", header = TRUE) %>%
st_as_sf(., coords = c("LONGITUDE", "LATITUDE"), crs = 4326, agr = "constant") %>%
st_transform('ESRI:102685')
## Urban Ag Area
urban_ag <- st_read("./data/Urban_Agriculture_Areas.geojson") %>%
st_transform('ESRI:102685')
## Zoning Map
zoning <- st_read("./data/Zoning_Regulations_of_2016.geojson") %>%
st_transform('ESRI:102685')
## Mean temperature per day
weather.Panel <-
riem_measures(station = "DCA", date_start = "2015-08-01", date_end = "2018-07-31") %>%
dplyr::select(valid, tmpf, p01i, sknt)%>%
replace(is.na(.), 0) %>%
mutate(serviceday = ymd(substr(valid,1,10))) %>%
mutate(week = week(serviceday),
dotw = wday(serviceday, label=TRUE)) %>%
group_by(serviceday) %>%
summarize(Temperature = max(tmpf),
Wind_Speed = max(sknt)) %>%
mutate(Temperature = ifelse(Temperature == 0, 42, Temperature))
# Join 311 Data, count per day
Data311_perday <-
st_join(Data311, blocks) %>%
st_drop_geometry() %>%
group_by(serviceday, TYPE, block_id) %>%
summarize(count = n()) %>%
na.omit()
Data311_perday <- spread(Data311_perday, key = TYPE, value = count)
Data311_perday[is.na(Data311_perday)] <- 0
## Intersection of blocks and feature points
storm_drains$block_id <- st_intersects(storm_drains, block_dat)
sewer_grates$block_id <- st_intersects(sewer_grates, block_dat)
trash_cans$block_id <- st_intersects(trash_cans, block_dat)
const_permits_all$block_id <- st_intersects(const_permits_all, block_dat)
storm_block <-
storm_drains %>%
st_drop_geometry() %>%
group_by(block_id) %>%
summarize(count=n()) %>%
dplyr::filter(!grepl(':', block_id)) %>%
dplyr::filter(!grepl('integer', block_id)) %>%
na.omit()
block_dat$storm_drain <- storm_block$count[match(block_dat$block_id, storm_block$block_id)]
block_dat[is.na(block_dat[, "storm_drain"]), "storm_drain"] <- 0
sewer_block <-
sewer_grates %>%
st_drop_geometry() %>%
group_by(block_id) %>%
summarize(count=n()) %>%
dplyr::filter(!grepl(':', block_id)) %>%
dplyr::filter(!grepl('integer', block_id)) %>%
na.omit()
block_dat$sewer_grate <- sewer_block$count[match(block_dat$block_id, sewer_block$block_id)]
block_dat[is.na(block_dat[, "sewer_grate"]), "sewer_grate"] <- 0
trashcan_block <-
trash_cans %>%
st_drop_geometry() %>%
group_by(block_id) %>%
summarize(count=n()) %>%
dplyr::filter(!grepl(':', block_id)) %>%
dplyr::filter(!grepl('integer', block_id)) %>%
na.omit()
block_dat$trash_can <- trashcan_block$count[match(block_dat$block_id, trashcan_block$block_id)]
block_dat[is.na(block_dat[, "trash_can"]), "trash_can"] <- 0
const_block <-
const_permits_all %>%
st_drop_geometry() %>%
group_by(block_id) %>%
summarize(count=n()) %>%
dplyr::filter(!grepl(':', block_id)) %>%
dplyr::filter(!grepl('integer', block_id)) %>%
na.omit()
block_dat$const_permit <- const_block$count[match(block_dat$block_id, const_block$block_id)]
block_dat[is.na(block_dat[, "const_permit"]), "const_permit"] <- 0
#finding density (aka units) by block
addresses <- st_join(addresses, block_dat)
block_units <- addresses %>%
dplyr::select(geometry, ACTIVE_RES_UNIT_COUNT, block_id)
block_units <- block_units %>%
st_drop_geometry()%>%
group_by(block_id) %>%
summarize(unit_count = sum(ACTIVE_RES_UNIT_COUNT))
block_dat$res_unit_count <- block_units$unit_count[match(block_dat$block_id, block_units$block_id)]
block_dat[is.na(block_dat[, "res_unit_count"]), "res_unit_count"] <- 0
#finding zoning for each block
block_zone <- st_join(st_centroid(block_dat), zoning)
zoning_by_block <- block_zone %>%
st_drop_geometry() %>%
dplyr::select(block_id,ZONE_DISTRICT)
zoning_by_block$Residential_Zone <- ifelse(zoning_by_block$ZONE_DISTRICT == "Residential Zone", 1, 0)
zoning_by_block$Residential_Flat_Zone <- ifelse(zoning_by_block$ZONE_DISTRICT == "Residential Flat Zone", 1, 0)
zoning_by_block$Unzoned <- ifelse(zoning_by_block$ZONE_DISTRICT == "Unzoned", 1, 0)
zoning_by_block$Residential_Apt_Zone <- ifelse(zoning_by_block$ZONE_DISTRICT == "Residential Apartment Zone", 1, 0)
zoning_by_block$Mixed_Use <- ifelse(zoning_by_block$ZONE_DISTRICT== "Mixed-Use Zone", 1, 0)
zoning_by_block$Downtown_Zone <- ifelse(zoning_by_block$ZONE_DISTRICT== "Downtown Zone", 1, 0)
zoning_by_block$Prod_Dist_Repair <- ifelse(zoning_by_block$ZONE_DISTRICT== "Production, Distribution, and Repair Zone", 1, 0)
zoning_by_block$Special_Purpose <- ifelse(zoning_by_block$ZONE_DISTRICT== "Special Purpose Zone", 1, 0)
zoning_by_block$Neighborhood_Mixed_Use <- ifelse(zoning_by_block$ZONE_DISTRICT == "Neighborhood Mixed-Use Zone", 1, 0)
zoning_by_block <- zoning_by_block %>%
group_by(block_id) %>%
dplyr::select(-ZONE_DISTRICT)
zoning_by_block %>%
dplyr::select(-block_id) %>%
mutate(Zone= names(.)[which.max(c(Residential_Zone, Residential_Flat_Zone, Unzoned, Residential_Apt_Zone, Mixed_Use, Downtown_Zone, Prod_Dist_Repair, Special_Purpose, Neighborhood_Mixed_Use))])
zoning_by_block <- zoning_by_block %>%
group_by(block_id) %>%
rowwise() %>%
mutate(max = names(cur_data())[which.max(c_across(everything()))])
block_dat$zoning <- zoning_by_block$max[match(block_dat$block_id, zoning_by_block$block_id)]
# incorporating population density
pop_bg_17 <- get_acs(geography = "block group",
year = 2017,
state = "DC",
survey = "acs5",
variables = "B01001_001",
geometry = TRUE) %>%
st_transform("ESRI:102685") %>%
mutate(pop_dens = estimate / st_area(.))
# join to blocks by taking average pop density per block
block_bg_join <-
st_join(dplyr::select(blocks, block_id), dplyr::select(pop_bg_17, GEOID, pop_dens)) %>%
st_drop_geometry() %>%
group_by(block_id) %>%
summarize(pop_dens = mean(as.numeric(pop_dens)))
# join to block dataset
block_dat <- left_join(block_dat, block_bg_join)
```
Many different factors can contribute to the likelihood of a city block having a rat infestation. Most of these variables have to do with the nature of the built environment and settlement patterns that might encourage rat populations. Built environment variables we collected for initial testing included the locations of sewer grates and storm drains, active construction permits, trash cans, parks, and community gardens. Each of these physical factors presents an opportunity for a rat colony to burrow or navigate the urban environment.
On the settlement pattern side, we collected data on population density, zoning, and 311 complaints related to trash cleanup issues, illegal dumping, infrastructure repair, and other environmental concerns. Finally, we looked at weather and time-of-year variables to see if there was any relationship between the season and/or weather conditions when it comes to inspection requests.
Each of these variables was spatially aggregated into the city block dataset described above. The variables demonstrated a range of different relationships to the history of rat infestation identification in the primary dataset.
```{r , message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
block_dat_nogeom <- block_dat %>%
st_drop_geometry()
block_dat_nogeom$pop_density <- ifelse(block_dat$pop_dens >= 0.0005250146, 'Above Avg', 'Below Avg')
block_dat_nogeom$rats_yn <- ifelse(block_dat_nogeom$rats_found_yn == 1, 'yes','no')
block_dat_nogeom$rats_yn_req <- ifelse(block_dat_nogeom$rats_found_yn == 1, 'yes', ifelse(block_dat_nogeom$rats_found_yn == 0 & block_dat_nogeom$inspection_count == 0 , 'no requests', 'no'))
block_dat_nogeom$dens_rats <- ifelse(block_dat_nogeom$pop_density == 'Above Avg' & block_dat_nogeom$rats_yn_req == 'yes', 'high density with rats', ifelse(block_dat_nogeom$pop_density == 'Above Avg' & block_dat_nogeom$rats_yn_req == 'no', 'high density with no rats', 'na'))
block_dat_nogeom$storm_drain_cat <- ifelse(block_dat_nogeom$storm_drain >= 1, 'storm drains', 'no storm drains')
block_dat_nogeom$sewer_grate_cat <- ifelse(block_dat_nogeom$sewer_grate >= 1, 'sewer grates', 'no sewer grates')
block_dat_nogeom$trash_can_cat <- ifelse(block_dat_nogeom$trash_can >= 1, 'trash cans', 'no trash cans')
block_dat_nogeom$const_permit_cat <- ifelse(block_dat_nogeom$const_permit >= 1, 'const permits', 'no const permits')
pop_dens_bars <- block_dat_nogeom %>%
dplyr::select(rats_yn, pop_density) %>%
dplyr::filter(block_dat_nogeom$pop_density == 'Above Avg' | block_dat_nogeom$pop_density == 'Below Avg') %>%
gather(Variable, value, -rats_yn) %>%
count(Variable, value, rats_yn) %>%
ggplot(., aes(value, n, fill = rats_yn)) +
geom_bar(position = "dodge", stat="identity") +
facet_wrap(~Variable, scales="free") +
scale_fill_manual(values = c("#E99191", "#E91C1C")) +
labs(x="Blocks with Rats", y="Value",
title = "Blocks with Rat ID by Population Density") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
zoning_bars <- block_dat_nogeom %>%
dplyr::select(rats_yn_req, zoning) %>%
dplyr::filter(block_dat_nogeom$rats_yn_req == 'yes' | block_dat_nogeom$rats_yn_req == 'no') %>%
gather(Variable, value, -rats_yn_req) %>%
count(Variable, value, rats_yn_req) %>%
ggplot(., aes(value, n, fill = rats_yn_req)) +
geom_bar(position = "dodge", stat="identity") +
facet_wrap(~Variable, scales="free") +
scale_fill_manual(values = c("#E99191", "#E91C1C")) +
labs(x="Blocks with Rats", y="Value",
title = "Blocks with Rat ID by Zoning") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
grid.arrange(pop_dens_bars, zoning_bars, ncol = 2)
```
Population density and zoning were two variables that stuck out as having particularly notable distributions related to the presence of rat infestation evidence. It is clear from the graph on the left that areas with an above-average population density, for instance, have a much higher rate of inspections leading to the treatment of rat infestation. The same is true for zoning, especially when blocks that recieved no requests at all were removed: the graph on the right shows this and demonstrates that certain zones such as Residential Apt. Zone, Residential Flat Zone, and Mixed Use are much more likely to yield evidence of rats upon an inspection.
```{r}
block_dat_nogeom %>%
dplyr::select(rats_yn_req, storm_drain_cat, sewer_grate_cat, trash_can_cat, const_permit_cat) %>%
dplyr::filter(block_dat_nogeom$rats_yn_req == 'yes' | block_dat_nogeom$rats_yn_req == 'no') %>%
gather(Variable, value, -rats_yn_req) %>%
count(Variable, value, rats_yn_req) %>%
ggplot(., aes(value, n, fill = rats_yn_req)) +
geom_bar(position = "dodge", stat="identity") +
facet_wrap(~Variable,ncol = 2, scales="free") +
scale_fill_manual(values = c("#E99191", "#E91C1C")) +
labs(x="Blocks with Rats", y="Value",
title = "Built Environment Variables, Removing Blocks Without Inspection Requests") +
theme(axis.text.x = element_text(angle = 0))
```
Variables related to the built environment also have an interesting relationship to the presence of rats. The four charts above show that, for blocks that have received at least one inspection request, the presence of factors such as active construction permits, sewer grates, and trash cans all contribute to a greater chance of finding evidence of rats.
### 2.4: Feature Engineering
Oftentimes, the pure presence-absence of a given independent variable in an area does not speak to the true relationship between it and the dependent variable. Feature engineering is a crucial and necessary step in the process of building machine learning models. It involves selecting and transforming relevant features from raw data to improve the performance and accuracy of the model. Without proper feature engineering, even the most sophisticated algorithms may fail to produce meaningful results. The quality and relevance of the features used directly impact the model’s ability to learn and make accurate predictions. Therefore, investing time and effort in feature engineering is essential for producing reliable and effective machine learning models.
#### 2.4.1: Calculating Rat Infestation Hotspots
In this project, much of the feature engineering revolved around creating new variables which speak to the spatial distribution of rat infestations in the past, as well as the relationship between other independent variables and rat infestations. One of the methods used to achieve this was to run a local Moran’s I hotspot analysis on rat infestation observations to identify the statistically-significant rat hotspots across the city based on the 311 data available to us.
```{r create fishnet and morans i, message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
# create fishnet
fishnet <-
st_make_grid(boundary,
cellsize = 500,
square = TRUE) %>%
.[boundary] %>%
st_sf() %>%
mutate(uniqueID = 1:n())
# assign each inspection a value of 1 and aggregate
inspection_net <-
dplyr::select(Rats) %>%
mutate(count_inspection = 1) %>%
aggregate(., fishnet, sum) %>%
mutate(count_inspection = replace_na(count_inspection, 0),
uniqueID = 1:n(),
cvID = sample(round(nrow(fishnet) / 24),
size=nrow(fishnet), replace = TRUE))
# join in rat observed variable
rat_net <-
Rats %>%
filter(activity == 1) %>%
st_join(fishnet, join=st_within) %>%
st_drop_geometry() %>%
group_by(uniqueID) %>%
summarize(rat_obs_count = n()) %>%
left_join(inspection_net, ., by = "uniqueID") %>%
ungroup() %>%
mutate(rat_obs_count = replace_na(rat_obs_count, 0))
## make polygon to neighborhoods...
rat_net.nb <- poly2nb(as_Spatial(rat_net), queen=TRUE)
## ... and neighborhoods to list of weights
rat_net.weights <- nb2listw(rat_net.nb, style="W", zero.policy=TRUE)
local_morans <- localmoran(rat_net$rat_obs_count, rat_net.weights, zero.policy=TRUE) %>%
as.data.frame()
# join local Moran's I results to fishnet
rat_net.localMorans <-
cbind(local_morans, as.data.frame(rat_net)) %>%
st_sf() %>%
dplyr::select(Rat_Observation_Count = rat_obs_count,
Local_Morans_I = Ii,
P_Value = `Pr(z != E(Ii))`) %>%
mutate(Significant_Hotspots = ifelse(P_Value <= 0.001, 1, 0)) %>%
gather(Variable, Value, -geometry)
vars <- unique(rat_net.localMorans$Variable)
varList <- list()
for(i in vars){
varList[[i]] <-
ggplot() +
geom_sf(data = filter(rat_net.localMorans, Variable == i),
aes(fill = Value), colour=NA) +
scale_fill_gradient(low = "#e3b1b1", high = "#E91C1C") +
labs(title=i) +
mapThememin() + theme(legend.position="bottom")}
do.call(grid.arrange,c(varList, ncol = 4, top = "Local Morans I Statistics for Rat Infestation Hotspot Identification"))
```
The hotspots identified by the Moran’s I process can be seen on the right-most map here. Unsurprisingly, the primary hotspots are in the center of the city where the highest inspection and rat evidence identification clusters are found, as well as the highest population density. In order to make this data as useful as possible to the model, another engineered variable was calculated which assigned each block the distance to the nearest hotspot. This provides a sense of each block’s spatial relationship to most substantial rat populations:
```{r message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
# add distance to hot spot var to final fishnet
rat_net <- rat_net %>%
mutate(rat_obs.isSig =
ifelse(local_morans[,5] <= 0.001, 1, 0)) %>%
mutate(rat_obs.isSig.dist =
nn_function(st_coordinates(st_centroid(rat_net)),
st_coordinates(st_centroid(filter(rat_net,
rat_obs.isSig == 1))),
k = 1))
# add distance to hot spot var to block dataset
block_dat <-
block_dat %>%
mutate(hotspot_dist =
nn_function(st_coordinates(st_centroid(block_dat)),
st_coordinates(st_centroid(filter(rat_net,
rat_obs.isSig == 1))),
k = 1),
hotspot_dist_log = log(hotspot_dist))
block_dat <-
block_dat %>%
mutate(hotspot_dist_pop_dens = hotspot_dist / pop_dens,
hotspot_dist_log_pop_dens = hotspot_dist_log / pop_dens)
ggplot() +
geom_sf(data = block_dat, aes(fill=hotspot_dist), color = "transparent") +
scale_fill_gradient(low = "lightgray", high = "#E91C1C", name = "Distance (Feet)") +
labs(title = "Distance from Rat Infestation Hotspot by Block",
subtitle = "Hotspot : p-value ≤ 0.001",
caption = "") +
mapThememin()
```
#### 2.4.2: Nearest-Neighbor Calculations
```{r message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
# generating knn features at block level for nearest rat observations
block_dat <-
block_dat %>%
mutate(Transh_cans_nn3 = round(nn_function(st_c(st_coid(block_dat)), st_c(trash_cans), k = 3)),
Storm_drains_nn3 = round(nn_function(st_c(st_coid(block_dat)), st_c(storm_drains), k = 3)),
Sewer_grates_nn3 = round(nn_function(st_c(st_coid(block_dat)), st_c(sewer_grates), k = 3)),
area_acres_log = log(area_acres),
rats_nn3 = nn_function(st_coordinates(st_centroid(block_dat)), st_coordinates(filter(Rats, activity == 1)), k = 3),
rat_nn4 = nn_function(st_coordinates(st_centroid(block_dat)), st_coordinates(filter(Rats, activity == 1)), k = 4),
rat_nn5 = nn_function(st_coordinates(st_centroid(block_dat)), st_coordinates(filter(Rats, activity == 1)), k = 5),
rat_nn3_log = log(nn_function(st_coordinates(st_centroid(block_dat)), st_coordinates(filter(Rats, activity == 1)), k = 3)),
rat_nn4_log = log(nn_function(st_coordinates(st_centroid(block_dat)), st_coordinates(filter(Rats, activity == 1)), k = 4)),
rat_nn5_log = log(nn_function(st_coordinates(st_centroid(block_dat)), st_coordinates(filter(Rats, activity == 1)), k = 5)))
# create some pop density-sensitive variables
block_dat <-
block_dat %>%
mutate(rat_nn5_pop_dens = rat_nn5 / pop_dens)
block_dat.nn <-
dplyr::select(block_dat, ends_with("nn3")) %>%
gather(Variable, value, -geometry)
block_dat.nns <- unique(block_dat.nn$Variable)
mapList <- list()
for(i in block_dat.nns){
mapList[[i]] <-
ggplot() +
geom_sf(data = filter(block_dat.nn, Variable == i), aes(fill=value), color = "transparent") +
scale_fill_gradient(low = "lightgray", high = "#E91C1C") +
labs(title = i) +
mapThememin()
}
do.call(grid.arrange,c(mapList, ncol=2, top="Nearest Neighbor Potential Factors by Block"))
```
Our second feature engineering approach was to calculate the average nearest neighbor distance of rat observations to each block as a proxy for a smoother exposure relationship across space. To create average nearest neighbor features, the city blocks were first converted into centroid points. Then, the distance between each centroid point and the k-nearest risk factor points (in this case, observed evidence of rat infestation) is measured. We tried several different options for k and settled on k = 3 as the most effective representation of this data. The maps above show the spatial distribution of the k = 3 nearest neighbor variables calculated during this stage.
### 2.5: Correlation Analysis
```{r message=FALSE, warning=FALSE, out.width = '100%', results='hide', fig.keep='all'}
#correlation matrix
newVars <-
select_if(st_drop_geometry(block_dat), is.numeric) %>%
dplyr::select(-block_id, -rats_found_yn) %>%
na.omit()
ggcorrplot(
round(cor(newVars), 1),
p.mat = cor_pmat(newVars),
colors = c("#e3b1b1", "white", "#E91C1C"),
type="lower",
insig = "blank") +
labs(title = "Correlation across numeric variables") +
theme(axis.text.x=element_text(size=rel(0.75), angle=45)) +
theme(axis.text.y=element_text(size=rel(0.75)))
```
Before reaching the modeling stage, it is important to understand the relationship between independent variables in addition to the relationship between those variables and the dependent variable. The correlation plot above provides insight into how some of the explanatory variables collected in this portion of the process relate to one another. Unsurprisingly, the variables with the highest correlation are those which are measuring closely-related things, such as the k = 3 and k = 4 nearest neighbor variables. This chart was used to narrow down the variables included in the modeling process in an effort to eliminate redundancy.