Wrangling Crime Data with R

Christopher Prener, Ph.D.

2019-08-07

Overview

The goal of compstatr is to provide a suite of tools for working with crime data made public by the City of St. Louis’s Metropolitan Police Department.

Motivation

Among cities in the United States, St. Louis has the distinction of having the highest or one of the highest violent crime and homicide rates since 2010. It therefore presents an important site for social scientists, public health researchers, and health care providers as well as policy makers to understand the effects of violent crime on urban communities.

The City’s crime data, however, are difficult to work with and present a number of challenges for researchers. These data are inconsistently organized, with all data before 2013 and some months of 2013 itself having eighteen variables. Beginning during 2013, most (but not all) months have twenty variables, many of which are named differently from their pre-2014 counterparts. These inconsistencies, and the fact that working with their data requires managing over 120 spreadsheets that each download with with a .html file extension, are the motivating force behind compstatr.

We therefore provide a set of tools for accessing, preparing, editing, and mapping St. Louis Metropolitan Police Department (SLMPD) crime data, which are available on their website as .csv files. The categorization tools that are provided will work with any police department that uses 5 and 6 digit numeric codes to identify specific crimes.

Installation

We recommend that users install sf before proceeding with the installation of compstatr. Windows users should be able to install sf without significant issues, but macOS and Linux users will need to install several open source spatial libraries to get sf itself up and running. The easiest approach for macOS users is to install the GDAL 2.0 Complete framework from Kyng Chaos.

For Linux users, steps will vary based on the flavor being used. Our configuration file for Travis CI and its associated bash script should be useful in determining the necessary components to install.

Once sf is installed, the easiest way to get compstatr is to install it from CRAN:

The development version of compstatr can be accessed from GitHub with remotes:

Tips

Accessing SLMPD Data

SLMPD data can be accessed two ways - you can either read tables from the website directly into R using compstatr’s web scraping tools, or you can manually download the individual monthly tables and store them on disk before reading them in.

Both techniques produce identical “year-list” objects that are the core data type used for validation and standardization. The only difference between the two approaches is that the scraping method produces a year-list object that is ordered in reverse chronological order by month, whereas the manual download approach results in a year-list object ordered alphabetically by month.

In either case, you’ll want to start by loading the compstatr package:

> library(compstatr)

Read Tables Directly into R

As of version v0.2.0, data tables can be scraped and read directly into R without manually downloading them first. They are read from the St. Louis Metropolitan Police Department’s website and imported directly as objects in R’s global environment. To identify the last available month:

To enable scraping, an index of the available data needs to be created. Doing this is optional but highly recommended to improve performance:

The page, row, and value columns reflect the organizational characteristics of the iframe on SLMPD’s website. This index is used by cs_get_data() to find the requested table or tables, post a request via the SLMPD website’s form system, and then download your data:

Once data are downloaded, they need to be validated and standardized before proceeding with analysis.

Use Tables Downloaded Manually

While scraping is now an option, St. Louis data can still be downloaded month-by-month from SLMPD. compstatr assumes that only one year of crime data (or less) is included in specific folders within your project. These next examples assume you have downloaded all of the data for 2017 and 2018, and saved them respectively in data/raw/2017 and data/raw/2018.

You should be aware that compstatr uses an opinionated approach for data organization. Data should be downloaded from SLMPD into a clear folder hierarchy that approximates this:

The initial functions cs_prep_data() and cs_load_data() (both of which are described below) assume that there are no more than 12 files per folder containing raw data. The function cs_prep_data() can be used to rename files, which will be downloaded with the wrong file extension (January2018.csv.html). Once downloaded you can load them into what we call year-list objects:

Once data are downloaded, they need to be validated and standardized before proceeding with analysis.

Usage

Regardless of how you create your year-list object, you will need to follow the same workflow below.

Data Preparation

Both the data downloaded manually as well as the tables scraped from SLMPD’s website are inconsistently organized. Problems that need to be addressed prior to collapsing a year-list into a single object can be identified with cs_validate():

If a FALSE value is returned, the vebose = TRUE argument provides additional detail:

In this case, we have the wrong number of variables for the month of May (in this case there are 26). We can fix this by using cs_standardize() to create the correct number of columns (20) and name them appropriately:

For 2013 and prior years, there will be only 18 variables. The 2013 data need to be fixed month by month because there are some correct months, but years 2008 through 2012 can be fixed en masse:

If there are more significant problems with a given month, cs_extract_month() can be used to pull a single month out of a year-list object. It can then be edited using dplyr or similar tools, and then replaced into the year-list object with cs_replace_month(). As of March 2019, there are no months of released data that require this. These functions are therefore provided as cautionary tools.

Once the data have been standardized, we can collapse them into a single object with cs_collapse():

This gives us all of the crimes reported in 2017. However, there will be crimes that were reported that year that occurred in prior years, and there may also be crimes reported in 2018 that took place in our year of interest. We can address both issues (assuming we have the next year’s data) with cs_combine():

We now have a tibble containing all of the known crimes that occurred in 2017 (including those reported in 2018).

Data Wrangling and Mapping

Once we have the data prepared, we can easily pull out a specific set of crimes to inspect further. For example, we could identify homicides. In the next few examples, we’ll use the january2018 example data that comes with the package. We’ll start by using cs_filter_crimes() to select only homicides as well as cs_filter_count() to remove any unfounded incidents:

There are also options for categorizing crimes, including cs_crime_cat(), which creates a numeric, string, or factor variable that summarizes each individual crime by UCR code. Likewise, there is a cs_crime() function that creates logical vectors that are TRUE if a given observation fits into the specified UCR code or family of UCR codes (like Part 1, violent, or property crimes).

Next, we’ll check for missing spatial data with cs_missingXY():

We don’t have any missing spatial data in this example, but if we did we would need to remove those observations with dplyr::filter() (or another subsetting tool). The compstatr package also comes with a function, cs_replace0(), that can be used to properly convert coordinates that are given as 0 to NA.

Finally, we can project and map our data:

These data can also be mapped using ggplot2 once they have been projected:

Non St. Louis Data

If you work with data from other police departments, the cs_crime(), cs_crime_cat(), and cs_filter_crime() functions may be useful for identifying, grouping, and subsetting by crime so long as they use a standard set of 5 and 6 digit codes based on the UCR system (e.g. 31111 (robbery with a firearm) or 142320 (malicious destruction of property)).

Getting Help