R/fars_functions.R

#' The following functions read, summarize and plot data from the US National Highway
#' Traffic Safety Administration's Fatality Analysis Reporting System (FARS)
#' \href{http://www.nhtsa.gov/research-data/fatality-analysis-reporting-system-fars}{Fatality Analysis Reporting System (FARS)}.
#'
#'
#' Data reading by file name
#'
#' This function reads a FARS file and creates a data
#' frame table. The file name is generated by the function make_filename.
#'
#' @param filename the name of the file containing the data to  be read.
#'
#' @return This function returns a data frame table when the file exists. An
#' error is given if the file doesn't exist. The file has to be located in
#' the present working directory
#'
#' @examples
#' \dontrun{
#'   my_data <- fars_read("accident_2013.csv.bz2")
#' }
#'
#' @importFrom readr read_csv
#' @importFrom dplyr tbl_df %>%
#'
#' @export



fars_read <- function(filename) {
        if(!file.exists(filename))
                stop("file '", filename, "' does not exist")
        data <- suppressMessages({
                readr::read_csv(filename, progress = FALSE)
        })
        dplyr::tbl_df(data)
}

#' File name making
#'
#' This function creates the FARS file name based in the year covered
#' by the data
#'
#'
#' @param year An integer or string indicating the year of the FARS report
#'
#' @return This function return a string with the FARS file name
#'
#'
#' @examples
#' \dontrun{
#' my_file <- make_filename(2013)
#' my_file <- make_filename("2013")
#' }
#'
#' @export

make_filename <- function(year) {
        year <- as.integer(year)
        sprintf("accident_%d.csv.bz2", year)
}

#' Reading multiple years of FARS data files
#'
#' This function extracts months and years of every FARS
#' file within the years specified. An error is retuned for invalid years
#' specified when the FARS file doesn't exits for that year
#'
#' @param years a vector of integers or strings with the year of the FARS data files
#'
#' @return a list of FARS months and years based on the FARS files specified by
#' the years input
#'
#'
#'
#' @importFrom dplyr mutate select %>%
#' @importFrom stats setNames
#'
#' @examples
#'   \dontrun{
#'     my_data <- fars_read_years(c(2013, 2014, 2015))
#'     my_data <- fars_read_years(c("2013", "2014", "2015"))
#'   }
#'
#' @export

fars_read_years <- function(years) {
        lapply(years, function(year) {
                file <- make_filename(year)
                tryCatch({
                        dat <- fars_read(file)
                        dplyr::mutate_(dat,.dots = setNames(list(~year), "year")) %>%
                                dplyr::select_(~MONTH, ~year)
                }, error = function(e) {
                        warning("invalid year: ", year)
                        return(NULL)
                })
        })
}

#' Fatalities by month and year
#'
#'  This functions gives a summary of the fatalities by month for
#' every FARS files read by year
#'
#' @param years a vector of integers or strings with the year of the FARS data
#' files
#'
#' @return This function return the table (tibble) of the fatalities by month for every
#' year specified of the FARS file
#'
#'
#' @importFrom dplyr bind_rows group_by summarize %>%
#' @importFrom tidyr spread
#' @importFrom stats setNames
#'
#' @examples
#'   \dontrun{
#'     fars_summarize_years(c(2013, 2014))
#'     fars_summarize_years(c("2013", "2014"))
#'   }
#' @export

fars_summarize_years <- function(years) {
        dat_list <- fars_read_years(years)
        dplyr::bind_rows(dat_list) %>%
                dplyr::group_by_(~year, ~MONTH) %>%
                dplyr::summarize_(.dots = setNames(~n(), "n")) %>%
                tidyr::spread_(~year, ~n)
}

#' Plotting fatalities' state locations by  year
#'
#' This function generates a US state map with the locations of the
#' fatalities for a given year. An error is given if the state number is not
#' present in the data set. If no fatalities present a messages is generated
#'
#' @param state.num An integer representing a US state
#' @param year An integer or string for the year of the FARS file
#'
#' @return this function returns a US state map with dots representing the
#' fatalities in a given year for a FARS file
#'
#'
#'
#' @importFrom dplyr filter %>%
#' @importFrom maps map
#' @importFrom graphics points
#'
#' @examples
#'   \dontrun{
#'     fars_map_state(10, 2015)
#'     fars_map_state(36, 2014)
#'     fars_map_state(50, 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)
        })
}
ykv001/FARSpckgwk4 documentation built on May 6, 2019, 12:05 a.m.