knitr::opts_chunk$set(echo = TRUE)
This is an R Markdown document. Which explin in detail about the Accident data example package. This package contain some data from the US National Highway Traffic Safety Administration's Fatality Analysis Reporting System https://www.nhtsa.gov/ and some functions for extrapolating and summarizing the data.
This package contain five functions which will be explained above.
Returns a character vector containing a formatted combination of the year of the data, which is needed, and the full filename.
make_filename <- function(year) { year <- as.integer(year) sprintf("accident_%d.csv.bz2", year) }
Takes a character vector, containing file name or path and load it.
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) }
Loads specified data about year and month.
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) }) }) }
Return the number of observations per month for a given year.
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) }
Function for plotting an states accidentes map for given a state & year
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.