/
weekly_EDA.Rmd
272 lines (204 loc) · 9.11 KB
/
weekly_EDA.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
---
title: "Weather and Shootings in Baltimore"
author: "Justin Elszasz"
date: "April 25, 2018"
output:
html_notebook:
toc: yes
toc_float: yes
---
```{r}
library(tidyverse)
library(readxl)
library(RSocrata)
library(lubridate)
library(RcppRoll)
```
I grabbed [daily weather data from NOAA](https://www.ncdc.noaa.gov/cdo-web/datasets) back to 2012 since that's what we have part 1 crime data on [Open Baltimore](https://data.baltimorecity.gov/Public-Safety/BPD-Part-1-Victim-Based-Crime-Data/wsfq-mvij) for. Had to grab it in two csv's. Somewhere I have a Python script for getting weather data from Weather Underground's API. I downloaded it for all weather stations in Baltimore City area but I'll just filter it for the Maryland Science Center weather station.
```{r}
weather <- read.csv("1325092.csv") %>%
bind_rows(read.csv("1325101.csv")) %>%
filter(NAME == "MARYLAND SCIENCE CENTER, MD US") %>%
mutate_at("DATE", as.Date)
```
And through the RSocrata package, it's super easy to connect to an open dataset in R.
```{r}
endpoint <- "https://data.baltimorecity.gov/resource/4ih5-d5d5.json"
crime <- read.socrata(endpoint)
```
Next I'll take that crime data (where each row is an incident) and do daily counts for the number of homicides, number of non-fatal shootings, and the sum of those two counts.
```{r}
weekly.shooting <- crime %>%
mutate_at("crimedate", as.Date) %>%
mutate(week.start = floor_date(crimedate, "week")) %>%
group_by(week.start) %>%
summarise(nfs = sum(description == "SHOOTING"),
hom = sum(description == "HOMICIDE"),
all.shootings = nfs + hom) %>%
mutate(uprising = ifelse(week.start <= "2015-05-01", "Before May 2015", "May 2015 +"))
head(weekly.shooting, 25)
```
The total daily shootings + homicides are counts so we expect a Poisson distribution.
```{r}
weekly.shooting %>%
ggplot(aes(all.shootings)) +
geom_histogram(bins = 40) +
theme_minimal()
```
Can also look at this frequency distribution with a split for pre and post 2015. As we expect, the 2015+ period is shifted to the right (more total shootings).
```{r}
weekly.shooting %>%
ggplot(aes(all.shootings, color = uprising)) +
geom_freqpoly(bins = 12) +
theme_minimal() +
theme(legend.title = element_blank()) +
ylab("Count") +
xlab("Weekly Shootings") +
ggtitle("Weekly Shooting Distribution for Baltimore") +
ggsave(filename = "img/poisson_weekly.png", width = 6, height = 4)
```
Joining the shooting counts to the weather data. For whatever reason, the Maryland Science Center data doesn't include an average daily temp, just the max and min, so we'll calculate a median off of that range and use that for the model.
```{r}
# prepare weather data
weekly.weather <- weather %>%
mutate(week.start = floor_date(DATE, "week")) %>%
group_by(week.start) %>%
summarise(mean.max.temp = mean(TMAX, na.rm = T),
mean.min.temp = mean(TMIN, na.rm = T),
days.precip = sum(PRCP > 0.05), # precip threshold decent?
total.precip = sum(PRCP))
```
```{r}
# join and prepare weekly shootings and weather
weekly.data <- weekly.shooting %>%
left_join(weekly.weather, by = c("week.start"))
```
Let's take a quick look at the correlation between temperature and total shootings. Also interested in pre-2015 and 2015+ split.
```{r}
weekly.data %>%
ggplot(aes(mean.max.temp, all.shootings,
color = uprising)) +
geom_jitter(size = 2, alpha = 0.4) +
geom_smooth(method='lm', formula = y ~ x, fill = NA) +
theme_minimal() +
xlab("Average Daily Maximum Temp (deg F)") +
ylab("Weekly Total Shootings (Non-Fatal + Hom.)") +
ggtitle("Effect of Outdoor Temperature on Weekly Shootings in Baltimore") +
theme(legend.title = element_blank()) +
ggsave(filename = "img/trends_weekly.png", width = 6, height = 4)
```
If you look at the scatter plot (with jitter added so there aren't points right on top of each other) you can see more blue (2015 and after) weeks towards the top of the plot because we've seen more shootings these past few years.
Another way to visualize it might be a boxplot, where along the x-axis we use the total number of shootings and use the y-axis for the temperature. Again we see the increase in temperature with increase in shootings.
```{r}
weekly.data %>%
ggplot(aes(as.factor(all.shootings), mean.max.temp)) +
geom_boxplot() +
#facet_wrap(~ (year(crimedate) >= 2015)) +
theme_minimal()
```
```{r}
weekly.data %>%
ggplot(aes(log(total.precip), all.shootings,
color = uprising)) +
geom_jitter(size = 2, alpha = 0.4) +
geom_smooth(method='lm', formula = y ~ x, fill = NA) +
theme_minimal() +
#xlab("Average Daily Maximum Temp (deg F)") +
#ylab("Weekly Total Shootings (Non-Fatal + Hom.)") +
#ggtitle("Effect of Outdoor Temperature on Weekly Shootings in Baltimore") +
theme(legend.title = element_blank())
#ggsave(filename = "img/trends_weekly.png", width = 6, height = 4)
```
```{r}
weekly.data %>%
ggplot(aes(days.precip, all.shootings,
color = uprising)) +
geom_jitter(size = 2, alpha = 0.4) +
geom_smooth(method='lm', formula = y ~ x, fill = NA) +
theme_minimal() +
#xlab("Average Daily Maximum Temp (deg F)") +
#ylab("Weekly Total Shootings (Non-Fatal + Hom.)") +
#ggtitle("Effect of Outdoor Temperature on Weekly Shootings in Baltimore") +
theme(legend.title = element_blank())
#ggsave(filename = "img/trends_weekly.png", width = 6, height = 4)
```
```{r}
weekly.data %>%
ggplot(aes(factor(days.precip > 0), all.shootings)) +
geom_boxplot() +
#facet_wrap(~ (year(crimedate) >= 2015)) +
theme_minimal()
```
```{r}
weekly.data %>%
ggplot(aes(factor(total.precip > 0), all.shootings)) +
geom_boxplot() +
#facet_wrap(~ (year(crimedate) >= 2015)) +
theme_minimal()
```
```{r}
weekly.data %>%
ggplot(aes(all.shootings, ..density.., color = factor(total.precip > 0.00))) +
geom_freqpoly() +
#facet_wrap(~ (year(crimedate) >= 2015)) +
theme_minimal()
```
## Autocorrelation/Lags
```{r}
acf(weekly.data$all.shootings)
```
About 15 lags (previous 15 previous weeks) are relevant.
```{r}
lags <- seq(15)
lag_names <- paste("lag", formatC(lags, width = nchar(max(lags)), flag = "0"),
sep = "_")
lag_functions <- setNames(paste("dplyr::lag(., ", lags, ")"), lag_names)
weekly.data <- weekly.data %>%
mutate_at(vars(all.shootings), funs_(lag_functions))
```
```{r}
```
# Modeling
Since shootings are weekly counts we expect this to follow a Poisson distribution. So, we'll use a generalized linear model with a log-link. Let's make a model for before 2015 and 2015 and after so we can compare.
```{r}
model.pre2015 <- glm(all.shootings ~ mean.max.temp,
data = weekly.data %>%
filter(week.start <= "2015-05-01"),
family = "poisson")
summary(model.pre2015)
```
```{r}
model.post2015 <- glm(all.shootings ~ mean.max.temp,
data = weekly.data %>%
filter(week.start > "2015-05-01"),
family = "poisson")
summary(model.post2015)
```
# EDIT -------------
For the pre-2015 model, we've got an intercept of -.21. Since this is a logistic-link, the intercept for number of shootings is exp(-0.21) = 0.81. In other words, at 0 degrees Fahrenheit for the median outdoor temperature, we'd expect 0.8 total shootings for the day.
The coefficient for the daily median temperature is 0.011. We'll multiply this by 10 so we can understand the effect in terms of 10 degree F increments: exp(10 * 0.011) = 1.12. __This means that for every 10 degree F increase in outdoor median temperature, we expect a 12% increase in the total number of shootings__ (again, homicides plus non-fatal shootings).
For the 2015 and after model, we've got an intercept of .21. At 0 degrees Fahrenheit for the median outdoor temperature during and after 2015, we'd expect 1.2 total shootings for the day - a noticeable increase over the baseline intercept for pre-2015.
In this model, the coefficient for the daily median temperature is 0.013, resulting in a expected increase factor of 1.14: __for every 10 degrees F increase in outdoor median temperature in 2015 and thereafter, we expect a 14% increase in the total number of shootings__, which is not all that different of an effect from pre-2015.
It's sensible that the effect of weather on total shootings hasn't itself dramatically changed. A model for all years (without considering this 2015 split) gives __an effect of about 12% increase in shootings with every 10 degree F increase in daily median temperature.__
# ---------------------
```{r}
View(weekly.data)
training.data <- weekly.data %>%
select(-nfs, -hom, -total.precip, -uprising, -mean.min.temp)
model.all <- glm(all.shootings ~ .,
data = training.data,
family = "poisson")
summary(model.all)
```
```{r}
weekly.data.pred <- weekly.data %>%
mutate(pred = predict.glm(model.all, weekly.data %>% select(-nfs, -hom, -all.shootings),
type = "response"))
```
```{r}
weekly.data.pred %>%
#filter(week.start >= "2017-01-01") %>%
ggplot(aes(week.start)) +
geom_line(aes(y = all.shootings)) +
geom_line(aes(y = pred), color = "red")
```