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 file
#'
#' @description Reads a CSV file in and creates a tibble from it. Specify the
#'   filename using the \code{filename} argument.
#'
#' @param filename Either a path to a file, a connection, or literal data.
#'   Compressed files will be automatically uncompressed. Files on the web will
#'   be automatically downloaded.
#'
#' @return Returns a tibble based on the specified CSV file.
#'
#' @details Returns an error if \code{filename} does not exist.
#'
#' @examples
#' \dontrun{
#' accident_2013 <- fars_read("accident_2013.csv.bz2")
#' }
#'
#' @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)
}

#' Construct filename string
#'
#' @description Creates a filename, in the following format:
#'   \code{"accident_<year>.csv.bz2"}, where \code{year} is a parameter.
#'
#' @param year An integer representing the year in the FARS dataset.
#'   Non-integers are coerced to integer.
#'
#' @return Returns a filename as a character string.
#'
#' @examples
#' \dontrun{
#' # Integers or any data that can be coerced to an integer
#' make_filename(2000L)
#' make_filename(2000)
#' make_filename(2000.2)
#'
#' # If there is a conversion problem, you get a warning and the element is replaced by NA
#' make_filename("This cannot be coerced to an integer")
#' }
make_filename <- function(year) {
	year <- as.integer(year)
	sprintf("accident_%d.csv.bz2", year)
}

#' Read CSV file and select the month and year columns, filtered by a set of
#' years.
#'
#' @description This function reads a CSV file, then filters its contents based
#'   on \code{year} and selects the \code{MONTH} and \code{year} columns.
#'
#' @param years A vector or list of years to filter by.
#'
#' @return Returns a list of tibbles consisting of two columns: \code{month} and
#'   \code{years}.
#'
#' @details Returns a warning and NULL value if the file with \code{year} does
#'   not exist.
#'
#' @examples \dontrun{
#' # Existing integer or list of integers
#' fars_read_years(2013)
#' fars_read_years(2013:2015)
#'
#' # If years contain a non-existing integer or it cannot be coerced to an integer, NA is returned
#' fars_read_years(2010)
#' fars_read_years(c(2013, "Not an integer"))
#' }
#'
#' @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(MONTH, year)
		}, error = function(e) {
			print(e)
			warning("invalid year: ", year)
			return(NULL)
		})
	})
}

#' Count accidents by months, filtered by a set of years.
#'
#' @description This function counts accidents grouped by months and filtered by
#'   \code{years}
#'
#' @param years A vector of integers representing a series of years
#'
#' @return Returns a tibble consisting of \code{MONTH} and the count of records
#'   for every \code{year} in the \code{years}.
#'
#' @details Returns an error if none of the elements in \code{years} is valid.
#'   If only some of the elements are invalid returns the tibble and throws
#'   warnings for every invalid year.
#'
#' @importFrom dplyr bind_rows
#' @importFrom dplyr group_by
#' @importFrom dplyr summarize
#' @importFrom tidyr spread
#' @importFrom magrittr %>%
#'
#' @examples \dontrun{
#' # Filtering by existing years
#' fars_summarize_years(2013)
#' fars_summarize_years(2013:2015)
#'
#' # Filtering by partially existing years
#' fars_summarize_years(2010:2013)
#' fars_summarize_years(2013:2017)
#'
#' # Filtering by non-existing years
#' fars_summarize_years(2010)
#' fars_summarize_years(2016:2018)
#' }
#' @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)
}

#' Plot the accidents on a map
#'
#' @description This function plots the accident data for the specified
#'   \code{state} in the specified \code{year}.
#'
#' @param state.num The number of a US state coerced to integer.
#' @param year An integer representing the year in the FARS dataset.
#'   Non-integers are coerced to integer.
#'
#' @return This function returns a plot of the accidents in a state map.
#'
#' @details Returns an error if there is no data for the specified \code{state}
#'   and \code{year}.
#'
#' @examples
#' \dontrun{
#' # Existing state, year pair
#' fars_map_state(1, 2013)
#'
#' # Non-existing state or year
#' fars_map_state(1, 2016)
#' fars_map_state(100, 2013)
#' }
#'
#' @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)
	})
}
Davidovich4/building.an.R.package documentation built on May 29, 2019, 2:08 p.m.