The goal of this project is to create a map of violent crime in manhattan. When zoomed in, the map displays the location of the crime and clicking on a the marker will display the specific crime that occurred. Zooming out will group the crimes into a heat map type marker based on the number of crimes that have occurred in that area.
We need the following packages: Leaflet is required to create the map jsonlite lets us read the JSON file that we’ll get the data from *curl is required by jsonlite’s fromJSON function
library(leaflet)
library(curl)
library(jsonlite)
The data we need is publicly available from the City of New York here. The website provides an API endpoint in JSON format.
my_data<-fromJSON("https://data.cityofnewyork.us/resource/5jvd-shfj.json",flatten=TRUE)
We need to make the following changes to the data: We only want Manhattan, so filter out non-Manhattan columns using the boro_nm field We want the most violent crimes, so we’ll select felonies only using the law_cat_cd field *Eight data points are missing latitude/longitude data, so we’ll remove these
my_cleansed_data<-my_data[which(!is.na(my_data$lat_lon.longitude)),]
my_cleansed_data<-my_cleansed_data[which(my_cleansed_data$law_cat_cd=="FELONY"),]
my_cleansed_data<-my_cleansed_data[which(my_cleansed_data$boro_nm=="MANHATTAN"),]
my_cleansed_data$lat_lon.latitude<-as.numeric(my_cleansed_data$lat_lon.latitude)
my_cleansed_data$lat_lon.longitude<-as.numeric(my_cleansed_data$lat_lon.longitude)
In setting up the leaflet, we want the following: Markers appear at the listed latitude and longitude Markers will be clustered together in heat marker format when zoomed out *When an individual marker is clicked upon, it shows the description
my_latlng<-data.frame(lat=my_cleansed_data$lat_lon.latitude,lng=my_cleansed_data$lat_lon.longitude)
my_popups<-my_cleansed_data$pd_desc
my_latlng %>% leaflet() %>% addTiles() %>% addMarkers(popup=my_popups, clusterOptions=markerClusterOptions())
Because this is connected to the NYC crime API, it will automatically update over time, pulling the last 1000 observations (which will then be filtered down to just our specifications which as of this writing was 66 different cases). Generally speaking, as of this writing violent crime is fairly dispersed across Manhattan but seems to be lower in FiDi and the Upper East and Upper West. Times Square, Lower East Side, Harlem and East Harlem seem to have the most violent crime.