R/source_script.R

#' Load csv data
#' This function checks whether data (in CSV format) exists in current woring directory, and if "yes",
#' loads it into workspace. The progress printed in console can be switched off by assigning
#' \code{progress = FALSE}.
#'
#' @param filename A character string with the name of csv file that is looked for in current directory.
#'
#' @return This function returns table if specified csv file exists in working directory.
#' Otherwise it stops and notifies that file does not exist.
#'
#' @examples
#' \dontrun{
#' data<-fars_read(filename="foo.csv")
#' data<-fars_read(filename="foo.csv", progress=FALSE)}
#'
#' @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)
}


#' File Naming
#' This function make character name using existing pattern and year, so final name for year=2012
#' becomes "accident_2012.csv.bz2 "
#'
#' @param year A parameter which identifies the value of year, used in built file name
#'
#' @return This function returns object of class "character" with the constructed file name
#'
#' @examples
#'  \dontrun{filename<-make_filename(year=2012)}
#'
#' @export
make_filename <- function(year) {
  year <- as.integer(year)
  sprintf("accident_%d.csv.bz2", year)
}



#' Only year based csv file loading
#' This file uses the only value of a year to import csv files having names, generated by \code{\link{make_filename}}
#' function. Then it  selects year and month from each imported files and store it an a list.
#'
#' @param years A parameter which identifies which years are used to search and read files
#' @inheritParams make_filename
#'
#' @return List of dataframes, where each data frame corresponds to initial .csv file and have two columns:
#' month and year is returned. In case of absence of the requested .csv file to import, list value for it is NULL
#' and warning message is produced.
#'
#' @examples \dontrun{
#' fars_read_years(years=c(2011,2012,2013))
#'  fars_read_years(years=seq(from=2011, to=2015))}
#'
#'
#' @importFrom magrittr %>%
#' @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)
      dplyr::mutate(dat, year = year) %>%
        dplyr::select(MONTH, year)
    }, error = function(e) {
      warning("invalid year: ", year)
      return(NULL)
    })
  })
}


#' Summarizig years
#' This function uses the  \code{\link{fars_read_years}} output (list, containing months and years data) as input to
#'  provide with summary information of how many observation occurs for each year.
#'
#' @inheritParams fars_read_years
#' @inheritParams make_filename
#'
#' @return Data frame with each subsisting years (from output list of \code{\link{fars_read_years}} )
#'  in columns and number of observation is returned by each  month (in rows).
#'
#' @examples \dontrun{
#' fars_summarize_years(years=c(2011,2012,2013))
#' fars_summarize_years(years=seq(from=2011, to=2015))}
#'
#' @importFrom magrittr %>%
#' @importFrom dplyr bind_rows
#' @importFrom dplyr group_by
#' @importFrom dplyr summarize
#' @importFrom tidyr spread
#'
#' @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)
}



#' Ploting map
#' This function uses names, generated by function make_filename to (in case of existense)
#'  import .csv files  by fars_read funnction.
#' With the specified state number all accidents are plotted on the map.
#'
#' @param state.num Integer, that identifies state to plot observations on a map
#' @inheritParams make_filename
#'
#' @return If specified state number is not presented in initial data, function stops with the corresponding message.
#' If there is such a state number in data, but there is no observations, nothing is plotted (with the printed message
#' about it) . Finally, if there are observations for specified state number, they are plotted on a map.
#'
#' @examples \dontrun{
#' fars_map_state(1, 2011)
#' fars_map_state(2, 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)
  })
}
Yailama/assignment4 documentation built on May 10, 2019, midnight