R/farsfunctions.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 fars data from file
#'
#' This function is a specialized data reading function for fars data.
#' \code{fars_read} is a wrapper for \code{\link[readr]{read_csv}} with added
#' functionality to output an object of class tbl_df instead of a data.frame.
#'
#' @param filename A character string for the file path to the fars data file to
#'   be read. filename must resolve to an existing file or function will error.
#'
#' @return This function returns an object of type tibble, which itself is an
#'   enhanced data.frame object. Please see tibble package for details on
#'   \code{\link[tibble]{tibble-package}} objects.
#'
#' @examples
#' \dontrun{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)
}

#' Create a year based filename
#'
#' This function will concatenate the fars file naming convention with the
#' provided \code{year} argument using \code{sprintf()} to produce a proper file
#' name for a data set.
#'
#' @param year The year associated with the data file. \code{year} can be of any
#'   single value basic type capable of being coerced to character string.
#'
#' @return This function returns a character string consisting of a proper
#'   filename. The output will not include a filepath, solely the name of data
#'   file.
#'
#' @examples
#' \dontrun{make_filename(year=2013)}
#' \dontrun{make_filename(year="2014")}
#'
#' @export
make_filename <- function(year) {
  year <- as.integer(year)
  sprintf("accident_%d.csv.bz2", year)
}


#' Read multiple fars data years
#'
#' This function will read in data for years provided in the \code{year}
#' argument by first creating filenames via \code{\link{make_filename}} and then
#' using \code{\link{fars_read}} to import fars data. If one of the elements of
#' \code{year} does not resolve to an existing filename, a warning is provided
#' for the given year and the data for that year is (obviously) not included in
#' the output.
#'
#' @param years A vector of years associated with the data files desired.
#'
#' @return This function returns a list of tibble objects (class tbl, tbl_df).
#'   See \code{\link[tibble]{tibble-package}} for tibble specifics.
#'
#' @examples
#' \dontrun{fars_read_years(2013:2014)}
#' \dontrun{fars_read_years(c(2013,2015))}
#' \dontrun{fars_read_years(c("2013","2014"))}
#'
#' @importFrom dplyr mutate
#' @importFrom dplyr select
#'
#' @export
fars_read_years <- function(years) {
  lapply(years, function(year) {
    file <- make_filename(year)
    tryCatch({
      dat <- fars_read(file)
      dat<-dplyr::mutate_(dat, .dots=stats::setNames(list(~year),c("year")))
        dplyr::select_(dat,~MONTH, ~year)
    }, error = function(e) {
      warning("invalid year: ", year)
      return(NULL)
    })
  })
}

#' Create useful summary of fars data
#'
#' This function will read in data for years specified via
#' \code{\link{fars_read_years}}, bind all list elements by \code{link[dplyr]{}}
#' and produce frequency of observations by month and year.
#'
#' @param years A vector of years associated with the data files desired.
#'
#' @return This function returns a tibble object (class tbl, tbl_df).
#' See \code{\link[tibble]{tibble-package}} for tibble specifics.
#'
#' @examples
#' \dontrun{fars_summarize_years(2013:2015)}
#' \dontrun{fars_summarize_years(c(2013,2015))}
#'
#' @importFrom dplyr bind_rows
#' @importFrom dplyr group_by
#' @importFrom dplyr summarize
#' @importFrom tidyr spread
#' @importFrom stats setNames
#'
#' @export
fars_summarize_years <- function(years) {
  dat_list <- fars_read_years(years)
  dat<-dplyr::bind_rows(dat_list)
  dat<-dplyr::group_by_(dat,.dots=stats::setNames(list(~year, ~MONTH),c("year","MONTH")))
  dat<-dplyr::summarize_(dat,.dots=stats::setNames(list(~n()),c("n")))
       tidyr::spread_(dat,"year", "n")
}

#' Create useful summary of fars data
#'
#' This function will plot a subset of fars data for a given state and year
#' using \code{\link[maps]{map}}. The data is read in for the year specified via
#' \code{\link{fars_read}} by loading the proper data file using
#' \code{\link{make_filename}} as an input to fars_read. LONGITUD > 900 or
#' LATITUDE > 90 are removed from the plot.
#'
#' @param state.num The numeric code coresponding to the state of interest. This
#'   will be coerced to integer. See State Number Reference Table.
#'
#' @param year The year associated with the data file. year can be of any single
#'   value basic type capable of being coerced to character string.
#'
#' @section State Number Reference Table:
#' \tabular{cc}{
#' \strong{state.num} \tab \strong{State}\cr
#' 1 \tab Alabama\cr
#' 2 \tab Alaska\cr
#' 4 \tab Arizona\cr
#' 5 \tab Arkansas\cr
#' 6 \tab California\cr
#' 8 \tab Colorado\cr
#' 9 \tab Connecticut\cr
#' 10 \tab Delaware\cr
#' 11 \tab District of Columbia\cr
#' 12 \tab Florida\cr
#' 13 \tab Georgia\cr
#' 15 \tab Hawaii\cr
#' 16 \tab Idaho\cr
#' 17 \tab Illinois\cr
#' 18 \tab Indiana\cr
#' 19 \tab Iowa\cr
#' 20 \tab Kansas\cr
#' 21 \tab Kentucky\cr
#' 22 \tab Louisiana\cr
#' 23 \tab Maine\cr
#' 24 \tab Maryland\cr
#' 25 \tab Massachusetts\cr
#' 26 \tab Michigan\cr
#' 27 \tab Minnesota\cr
#' 28 \tab Mississippi\cr
#' 29 \tab Missouri\cr
#' 30 \tab Montana\cr
#' 31 \tab Nebraska\cr
#' 32 \tab Nevada\cr
#' 33 \tab New Hampshire\cr
#' 34 \tab New Jersey\cr
#' 35 \tab New Meico\cr
#' 36 \tab New York\cr
#' 37 \tab North Carolina\cr
#' 38 \tab North Dakota\cr
#' 39 \tab Ohio\cr
#' 40 \tab Oklahoma\cr
#' 41 \tab Oregon\cr
#' 42 \tab Pennsylvania\cr
#' 43 \tab Puerto Rico\cr
#' 44 \tab Rhode Island\cr
#' 45 \tab South Carolina\cr
#' 46 \tab South Dakota\cr
#' 47 \tab Tennessee\cr
#' 48 \tab Teas\cr
#' 49 \tab Utah\cr
#' 50 \tab Vermont\cr
#' 51 \tab Virginia\cr
#' 52 \tab Virgin Islands\cr
#' 53 \tab Washington\cr
#' 54 \tab West Virginia\cr
#' 55 \tab Wisconsin\cr
#' 56 \tab Wyoming
#' }
#'
#' @return This function returns a plot object of the data with the given
#'   parameters.
#'
#' @examples
#' \dontrun{fars_map_state(30,2013)}
#'
#' @importFrom dplyr filter
#' @importFrom maps map
#'
#' @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)
  })
}
JJNewkirk/Rfars documentation built on May 7, 2019, 10:12 a.m.