/
crime_weather_covid_TimeSeriesFoundations.Rmd
213 lines (171 loc) · 7.69 KB
/
crime_weather_covid_TimeSeriesFoundations.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
---
title: "The influence of weather and a pandemic on crime"
output:
html_document:
df_print: paged
---
```{r Markdown cheatsheet, echo=FALSE}
# echo=FALSE prevents code, but not the results from appearing in the rendered file
# eval=TRUE evaluates the code and includes the results
# results='hide' hides the results but displays the code
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
### Install packages (if required)
```{r install packages, eval=FALSE, message=FALSE, warning=FALSE}
# set eval=TRUE if running script for the first time
if(!require("ggseas")) install.packages("ggseas")
if(!require("forecast")) install.packages("forecast")
if(!require("data.table")) install.packages("data.table")
if(!require("knitr")) install.packages("knitr")
if(!require("bigrquery")) install.packages("bigrquery")
if(!require("devtools")) install.packages("devtools")
if(!require("tsibble")) install.packages("tsibble")
if(!require("fable")) install.packages("fable") # forecasting package of the tidyverse family
# devtools::install_github("rstats-db/bigrquery", force = TRUE)
```
### Load packages
```{r eval=TRUE, message=FALSE, warning=FALSE}
library(bigrquery)
library(ggplot2)
library(tidyr)
library(dplyr)
library(lubridate) # handle date information
library(readr) # read txt file with credentials
library(fable)
library(tsibble)
library(feasts)
library(ggpmisc) # plot R^2 in scatter plot
```
## TODO
# source readData or read from csv below
```{r read in data from csv}
counts_day <- read.csv("counts_day.csv")
head(counts_day)
# format as date
counts_day$date <- as.Date(ymd_hms(counts_day$date))
head(counts_day)
```
## Time series analysis
Theory:
Forecasting: Principles and Practice
Rob J Hyndman and George Athanasopoulos
Monash University, Australia
Available at https://otexts.com/fpp3/
"a key step is knowing when something can be forecast accurately, and when forecasts will be no better than tossing a coin. Good forecasts capture the genuine patterns and relationships which exist in the historical data, but do not replicate past events that will not occur again. In this book, we will learn how to tell the difference between a random fluctuation in the past data that should be ignored, and a genuine pattern that should be modelled and extrapolated."
Each time series has three components:
1) trend
2) seasonality
3) error
```{r simple ts plot}
# simple plot using the feasts package
daily_counts %>% autoplot(counts)
```
The autoplot shows a consistent negative trend and strong seasonality
Is this a multiplicative or additive time series?
- interaction between general seasonality and the underlying trend
- multiplicative time series: the components multiply; with de- or increasing trend, the amplitude of seasonal activity increases
- additive time series: components additive to make up time series; with increasing trend, you still see roughly the same size peaks and troughs throughout the time series; often indexed time series where the absolute value is growing but changes stay relative
```{r}
daily_counts %>%
index_by(year_month = ~ yearmonth(.)) %>% # monthly aggregates
summarise(ttl_count = sum(counts, na.rm = TRUE)) %>%
gg_subseries(ttl_count) +
ylab("Offense counts") +
xlab("Year") +
ggtitle("Seasonal subseries plot: # of offenses")
```
Above, we are using the total of counts to aggregate the months. That, however, is not optimal. There is a variable number of days per months. Let's account for that. Moving forward, we use the average daily number of offenses per month.
```{r scatter plot of crime by precipitation}
year = 2019
daily_crime %>%
filter(year(date) == year) %>%
ggplot(aes(x = temperature, y = counts)) +
ylab("Offence counts") + xlab("Temperature (F)") +
ggtitle(paste("Correlation of temperature and offense counts in", year, sep=" ")) +
geom_smooth(method = "lm") +
stat_poly_eq(formula = y ~ x,
eq.with.lhs = "italic(hat(y))~`=`~",
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse = TRUE) +
geom_point()
```
In 'normal' years, the number of offenses and temperature are correlated. Temperature explains more than half of the variation in offense counts (i.e., R^2 above 0.5).
```{r plot correlation matrix, message=FALSE, warning=FALSE}
year = 2019
daily_crime %>%
filter(year(date) == year) %>%
GGally::ggpairs(columns = 2:8)
# ggsave("counts_by_weather_correlation_matrix.png")
```
```{r retrieve correlation coefficients}
counts2019 <- daily_crime %>%
filter(year(date) == 2019)
cor(counts2019[2:8], use = "pairwise.complete.obs", method = "pearson")
```
### Exploring lag in data
Each graph shows y<sub>t</sub> plotted against y<sub>t−k</sub> for different values of k (here, months).
```{r}
daily_crime %>%
filter(between(year(date), 2017, 2019)) %>%
index_by(year_month = ~ yearmonth(.)) %>% # monthly aggregates
summarise(
avg_counts = mean(counts, na.rm = TRUE)
) %>%
gg_lag(avg_counts, geom="point") +
ggtitle("Lag plot: Avg daily counts per month versus counts + lag")
```
## Autocorrelation
Correlation measures the extent of a linear relationship between two variables. Autocorrelation measures the linear relationship between lagged values of a time series. The autocorrelation coefficients make up the autocorrelation function or ACF.
In simple words: how do counts between months correlate?
```{r autocorrelation}
daily_crime %>%
index_by(year_month = ~ yearmonth(.)) %>% # monthly aggregates
summarise(
avg_counts = mean(counts, na.rm = TRUE)
) %>%
ACF(avg_counts, lag_max = 48) %>% autoplot() +
ggtitle("Correlogram: Correlation of avg daily counts per month and monthly counts lag-times later")
```
The monthly offense counts are strongly autocorrelated. We notice both the seasonal trend and negative trend. Neighboring monthly counts are stronger correlated than those shifted by 6-month. The larger the lag, the weaker the correlation.
### Time Series Decomposition
```{r STL decomposition}
dcmp <- daily_crime %>%
index_by(year_month = ~ yearmonth(.)) %>% # monthly aggregates
summarise(
avg_counts = mean(counts, na.rm = TRUE)
) %>%
model(STL(avg_counts))
components(dcmp)
```
```{r autoplot including trend line}
daily_counts %>%
index_by(year_month = ~ yearmonth(.)) %>% # monthly aggregates
summarise(
avg_counts = mean(counts, na.rm = TRUE)
) %>%
autoplot(avg_counts, color='gray') +
autolayer(components(dcmp), trend, color='red') +
xlab("Year") + ylab("Avg. daily offense counts") +
ggtitle("Daily avg offense counts per month and overall trend.")
```
The trend-cycle component (red) and the raw data (grey).
We can plot all of the components in a single figure using autoplot():
```{r visually parse out components}
components(dcmp) %>% autoplot() + xlab("Year")
```
The grey bars to the left of each panel show the relative scales of the components. Each grey bar represents the same length but because the plots are on different scales, the bars vary in size.
We are not interested to understand seasonal changes in offense counts, so let's plot the trend again, but adjust for seasonal effects (i.e., remove seasonal effects). In other words, seasonally adjusted time series contain the remainder component as well as the trend-cycle (but not the seasonal compotent).
## Seasonal adjustment of offense counts
```{r seasonal adjustment}
daily_counts %>%
index_by(year_month = ~ yearmonth(.)) %>% # monthly aggregates
summarise(
avg_counts = mean(counts, na.rm = TRUE)
) %>%
autoplot(avg_counts, color='gray') +
autolayer(components(dcmp), season_adjust, color='blue') +
xlab("Year") + ylab("Avg. daily offense counts") +
ggtitle("Seasonally adjusted offense counts")
```