Edit this page

< back to recipes

Police recorded crime and incidents of anti-social behaviour (ASB) that occur within a mile radius of a specific location are available from data.police.uk. The location of each crime or incident of ASB is only approximate but interesting spatial patterns can still emerge. In this recipe we’ll pull out the latest incidents of anti-social behaviour (June 2019) within a mile of Piccadilly Gardens in Manchester.

Ingredients

Instructions

  1. Load the necessary R packages.
library(tidyverse) ; library(opencage) ; library(httr) ; library(jsonlite) ; library(sf) ; library(mapview)
  1. Create a string object with the name of a location or postcode in England, Wales or Northern Ireland.
location <- "Piccadilly Gardens"
  1. Use the opencage package to ‘forward geocode’ i.e. return the latitude and longitude for your location. You’ll need to obtain a free API key to access the OpenCage service.
coordinates <- opencage_forward(key = "<your API key>",
                                placename = location, 
                                countrycode = "GB")$results
  1. Check the coordinates correspond to the location.
coordinates$formatted[1]
  1. Request the latest street-level crimes and incidents of anti-social behaviour within a mile radius of the location from the data.police.uk API.
crime_and_asb <- GET(url = "https://data.police.uk/api/crimes-street/all-crime",
                     query = list(lat = coordinates$geometry.lat[1],
                                  lng = coordinates$geometry.lng[1])) %>% 
  content(as = "text", encoding = "UTF-8") %>% 
  fromJSON(flatten = TRUE) %>% 
  mutate(location.latitude = as.numeric(location.latitude),
         location.longitude = as.numeric(location.longitude))
  1. Count and sort the number of crimes per category.
count(crime_and_asb, category, sort = TRUE)
  1. Identify the top 10 repeat locations for incidents of anti-social behaviour.
repeat_locations <- crime_and_asb %>%
  filter(category == "anti-social-behaviour") %>% 
  group_by(location.latitude, location.longitude, location.street.name, category) %>% 
  summarise(n = n()) %>%
  ungroup() %>%
  arrange(desc(n)) %>% 
  slice(1:10)
  1. Convert to a spatial object ready for mapping.
sf <- st_as_sf(repeat_locations, crs = 4326, coords = c("location.longitude", "location.latitude"))
  1. Visualise the repeat locations of anti-social behaviour incidents in an interactive map.
mapview(sf, 
        map.types = c("CartoDB.Positron", "CartoDB.DarkMatter"),
        cex = "n",
        col = "#FFFFFF", col.regions = "#374f6b", alpha.regions = 1,
        layer.name = unique(sf$category),
        label = unique(sf$category), legend = FALSE)