library(dplyr)
library(leaflet)

This document shows the location of all traffic fatalities in 2015. The data for this analysis comes from the National Highway Traffic Safety Administration’s (NHSTA) Fatality Analysis Reporting System (FARS).

download.file("ftp://ftp.nhtsa.dot.gov/fars/2015/National/FARS2015NationalCSV.zip",
              "FARS2015.zip")
unzip("FARS2015.zip", files="accident.csv", junkpaths=TRUE)
accidents <- read.csv("accident.csv")

The code below generates a map that shows the location of every crash in 2015. Crashes involving a drunk driver are colored red, while crashed that did not involve alcohol are colored blue. Clicking on any individual crash location will generate a popup with the date and time of the crash, along with the number of fatalities.

## Clean up the data for piping into leaflet()
accidents.clean <- accidents %>%
    mutate(drunk.driver=factor(DRUNK_DR, levels=c(0, 1),
                               labels=c("Sober", "Drunk")),
           ## Clean up the date and time fields
           date = sprintf("%d-%02d-%02d", YEAR, MONTH, DAY),
           am.pm = ifelse(HOUR < 12, "AM", "PM"),
           hour = HOUR %% 12,
           hour = ifelse(hour == 0, 12, hour),
           time.string = sprintf("%d:%02d%s", hour, MINUTE, am.pm),
           ## Pluralize label if necessary
           fatality.label = ifelse(FATALS > 1, "Fatalities", "Fatality"),
           ## Create final label
           label = sprintf("Crash on %s at %s; %d %s", 
                           date, time.string, FATALS, fatality.label)) %>%
    ## Keep only the fields we need
    select(latitude=LATITUDE, longitude=LONGITUD, drunk.driver, label)

## Create a color palette for drunk driving colorizing
drunk_palette <- colorFactor(c("#0000FF", "#FF0000"), c("Sober", "Drunk"))
## Set up clustering options
cluster.options <- markerClusterOptions(maxClusterRadius=35,
                                        disableClusteringAtZoom=11)

## Create map
leaflet(accidents.clean) %>%
    addTiles() %>%
    addCircleMarkers(clusterOptions=cluster.options, 
                     color= ~drunk_palette(drunk.driver), popup= ~label) %>%
    addLegend(pal= drunk_palette, values= ~drunk.driver,
              title="Drunk Driver Involved?") %>%
    fitBounds(-120, 43, -70, 32)