############# Building R Packages: Week 2 Assignment - Documentation with Roxygen2 ############
###############################################################################################
#' \code{fars_read} - a function to read in a Fatality Analysis Reporting System data file.
#' The expected format is CSV.
#'
#' @param filename an object of class \code{character}.The name of the file to be read.
#'
#' @return Returns a data frame tibble containing the file contents. If the file does not exist, the
#' function returns an error.
#'
#' @examples \dontrun{
#' fars_read('accident_2013.csv.bz2')
#' data <- fars_read('accident_2017.csv.bz2')
#' }
#'
#' @import dplyr maps tidyr readr
#'
#' @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)
}
#' \code{make_filename} - A function to create a FARS reporting system datafile name for a given year.
#' The function converts any input to integer before constructing the file name.
#'
#' @param year The year to include in the file name. Can be numeric, integer or a characterized version
#' of a numeric (e.g. "2003")
#'
#' @return Returns the full file name for the year specified as a character object.
#'
#' @examples \dontrun{
#' make_filename(2013)
#' first_file <- make_filename(2011)
#' }
#'
#' @export
make_filename <- function(year) {
year <- as.integer(year)
sprintf("accident_%d.csv.bz2", year)
}
#' \code{fars_read_years} - Reads in multiple files for FARS data according to user specified years.
#'
#' @details It uses the \code{fars_read} and \code{make_filename} functions, also from this package.
#' For each year, the function creates the proper filename, loads in the associated file, modifies
#' the column names and selects the month and year.
#'
#' @param years A vector or list of years.
#'
#' @return A list of tibbles containing the month and year variables for each year in the input list.
#'
#'
#' @examples \dontrun{
#' fars_read_years(c(2011,2012))
#' fars_read_years(list(2010,2001,2003))
#' }
#' @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)
})
})
}
#'
#' \code{fars_summarize_years} - Creates a summary of all fatalities by year, for each
#' year input by the user.
#'
#'
#' @param years A list or vector of years over which the summary is calculated.
#'
#' @return Returns a dataframe with the summaries of each year as separate columns.
#'
#' @details This function relies on the \code{fars_read_years} function to extract the variables
#' from the file associated with each year. It stacks these datasets together vertically, then
#' groups by year and calculates summaries, returning the result.
#'
#'
#' @examples \dontrun{
#' fars_summarize_years(c("2013","2015"))
#' summ_data <- fars_summarize_years(list(2014,2015,2016))
#' }
#'
#' @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)
}
#' \code{fars_map_state} - Maps a given state's fatalities for a given year using the \code{maps}
#' package. If the state number or year are invalid given the current data, the function returns
#' the appropriate error message.
#'
#' @param state.num The two-digit state code of the area the user wants to map. State codes start from
#' 01-51, and correspond to the alphabetical ordering of state names (e.g. 51 = Wyoming)
#'
#' @param year The year in which fatalities on the map will have occurred.
#'
#' @return Returns a map object showing the locations of the fatalities for the given state-year
#'
#' @details The function uses other functions from this package to construct, for the given year,
#' The appropriate file. It reads in that file, and converts the state number to an integer. Next,
#' It checks to confirm the state code is valid. The data are trimmed to exclude values above 90 LAT
#' or 900 Long (those are considered data collection errors, since coordinates are not defined past
#' those thresholds). Lastly, the \code{maps} package function \code{map} is used to map the coordinates.
#'
#' @examples \dontrun{
#' fars_map_state(04,2013)
#' fars_map_state(40,2014)
#' }
#' @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)
})
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.