R/fars_functions.R

Defines functions fars_map_state fars_summarize_years fars_read_years make_filename fars_read

Documented in fars_map_state fars_read fars_read_years fars_summarize_years make_filename

#' Silently read CSV file format
#'
#' This functions checks for an existent CSV file and read it silently. If
#' the file does not exists throws an error.
#'
#' @param filename A character string with a route to a CSV file
#'
#' @return At tibble object the CSV file data.
#'
#' @importFrom readr read_csv
#' @importFrom dplyr tbl_df
#' @export
#'
#' @examples
#' route <- system.file("extdata", "accident_2013.csv.bz2", package = "CourseraFARS")
#'
#' fars_read(route)
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 for FARS files
#'
#' Given a year creates a custom filename for FARS files.
#'
#' @param year Numeric. A number to format the filename
#'
#' @return A string with a custon filename
#' @export
#'
#' @examples
#' make_filename(2013)
make_filename <- function(year) {
  year <- as.integer(year)
  sprintf("accident_%d.csv.bz2", year)
}

#' Batch import of FARS data
#'
#' A iterator over a numeric yeare vector that reads FARS data for each given
#' year. If file does not exists returns a warning.
#'
#'
#' @param years Numeric vector for FARS years to read
#'
#' @return A list of tibbles. Each tibble contains two columns, MONTH and year
#' @export
#'
#' @importFrom dplyr mutate
#' @importFrom dplyr select
#' @importFrom magrittr "%>%"
#'
#' @examples
#' \dontrun{fars_read_years(2013:2015)}
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)
    })
  })
}

#' Summarize FARS years
#'
#' Count the number of observations by month in the given years
#'
#' @param years Numeric vector for FARS years to read
#'
#' @return A wide format tibble. One column for year and a MONTH column. Each
#' value is the count of observations in a year-month.
#' @export
#'
#' @importFrom dplyr bind_rows
#' @importFrom dplyr group_by
#' @importFrom dplyr summarize
#' @importFrom tidyr spread
#'
#' @examples
#' \dontrun{fars_summarize_years(2013:2015)}
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")
}

#' Draw a FARS data map for a given year and state
#'
#' Draws a map for a given year and state, one point for observation. It will
#' throw an error if state.num is not in the dataset. If no observations finded
#' it will throw a message.
#'
#' @param state.num Integer. State identifier
#' @param year Integer. Year of FAPS data
#'
#' @return NULL (Called by its side effects)
#' @export
#'
#' @importFrom maps map
#' @importFrom graphics points
#'
#' @examples
#' \dontrun{fars_map_state(1, 2013)}
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)
  })
}
JhossePaul/coursera_fars documentation built on May 8, 2017, 11:28 p.m.