R/fars_function.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

# Comments and description done by Jeff Smith as part of the Building R Packages course on Coursera.


##### fars_read description section #####
# Code fars_read returns a data frame using data from the supplied csv file, if the name is correct.
# Using predetermined parameters, the function takes a file of a specific file name and brings it into R to be read.
# If this predetermined file name does not exist the function will stop and provide the user with a descriptive error.
# Functions used: read_csv from readr and tbl_df from dplyr.
#' @title fars_read
#' @param filename a character string
#'
#' @importFrom readr read_csv
#' @importFrom dplyr tbl_df
#'
#' @return the data in tbl_df format
#'
#' @examples
#' fars_read("data/accident_2013.csv")
#' fars_read(accident_2014.csv")
#'
#'  @export

fars_read <- function(filename) {
  # Function checks if the file name exists before anything else.
  if(!file.exists(filename))
    # If the file name does not exist, an error is given to notify the user.
    stop("file '", filename, "' does not exist")
  # Suppress any messages
  data <- suppressMessages({
    # The package being used is readr.
    # From readr, read_csv is used to import data from the csv file.
    readr::read_csv(filename, progress = FALSE)
    # Progress parameter is set to FALSE so a progress bar is not shown.
  })
  # The next package being used is dplyr.
  # Using that package, the argument is forwarded from the tibble package to as.data.frame
  # Finally, the data frame is returned so it can be reviewed.
  dplyr::tbl_df(data)
}


#' @title make_filename
#' @param year integer or string in YYYY format
#' @return The function returns a string with provided year input
#'
#' @examples
#' make_filename(2015)
#'
#' @examples
#'
#'

make_filename <- function(year) {
  year <- as.integer(year)
  sprintf("accident_%d.csv.bz2", year)
}


##### fars_read_years description section #####
# this function takes a vector of different years and iterates over them.
# filenames are created to read in and return with the month and year columns selected.

# This function will create a filename dependent on the year input.
# If the the file name does not exist, an error will be produced for the user.
# If the file name does exist, the function will try to read them in.
# Once read in, the function will mutate a new column in with the year and then select the columns MONTH and year.
#
#' @title fars_read_years
#' @param years either scalar or vector
#'
#' @return MONTH and year from the accident data based on the availability of provided year as a parameter
#'
#' @examples
#' fars_read_years(2013:2015)
#' fars_read_years(2016) # Throws an error
#'
#' @importFrom dplyr mutate select
#'
#' @export

fars_read_years <- function(years) {
  # Apply a function to run on each vector element.
  lapply(years, function(year) {
    # Build a file name by passing the year from the vector to make_filename.
    file <- make_filename(year)
    # Implement condition system with tryCatch
    tryCatch({
      # Read the file into the environment using fars_read (previously used function)
      dat <- fars_read(file)
      # Add another variable using the called year
      dplyr::mutate(dat, year = year) %>%
        # Select the month and year columns only.
        dplyr::select(MONTH, year)
      # Produces an error when year is missing to fill value with NULL
    }, error = function(e) {
      # Warning year
      warning("invalid year: ", year)
      # If error is produced, the return will be NULL.
      return(NULL)
    })
  })
}


##### fars_summarize_years description section #####
# This function is used to summarize the data produced during previous steps by year.
# Using previously read data, the dataframes are bound together and summarized.

# This function with take a vector containing years and read in the data using fars_summarize_years.
# It then binds the rows together by the year and MONTH columns. From there, a column called count is made.
# Once the data is compiled, it is converted from a Long format to a Wide format using the spread function from tidyr.

#' @title fars_summarize_years
#' @param years either scalar or vector
#'
#' @return MONTH and year from the accident data based on the availability of provided year as a parameter
#'
#' @examples
#' fars_read_years(2013:2015)
#' fars_read_years(2016) # Throws an error
#'
#' @export

# Example:
#         \dontrun{
#           fars_summarize_years(c(2013, 2014))
#         }


fars_summarize_years <- function(years) {
  # Use the vectors year in fars_read_years to read in the vector of data.
  dat_list <- fars_read_years(years)
  # Bind all rows together
  dplyr::bind_rows(dat_list) %>%
    # Group by the year and MONTH variables.
    dplyr::group_by(year, MONTH) %>%
    # Summarize the data. Add a column called n that will be the count column.
    dplyr::summarize(n = n()) %>%
    # Convert the data from long to wide format, as mentioned in the description.
    tidyr::spread(year, n)
}


##### fars_map_state description section #####
# The fars_map_state function plots the state given as an integer and plots accidents for a given year.

# The function will take a year and state and try to the accidents for a provided state number.
# If there is no data for a state, the function will stop and provide the user with an error.
# If there are no accidents for the chosen state, a message will be returned stating this,

#' @title fars_map_state
#' @param state.num number of state integer or string
#' @param year integer
#'
#' @return a plot with selected criteria
#'
#' @examples
#' fars_map_state(1, 2013)insta
# 1 represents the state number, while 2013 represents the chosen year.

fars_map_state <- function(state.num, year) {
  # pass the year to make_filename and assign the variable to filename
  filename <- make_filename(year)
  # load the filename data in using fars_read
  data <- fars_read(filename)
  # Attempt to coerce state.num to integer type
  state.num <- as.integer(state.num)
  # If state.num does not exist in the data column STATE:
  if(!(state.num %in% unique(data$STATE)))
    # Produce an error and notify the user.
    stop("invalid STATE number: ", state.num)
  # Assign a variable to data.subset that is the data variable filtered for the state.num function
  data.sub <- dplyr::filter(data, STATE == state.num)
  # If there are no rows then message the user there are no accidents for this data
  if(nrow(data.sub) == 0L) {
    # Message
    message("no accidents to plot")
    # Produce a temporary invisible copy of NULL
    return(invisible(NULL))
  }
  # Deal with na values accordingly in the Longitude and Latitude columns.
  is.na(data.sub$LONGITUD) <- data.sub$LONGITUD > 900
  is.na(data.sub$LATITUDE) <- data.sub$LATITUDE > 90
  # Evaluate environment constructed from data
  with(data.sub, {
    # Draw lines and polygons as specified by the data.
    maps::map("state", ylim = range(LATITUDE, na.rm = TRUE),
              xlim = range(LONGITUD, na.rm = TRUE))
    # Draw points.
    graphics::points(LONGITUD, LATITUDE, pch = 46)
  })
}

# Done.
jeff-hardwoodsnb/Week4Fars documentation built on May 7, 2022, 12:07 a.m.