#libraries
library(data.table)
library(sp)
library(rgdal)
library(dplyr)
library(ggpubr)
library(grid)
library(leaflet)
#read in data table
chi_dat = fread("chicago_6mos_google_communities.csv")
#convert to data table
chi_dat = as.data.table(chi_dat)
#table of total incidents by community
#filter places outside of chicago communities
#final number of observations = 1021
chi_tab = chi_dat[community!=""]
#make data spatial
coordinates(chi_tab) = c("google_longitude","google_latitude")
crs.geo1 = CRS("+proj=longlat")
proj4string(chi_tab) = crs.geo1
plot(chi_tab, pch = 20, col = "steelblue")

#read in shapefile of chicago
chicago = readOGR(dsn = "./communities", layer = "geo_export_84596be1-10fc-47e4-a7d0-36d6c9a9e0a3")
## OGR data source with driver: ESRI Shapefile
## Source: "/Users/Daniela/Desktop/Classes/Programming Methods/chicago/communities", layer: "geo_export_84596be1-10fc-47e4-a7d0-36d6c9a9e0a3"
## with 77 features
## It has 9 fields
#leaflet map -- # of incidents
#reproject coordinates
proj4string(chicago) = crs.geo1
## Warning in `proj4string<-`(`*tmp*`, value = new("CRS", projargs = "+proj=longlat +ellps=WGS84")): A new CRS was assigned to an object with an existing CRS:
## +proj=longlat +ellps=WGS84 +no_defs
## without reprojecting.
## For reprojection, use function spTransform
chi_agg = aggregate(x=chi_tab["incidents_people"],by=chicago,FUN=length)
qpal = colorBin("Reds", chi_agg$incidents_people, bins=4)
leaflet(chi_agg) %>%
addPolygons(stroke = TRUE,opacity = 1,fillOpacity = 0.5, smoothFactor = 0.5,
color="black",fillColor = ~qpal(incidents_people),weight = 1) %>%
addLegend(values=~incidents_people,pal=qpal,title="Incidents")
#table missing 7 communities (all with zero incidents)
#seven NAs: OHARE (75) = 0
chi_agg@data$incidents_people[75] = as.integer(0)
chi_agg@data$incidents_people[77] = as.integer(0)
chi_agg@data$incidents_people[73] = as.integer(0)
chi_agg@data$incidents_people[36] = as.integer(0)
chi_agg@data$incidents_people[12] = as.integer(0)
chi_agg@data$incidents_people[71] = as.integer(0)
chi_agg@data$incidents_people[13] = as.integer(0)
bins <- c(0, 10, 20, 30, 40, 50, 60, 70, 80)
qpal = colorBin("Reds", chi_agg$incidents_people, bins=bins)
labels <- sprintf(
"<strong>%s</strong>",
chi_agg$incidents_people
) %>% lapply(htmltools::HTML)
leaflet(chi_agg) %>%
addPolygons(stroke = TRUE,opacity = 1,fillOpacity = 0.5, smoothFactor = 0.5,
color="black",fillColor = ~qpal(incidents_people),weight = 1, label = labels,
labelOptions = labelOptions(
style = list("font-weight" = "normal", padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(values=~incidents_people,pal=qpal,title="Incidents")