R/fars_functions.R

Defines functions fars_read make_filename fars_read_years fars_summarize_years fars_map_state

Documented in fars_map_state fars_read fars_read_years fars_summarize_years make_filename

#' Read CSV into R
#'
#' This is a function that takes the filename of a .csv file as an argument and
#' returns that file loaded into R as a tibble.
#'
#' For this function to work properly, a file must exist at the path specified
#' by the argument.
#'
#' @param filename The filename of the .csv file you want to import
#'
#' @return This function returns an R tibble containing the data from the .csv
#'   file that was read in. This function will return Error in
#'   file.exists(filename) : invalid 'file' argument if no file exists at the
#'   filepath specified as the filename argument.
#'
#' @examples
#' \dontrun{fars_read("coursera/data/accident_2013.csv.bz2")}
#' \dontrun{fars_read("data.csv")}
#'
#'
#' @importFrom dplyr tbl_df
#' @importFrom readr read_csv
#'
#' @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)
}
#' Make Filename From Year
#'
#' This function takes a year as an argument and uses that to
#' construct a valid filepath to the accident dataset for that year.
#'
#' For this function to work properly, a valid year must be provided.
#' Character strings as argument will return invalid filepaths
#' with NA. If you provide a year as for which no accident data is
#' available as the argument to this function, it will return
#' a filepath that may not refer to any existing file. This
#' will not cause an error in this function but will cause problems
#' if used as an argument in other functions within this package
#' such as \code{fars_read}
#'
#' @param year The year you want to pull data from.
#'
#' @return This function returns a valid filepath within
#' your R working directory.
#'
#' @examples
#' make_filename(2013)
#' make_filename(10)
#'
#' @note The second example will work, but the filename does not point to anything.
#'
#'
make_filename <- function(year) {
  year <- as.integer(year)
  sprintf("accident_%d.csv.bz2", year)
}

#' Import data for multiple years
#'
#' @param years The list or vector of four-digit years for which you want to
#'   import information.
#'
#' @return This function returns a list in which each element corresponds to
#'   an element in the argument "years." For each valid year in "years," the
#'   corresponding element of the list will be a tibble with rows equal to the
#'   number of observations and two columns: MONTH and year.
#'
#'   If an invalid year
#'   is provided as an argument, the corresponding element of the returned list
#'   will be NULL. A warning message will then print: \code{Warning message: In
#'   value[[3L]](cond) : invalid year}
#'
#' @examples
#' fars_read_years(2014)
#' fars_read_years(c(2013, 2014))
#' fars_read_years(c(2013, "invalid input"))
#'
#' @note Note that if input contains both valid and invalid years, the function will
#' successfully process the valid years while still returning \code{NULL} and giving
#' out a warning for invalid years.
#'
#' @importFrom dplyr mutate 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(MONTH, year)
    }, error = function(e) {
      warning("invalid year: ", year)
      return(NULL)
    })
  })
}

#' Summarize Monthly Accident Totals
#'
#' This is a function that takes a set of years and, for each
#' year, returns a tibble showing the total number of accidents
#' recorded in each month of that year.
#'
#' It uses \code{fars_read_years} in the body of the function to read in the
#' set of years. It then uses tidyverse functions from dplyr and tidyr, in
#' addition to the \code{%>%} piping function from magrittr, to form a tidy
#' dataset containing the number of accidents for each month of each year
#' in the dataset.
#'
#' For this function to work properly, a year must be provided that
#' corresponds to a year of data in a properly-named spreadsheet in the
#' working directory. If the year is not valid or the spreadsheet is not
#' in the directory, the function will return an error.
#'
#'
#' @inheritParams fars_read_years
#'
#' @return This function returns a tibble with 12 rows - one corresponding to
#' each month of the year - and one column, titled by the four-digit year,
#' for each valid year provided in the argument plus an additional column
#' MONTH listing the months in the data from 1-12.
#'
#' Each column named with a year shows the total month-by-month accident
#' reports for each month of that year.
#'
#'
#' @examples
#' fars_summarize_years(c(2013, 2014))
#' fars_summarize_years(2015)
#' fars_summarize_years(2010)
#'
#' @importFrom dplyr bind_rows group_by summarize
#' @importFrom tidyr spread
#'
#'
#' @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)
}

#' State Accident Mapping
#'
#' This function takes years and a state number and plots
#' the accident locations within that state.
#'
#' The function uses \code{\link{make_filename}} and \code{\link{fars_read_years}} to
#' pull data from the Fatality Analysis Reporting Spreadsheet for the given years.
#' It then checks to ensure the chosen state number is valid and that there
#' were fatal accidents in that state for the given year. If there were, it
#' uses the maps and graphics packages to plot the locations of those accidents
#' along with a rough outline of the state's boundaries.
#'
#' @param state.num A state number from the alphabetical list of states.
#' @param year The year from which you want to draw data.
#'
#' @return This function, even when successfully run, returns NULL invisibly.
#' However, it generates a plot in the course of running.
#'
#' @examples
#' fars_map_state(1,2014)
#' fars_map_state(4,2013)
#'
#' @note These examples plot the accidents from Alabama in 2014 and Arkansas in 2013,
#' respectively.
#'
#' @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)
  })
}
alexmjn/advancedr documentation built on May 29, 2019, 5:57 p.m.