#' Read FARS Data File
#'
#' `fars_read()` is a helper function used by `fars_read_years()` and `fars_map_state()`,
#' which reads in an annual FARS data file. The file is supposedly the query output from
#' the US National Highway Traffic Safety Administration's Fatality Analysis Reporting
#' System, exported into a .csv file and compressed in the bz2 format.
#'
#' @importFrom readr read_csv
#' @importFrom dplyr as_tibble
#'
#' @param filename A character string or object representing path to files
#'
#' @return A tibble contains the contents of input file, the first part of which will
#' be print out to console as a side effect. Invalid path will result in a "file ...
#' does not exist" error.
#'
#' @examples
#' \dontrun{
#' fars_read("accident_2013.csv")
#' }
fars_read <- function(filename) {
if(!file.exists(filename))
stop("file '", filename, "' does not exist")
data <- suppressMessages({
readr::read_csv(filename, progress = FALSE)
})
dplyr::as_tibble(data)
}
#' Construct File Path for a Specified Year
#'
#' `make_filename()` is a helper function used by `fars_read_years()` and `fars_map_state()`,
#' which constructs paths to annual FARS data files that corresponds to its argument and
#' follows a common naming pattern/convention.
#'
#' @param year A four digit number representing a year in the format 'YYYY', numeric
#'
#' @return A character string representing a file path
#'
#' @examples
#' \dontrun{
#' make_filename(2013)
#' }
make_filename <- function(year) {
year <- as.integer(year)
sprintf("accident_%d.csv.bz2", year)
}
#' Read in Annual FARS data for Multiple Years
#'
#' `fars_read_years()` is a helper function used by `fars_summarize_years()`,
#' which reads in fetal traffic accident entries for specified years from
#' accessible annual FARS data files within the current working directory
#'
#'
#' @importFrom dplyr mutate select
#' @importFrom tidyr %>%
#'
#' @inheritParams fars_summarize_years
#'
#' @return A list of tibbles containing annual accident entries that corresponds
#' to years specified in the argument. An invalid input value (year) will cause
#' a NULL value to be returned to the list and an "invalid year..." warning.
#'
#' @seealso \code{\link{fars_read}} and \code{\link{make_filename}},
#' which this function wraps
#' @examples
#' \dontrun{
#' fars_read_years(c(2013,2014,2015))
#' }
fars_read_years <- function(years) {
lapply(years, function(year) {
file <- make_filename(year)
tryCatch({
dat <- fars_read(file)
dplyr::mutate(dat, year = year) %>%
dplyr::select(MONTH, year)
}, error = function(e) {
warning("invalid year: ", year)
return(NULL)
})
})
}
#' Count FARS Traffic Accidents by Month and Year
#'
#' `fars_summarize_years()` produces a summary statistic of the fatal
#' traffic crash data compiled by the US National Highway Traffic Safety
#' Administration's Fatality Analysis Reporting System (FARS). The
#' function lets you count monthly totals of fatal traffic accidents
#' on an annual basis.
#'
#' \href{https://www.nhtsa.gov/research-data/fatality-analysis-reporting-system-fars}{See here}
#' for more information about FARS|NHTSA.
#'
#' @importFrom dplyr bind_rows group_by summarize
#' @importFrom tidyr spread %>%
#'
#' @param years a numeric vector of four digit numbers represents years
#' in the format 'YYYY'
#'
#' @return a summary or pivot table of monthly total values, generated by pivoting a
#' tibble wider, with rows by months and columns by years; An invalid value (year)
#' specified in the input will cause a NULL value generated while reading data from
#' corresponding file, missing value (column) for the invalid year in the output,
#' and a warning message "invalid year: ...". Completely invalid input will cause a
#' "Must group by variables found in `.data`" error in addition to warning messages
#' of "invalid year: ..."
#'
#' @seealso \code{\link{fars_read_years}} which this function wraps
#' @examples
#' \dontrun{
#' fars_summarize_years(c(2013,2014,2015))
#' }
#' \dontrun{
#' yrs <- 2013:2015
#' monthly_counts <- fars_summarize_years(years=yrs)
#' }
#'
#' @export
fars_summarize_years <- function(years) {
dat_list <- fars_read_years(years)
dplyr::bind_rows(dat_list) %>%
dplyr::group_by(year, MONTH) %>%
dplyr::summarize(n = dplyr::n()) %>%
tidyr::spread(year, n)
}
#' Plot Geographical Mapping of FARS Crash Location data by State
#'
#' `fars_map_state()` function plots geographic distribution of FARS
#' fatal traffic crash locations at individual state level. The function
#' reads in FARS data of the particular state and year specified in the
#' arguments, which includes the accidents’ geographical coordinates. The
#' function then calls \code{\link[maps]{map}} to draw the map of the state,
#' an outlined polygon selected from the geographical database of USA state
#' via the xlim and ylim arguments derived from accidents’ longitude and
#' latitude ranges. Lastly it calls \code{\link[graphics]{points}} function to
#' add the points mapping to all non NA coordinates in the data to the
#' state map.
#'
#' @importFrom maps map
#' @importFrom dplyr filter
#'
#' @param state.num A two-digit FIPS state numeric code
#' @param year A four-digit number representing a year
#'
#' @return The result or side-effect of \code{\link[maps]{map}} and
#' \code{\link[graphics]{points}}. Invalid \code{state.num}, which
#' has no match in STATE column of FARS data, will cause function
#' to stop execution and result in "invalid STATE number: ..." error.
#' Missing data for the state and year as specified in the arguments
#' will result in a warning message "no accidents to plot" and
#' (temporarily) an invisible NULL object to be returned.
#'
#'
#' @seealso \code{\link{fars_read}} and \code{\link{make_filename}},
#' which this function wraps
#' @examples
#' \dontrun{
#' fars_map_state(state.num=36, year=2013) # New York
#' }
#' \dontrun{
#' pdf(file="2015_STATE06.pdf")
#' fars_map_state(06, year=2015) # California
#' dev.off()
#' }
#'
#' @export
fars_map_state <- function(state.num, year) {
filename <- make_filename(year)
data <- fars_read(filename)
state.num <- as.integer(state.num)
if(!(state.num %in% unique(data$STATE)))
stop("invalid STATE number: ", state.num)
data.sub <- dplyr::filter(data, STATE == state.num)
if(nrow(data.sub) == 0L) {
message("no accidents to plot")
return(invisible(NULL))
}
is.na(data.sub$LONGITUD) <- data.sub$LONGITUD > 900
is.na(data.sub$LATITUDE) <- data.sub$LATITUDE > 90
with(data.sub, {
maps::map("state", ylim = range(LATITUDE, na.rm = TRUE),
xlim = range(LONGITUD, na.rm = TRUE))
graphics::points(LONGITUD, LATITUDE, pch = 46)
})
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.