R/fars_functions.R

#  ----------------------------------------------------------------------------
#  COURSERA: BUILDING R PACKAGES
#  File: fars_functions.R
#  ---------------------------------------------------------------------------


#' Reads a csv file and returns a data frame
#'
#' This function reads a csv file (can be compressed in bz2 format) & returns a
#' data frame (tibble) with the loaded data.
#'
#' @param filename A character string with the name of the file to read.
#'
#' @return A data frame(tibble) of the data contained in the cvs file.
#'     An error if the file doesn't exist or if it is not in the current directory.
#'
#' @importFrom readr read_csv
#' @importFrom dplyr tbl_df
#'
#' @examples
#' \dontrun{
#' fars_read("accident_2015.csv.bz2")
#' }
#'
#' @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)
}



#' Creates a string filename with a specific year
#'
#' This function reads a year number as an integer and adds it to the general filename
#' "accident_.csv.bz2", to create a string filename "accident_YEAR.csv.bz2".
#'
#' @param year A year in numbers (character, integer or numeric) to add to the filename.
#'
#' @return A string of a filename as "accident_YEAR.csv.bz2", with the specified year.
#'		An error if year numbers are not character, integer or numeric. See note.
#'
#' @examples
#' make_filename(2015)
#' make_filename("2013")
#'
#' @note if a text different from numbers is introduced, it won't be coerced to an
#'		integer and an error will be returned.
#'
#' @export


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



#' Creates a list of data frames by Year with its correspondent Year and Months
#'
#' This function reads the data from the US National Highway Traffic Safety Administration's
#' Fatality Analysis Reporting System, which is a nationwide census providing the American
#' public yearly data regarding fatal injuries suffered in motor vehicle traffic crashes from a
#' file type "accident_YEAR.csv.bz2", creates a data frame with multiple columns and
#' selects the specified Years and their correspondent Month columns. Then it creates a list with
#' separate data frames for each year. Each data frame contains two columns: month and year.
#'
#' @param years A year or vector of years in numeric or integer format.
#'
#' @return List containing data frames for each year, each one with two columns: MONTH & Year.
#'		ERROR Null data frames & warnings if the introduced year(s) doesn't exist (file(s) doesn't exist).
#'
#' @importFrom dplyr %>% mutate select
#'
#' @examples
#' fars_read_years(2013:2015)
#' fars_read_years(2014)
#'
#' @export


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)
                })
        })
}



#' Creates a data frame with the number of accidents by year and month in the US.
#'
#' This function reads the data from the US National Highway Traffic Safety Administration's
#' Fatality Analysis Reporting System, which is a nationwide census providing the American
#' public yearly data regarding fatal injuries suffered in motor vehicle traffic crashes.
#' Then creates several data frames in a list, groups them by year,
#' makes a summary of the number of accidents by MONTH and creates a data frame with this data with
#' Year's as columns and MONTH's as rows.
#'
#' @param years A year or vector of years in numeric or integer format.
#'
#' @return A data frame(tibble) containing columns for each Year and rows for each Month.
#'		Error(s) and Warning(s) if the introduced year(s) doesn't exist (file(s) doesn't exist).
#'
#' @importFrom dplyr bind_rows %>% group_by summarize
#' @importFrom tidyr spread
#'
#' @examples
#' \dontrun{
#' fars_summarize_years(2013:2015)
#' fars_summarize_years(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(n = n()) %>%
                tidyr::spread(year, n)
}



#' Plots the location of accidents in a US state in a year
#'
#' This function reads the data from the US National Highway Traffic Safety Administration's
#' Fatality Analysis Reporting System, which is a nationwide census providing the American
#' public yearly data regarding fatal injuries suffered in motor vehicle traffic crashes.
#' Then selects data from a specific state and a specific year and plots the location of the
#' accidents in a map of the state.
#'
#' @param state.num A number of a state (numeric, integer or character).
#' @param year A year number (numeric, integer or character).
#'
#' @return Plot of a map of the state and the location of the accidents in a year.
#'		Error if the introduced year and state aren't numbers.
#'		Error if the introduced year doesn't exist (file doesn't exist).
#'		Error if the introduced state doesn't exist in the data.
#'		Error if the number of accident is zero for given year and state.
#'
#' @importFrom dplyr filter
#' @importFrom maps map
#' @importFrom graphics points
#'
#' @examples
#' \dontrun{
#' fars_map_state(1,2015)
#' fars_map_state("1",2015)
#' fars_map_state(1.00,2015)
#' fars_map_state(1,"2015")
#' fars_map_state(1,2015.00)
#' }
#'
#' @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)
        })
}


## In the same source file (to remind you that you did it) add:
if(getRversion() >= "2.15.1")  utils::globalVariables(c("MONTH", "STATE", "n", "year"))
## Avoids the Undefined global functions or variables NOTE in Build:Check
LOT801106/FARS documentation built on May 10, 2019, 2:41 p.m.