Skip to content

Instantly share code, notes, and snippets.

@ctufts
Last active November 7, 2015 22:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctufts/c30dc068bdcace6021a2 to your computer and use it in GitHub Desktop.
Save ctufts/c30dc068bdcace6021a2 to your computer and use it in GitHub Desktop.
The script imports Philadelphia Crime Data Parts I and II (https://www.opendataphilly.org/dataset/crime-incidents), creates a summary based on year, month, and crime type and creates a basic map in leaflet using the first 1000 incidents
# the following script will import Philadelphia Crime Data
# Parts I and II, create a summary based on year, month, and crime type
# and will create a basic map in leaflet using the first 1000 incidents
# you will need to install dplyr, leaflet, readr, lubridate, and stringr
# packages ( install.packages('package name') )
rm(list = ls())
library(dplyr)
library(leaflet)
library(readr)
library(lubridate)
library(stringr)
# import data ####
ds <- read_csv('https://data.phila.gov/api/views/7ret-xhtc/rows.csv?accessType=DOWNLOAD')
# rename columns
names(ds)[c(3,6,7)] <- c('Dispatch.Date.Time', 'UCR.Code', 'General.Crime.Category')
# convert date objects
ds$Dispatch.Date.Time <- mdy_hms(ds$Dispatch.Date.Time)
# identify month and year of occurence
ds$month <- month(ds$Dispatch.Date.Time)
ds$year <- year(ds$Dispatch.Date.Time)
# incident counts by type, month, and year ####
crime.summary <- ds %>% group_by(General.Crime.Category,
month, year) %>%
summarise(
events = n()
)
# MAP ####
# create a data frame of the coordinates
ds$Coordinates<- gsub(")", "", ds$Coordinates)
ds$Coordinates<- gsub("\\(", "", ds$Coordinates)
coord.list <- (str_split(ds$Coordinates, ","))
ds$lat <- as.numeric(unlist(lapply(coord.list, function(x)x[1])))
ds$lon <- as.numeric(unlist(lapply(coord.list, function(x)x[2])))
# map the first 1000 incidents in the data set
# remove any missing coordinates
n <- 1000
coordinates <- na.omit(ds[1:n, ])
leaflet() %>%
addProviderTiles('CartoDB.Positron') %>%
setView(lng=-75.16048, lat=39.99000, zoom =11) %>%
addCircles(lat = coordinates$lat, lng = coordinates$lon,
fillOpacity = 0.8 , opacity = 0.8, radius = 8, weight = 1,
popup = paste("Crime Category:",coordinates$General.Crime.Category, "<br/> Time:", coordinates$Dispatch.Date))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment