Travis build status codecov CRAN RStudio mirror downloads Life cycle DOI

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

stats19

stats19 provides functions for downloading and formatting road crash data. Specifically, it enables access to the UK's official road traffic casualty database, STATS19. (The name comes from the form used by the police to record car crashes and other incidents resulting in casualties on the roads.)

A full overview of STATS19 variables be found in a document provided by the UK's Department for Transport (DfT).

The raw data is provided as a series of .csv files that contain integers and which are stored in dozens of .zip files. Finding, reading-in and formatting the data for research can be a time consuming process subject to human error. stats19 speeds up these vital but boring and error-prone stages of the research process with a single function: get_stats19(). By allowing public access to properly labelled road crash data, stats19 aims to make road safety research more reproducible and accessible.

For transparency and modularity, each stage can be undertaken separately, as documented in the stats19 vignette.

Installation

Install and load the latest version with:

remotes::install_github("ropensci/stats19")
library(stats19)

get_stats19()

get_stats19() requires year and type parameters, mirroring the provision of STATS19 data files, which are categorised by year (from 1979 onward) and type (with separate tables for crashes, casualties and vehicles, as outlined below). The following command, for example, gets crash data from 2017 (note: we follow the "crash not accident" campaign of RoadPeace in naming crashes, although the DfT refers to the relevant tables as 'accidents' data):

crashes = get_stats19(year = 2017, type = "accident")

What just happened? We read-in data on all road crashes recorded by the police in 2017 across Great Britain. The dataset contains r ncol(crashes) columns (variables) for r format(nrow(crashes), big.mark = ",") crashes. The contents of this dataset, and other datasets provided by stats19, are outlined below and described in more detail in the stats19 vignette.

We will see below how the function also works to get the corresponding casualty and vehicle datasets for 2017. The package also allows STATS19 files to be downloaded and read-in separately, allowing more control over what you download, and subsequently read-in, with read_accidents(), read_casualties() and read_vehicles(), as described in the vignette.

Data download

Data files can be downloaded without reading them in using the function dl_stats19(). If there are multiple matches, you will be asked to choose from a range of options. Providing just the year, for example, will result in the following options:

dl_stats19(year = 2017)
Multiple matches. Which do you want to download?

1: dftRoadSafetyData_vehicles.zip
2: dftRoadSafetyData_casualties.zip
3: dftRoadSafetyData_Accidents_2017.zip

Selection: 
Enter an item from the menu, or 0 to exit

Using the data

STATS19 data consists of 3 main tables:

The contents of each is outlined below.

Crash data

Crash data was downloaded and read-in using the function get_stats19(), as described above.

nrow(crashes)
ncol(crashes)

Some of the key variables in this dataset include:

crashes[c(7, 18, 23, 25)]

For the full list of columns, run names(crashes) or see the vignette.

Casualties data

As with crashes, casualty data for 2017 can be downloaded, read-in and formatted as follows:

casualties = get_stats19(year = 2017, type = "casualties")
nrow(casualties)
ncol(casualties)

The results show that there were r format(nrow(casualties), big.mark=",") casualties reported by the police in the STATS19 dataset in 2017, and r ncol(casualties) columns (variables). Values for a sample of these columns are shown below:

casualties[c(4, 5, 6, 14)]

The full list of column names in the casualties dataset is:

names(casualties)

Vehicles data

Data for vehicles involved in crashes in 2017 can be downloaded, read-in and formatted as follows:

vehicles = get_stats19(year = 2017, type = "vehicles")
nrow(vehicles)
ncol(vehicles)

The results show that there were r format(nrow(vehicles), big.mark=",") vehicles involved in crashes reported by the police in the STATS19 dataset in 2017, with r ncol(vehicles) columns (variables). Values for a sample of these columns are shown below:

vehicles[c(3, 14:16)]

The full list of column names in the vehicles dataset is:

names(vehicles)

Creating geographic crash data

An important feature of STATS19 data is that the "accidents" table contains geographic coordinates. These are provided at ~10m resolution in the UK's official coordinate reference system (the Ordnance Survey National Grid, EPSG code 27700). stats19 converts the non-geographic tables created by format_accidents() into the geographic data form of the sf package with the function format_sf() as follows:

crashes_sf = format_sf(crashes)

The note arises because NA values are not permitted in sf coordinates, and so rows containing no coordinates are automatically removed. Having the data in a standard geographic form allows various geographic operations to be performed on it. The following code chunk, for example, returns all crashes within the boundary of West Yorkshire (which is contained in the object police_boundaries, an sf data frame containing all police jurisdictions in England and Wales).

library(sf)
library(dplyr)
wy = filter(police_boundaries, pfa16nm == "West Yorkshire")
crashes_wy = crashes_sf[wy, ]
nrow(crashes_sf)
nrow(crashes_wy)

This subsetting has selected the r format(nrow(crashes_wy), big.mark = ",") crashes which occurred within West Yorkshire in 2017.

Joining tables

The three main tables we have just read-in can be joined by shared key variables. This is demonstrated in the code chunk below, which subsets all casualties that took place in Leeds, and counts the number of casualties by severity for each crash:

sel = casualties$accident_index %in% crashes_wy$accident_index
casualties_wy = casualties[sel, ]
cas_types = casualties_wy %>% 
  select(accident_index, casualty_type) %>% 
  mutate(n = 1) %>% 
  group_by(accident_index, casualty_type) %>% 
  summarise(n = sum(n)) %>% 
  tidyr::spread(casualty_type, n, fill = 0) 
cas_types$Total = rowSums(cas_types[-1])
cj = left_join(crashes_wy, cas_types, by = "accident_index")

What just happened? We found the subset of casualties that took place in West Yorkshire with reference to the accident_index variable. Then we used functions from the tidyverse package dplyr (and spread() from tidyr) to create a dataset with a column for each casualty type. We then joined the updated casualty data onto the crashes_wy dataset. The result is a spatial (sf) data frame of crashes in Leeds, with columns counting how many road users of different types were hurt. The original and joined data look like this:

crashes_wy[1:2, c(1, 5)] %>% st_drop_geometry()
cas_types[1:2, c("accident_index", "Cyclist")]
cj[1:2, c(1, 5, 34)] %>% st_drop_geometry()

Mapping crashes

The join operation added a geometry column to the casualty data, enabling it to be mapped (for more advanced maps, see the vignette):

cex = cj$Total / 3
plot(cj["speed_limit"], cex = cex)

The spatial distribution of crashes in West Yorkshire clearly relates to the region's geography. Crashes tend to happen on busy Motorway roads (with a high speed limit, of 70 miles per hour, as shown in the map above) and city centres, of Leeds and Bradford in particular. The severity and number of people hurt (proportional to circle width in the map above) in crashes is related to the speed limit. This can be seen by comparing the previous map with an overview of the area, from an academic paper on the social, spatial and temporal distribution of bike crashes in West Yorkshire [@lovelace_who_2016]:

knitr::include_graphics("https://raw.githubusercontent.com/ropensci/stats19/master/vignettes/wy-overview.jpg")

Time series analysis

We can also explore seasonal trends in crashes by aggregating crashes by day of the year:

library(ggplot2)
crashes_dates = cj %>% 
  st_set_geometry(NULL) %>% 
  group_by(date) %>% 
  summarise(
    walking = sum(Pedestrian),
    cycling = sum(Cyclist),
    passenger = sum(`Car occupant`)
    ) %>% 
  tidyr::gather(mode, casualties, -date)
ggplot(crashes_dates, aes(date, casualties)) +
  geom_smooth(aes(colour = mode), method = "loess") +
  ylab("Casualties per day")

Different types of crashes also tend to happen at different times of day. This is illustrated in the plot below, which shows the times of day when people who were travelling by different modes were most commonly injured.

library(stringr)

crash_times = cj %>% 
  st_set_geometry(NULL) %>% 
  group_by(hour = as.numeric(str_sub(time, 1, 2))) %>% 
  summarise(
    walking = sum(Pedestrian),
    cycling = sum(Cyclist),
    passenger = sum(`Car occupant`)
    ) %>% 
  tidyr::gather(mode, casualties, -hour)

ggplot(crash_times, aes(hour, casualties)) +
  geom_line(aes(colour = mode))

Note that cycling manifests distinct morning and afternoon peaks [see @lovelace_who_2016 for more on this].

Next steps

There is much important research that needs to be done to help make the transport systems in many cities safer. Even if you're not working with UK data, we hope that the data provided by stats19 data can help safety researchers develop new methods to better understand the reasons why people are needlessly hurt and killed on the roads.

The next step is to gain a deeper understanding of stats19 and the data it provides. Then it's time to pose interesting research questions, some of which could provide an evidence-base in support policies that save lives [e.g. @sarkar_street_2018]. For more on these next steps, see the package's introductory vignette.

Further information

The stats19 package builds on previous work, including:

ropensci_footer

References



ITSLeeds/stats19 documentation built on May 4, 2019, 7:35 a.m.