R/fars_map_state.R

Defines functions fars_map_state

Documented in fars_map_state

#' fars_map_state
#'
#' Read and map data from Fatality Analysis Reporting System data by year
#'
#' This function reads in Fatality Analysis Reporting System data per year
#' and maps accident location in a specific State.
#'
#' @param state.num Define a number between 1 and 56, corresponding to the state or territory to map.
#' @param year Define the four digit year in 'YYYY' format you'd like to map
#'
#' @return Displays a State map of class map with accident locations
#'
#' @importFrom dplyr filter
#' @importFrom graphics points
#' @import maps
#'
#' @section Warning: If an invalid state number is entered, the function will stop and prin "Invalid STATE number: x".
#' If there are no accidents in the state selected, the function will return an invisible NULL.
#'
#' @example fars_map_state(2, 2013)
#'
#' @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)
        })
}
JustinMShea/Fatality-Analysis-Reporting-System documentation built on Sept. 20, 2017, 12:01 a.m.