R/fars_functions.R

#' Reading data
#'
#' Imports data from a csv file and transform it into a tibble.
#' You specify the name of the file to read using the \code{filename} argument).
#'
#' @param filename A character string giving the name of the csv file to read.
#'
#' @return This function returns a tibble in the form of a tibble data frame.
#'
#' @note Returns an explicit error message if the file named \code{filename} does not exist.
#'
#' @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)
}


#' Creating a filename
#'
#' Creates a filename that specifies the year of the accident data as given by the
#' \code{year} argument.
#'
#' @param year An integer (or numeric) object specifying a year.
#'
#' @return This function returns a character string of the form "accident_\code{year}.csv.bz2",
#' where \code{year} is replaced with the given numeric input value.
#'
#'
#' @export
make_filename <- function(year) {
        year <- as.integer(year)
        sprintf("accident_%d.csv.bz2", year)
}

#' Keeping month and year information
#'
#' Only keeps month and year of accidents for a given input vector of years specified in the
#'\code{years} argument.
#'
#' @param years A vector of integers (or numerics) specifying some years.
#'
#' @return This function returns a list with same length as the input vector \code{years}.
#' To each year given in the input vector \code{years} corresponds an element of the list, which is
#' \itemize{
#'   \item either a 2-column tibble containing the month and year of all accidents
#' for that year, if the data for that year are available
#'   \item or the NULL element otherwise.
#' }
#'
#' @note If the data for a year given in the input vector \code{years} are not available,
#' then a Warning message "invalid year" is also issued.
#'
#' @importFrom dplyr mutate
#' @importFrom dplyr select
#' @importFrom magrittr %>%
#'
#'
#' @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_(.dots=c('MONTH', 'year'))
                }, error = function(e) {
                        warning("invalid year: ", year)
                        return(NULL)
                })
        })
}

#' Counting accidents per month
#'
#' Gives the number of accidents for each month, over the years specified in
#' the \code{years} argument.
#'
#' @param years A vector of integers or numerics specifying some years.
#'
#' @return A tibble giving the number of accidents per month for each year specified in \code{years}
#' whose data are available.
#'
#' @note Raises an error if the data are not available for any of the years specififed
#' in the \code{years} argument.
#'
#' @importFrom dplyr bind_rows group_by summarize
#' @importFrom tidyr spread
#' @importFrom magrittr %>%
#'
#'
#' @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_(key_col='year', value_col='n')
}


#' Mapping accident locations
#'
#' Maps accident locations for a given state over a given year.
#'
#' @param num.state An integer, code for a state of the USA.
#' @param year An integer (or numeric) specifying some year.
#'
#' @return Plots the map of all accident locations over a given year in a given state.
#'
#' @note Possible error messages
#' #' \itemize{
#'   \item "invalid STATE number": no accident data for this state and year
#'   \item "nothing to draw": regions out bounds (Alaska, Hawai)
#' }
#'
#' @importFrom dplyr filter
#' @importFrom maps map
#' @importFrom graphics points
#'
#'
#' @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)
        })
}
NataKouA/traffan documentation built on May 3, 2019, 3:38 p.m.