├── .Rbuildignore ├── .github ├── .gitignore └── workflows │ ├── pkgdown.yaml │ └── test-coverage.yaml ├── .gitignore ├── CITATION.cff ├── DESCRIPTION ├── LICENSE ├── LICENSE.md ├── NAMESPACE ├── NEWS.md ├── R ├── crashapi-package.R ├── data.R ├── fars_vars.R ├── get_crss_zip.R ├── get_fars.R ├── get_fars_crash_persons.R ├── get_fars_crash_vehicles.R ├── get_fars_zip.R ├── sysdata.rda ├── tigris-utils.R └── utils.R ├── README.Rmd ├── README.md ├── _pkgdown.yml ├── codecov.yml ├── codemeta.json ├── crashapi.Rproj ├── data-raw ├── crash_data_index.R ├── fars.R └── mmucc_codes.R ├── data ├── crash_data_index.rda ├── fars_terms.rda ├── fars_vars_labels.rda └── mmucc_codes.rda ├── docs ├── 404.html ├── LICENSE-text.html ├── LICENSE.html ├── authors.html ├── deps │ ├── bootstrap-5.1.0 │ │ ├── bootstrap.bundle.min.js │ │ ├── bootstrap.bundle.min.js.map │ │ └── bootstrap.min.css │ ├── data-deps.txt │ └── jquery-3.6.0 │ │ ├── jquery-3.6.0.js │ │ ├── jquery-3.6.0.min.js │ │ └── jquery-3.6.0.min.map ├── index.html ├── link.svg ├── news │ └── index.html ├── pkgdown.js ├── pkgdown.yml ├── reference │ ├── crash_data_index.html │ ├── crashapi-package.html │ ├── fars_terms.html │ ├── fars_vars.html │ ├── fars_vars_labels.html │ ├── figures │ │ ├── README-get_fars_summary-1.png │ │ └── README-map_fars_crashes-1.png │ ├── format_crashes.html │ ├── get_fars.html │ ├── get_fars_crash_persons.html │ ├── get_fars_crash_vehicles.html │ ├── get_fars_zip.html │ ├── index.html │ ├── mmucc_codes.html │ └── read_crashapi.html ├── search.json └── sitemap.xml ├── inst └── extdata │ ├── crash_data_index.csv │ ├── fars_terms.csv │ ├── fars_vars_labels.csv │ └── mmucc_codes.csv ├── man ├── crash_data_index.Rd ├── crashapi-package.Rd ├── fars_terms.Rd ├── fars_vars.Rd ├── fars_vars_labels.Rd ├── figures │ ├── README-get_fars_summary-1.png │ └── README-map_fars_crashes-1.png ├── format_crashes.Rd ├── get_crss_zip.Rd ├── get_fars.Rd ├── get_fars_crash_persons.Rd ├── get_fars_crash_vehicles.Rd ├── get_fars_zip.Rd ├── list_rbind.Rd ├── mmucc_codes.Rd └── read_crashapi.Rd └── tests ├── testthat.R └── testthat ├── setup.R ├── test-fars_vars.R ├── test-get_fars.R ├── test-get_fars_crash_vehicles.R ├── test-get_fars_year.R ├── test-get_fars_zip.R └── test-tigris-utils.R /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^README\.Rmd$ 4 | ^_pkgdown\.yml$ 5 | ^docs$ 6 | ^pkgdown$ 7 | ^LICENSE\.md$ 8 | ^data-raw$ 9 | ^codecov\.yml$ 10 | ^\.github$ 11 | ^codemeta\.json$ 12 | ^CITATION\.cff$ 13 | -------------------------------------------------------------------------------- /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /.github/workflows/pkgdown.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | release: 9 | types: [published] 10 | workflow_dispatch: 11 | 12 | name: pkgdown 13 | 14 | jobs: 15 | pkgdown: 16 | runs-on: ubuntu-latest 17 | # Only restrict concurrency for non-PR jobs 18 | concurrency: 19 | group: pkgdown-${{ github.event_name != 'pull_request' || github.run_id }} 20 | env: 21 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 22 | steps: 23 | - uses: actions/checkout@v3 24 | 25 | - uses: r-lib/actions/setup-pandoc@v2 26 | 27 | - uses: r-lib/actions/setup-r@v2 28 | with: 29 | use-public-rspm: true 30 | 31 | - uses: r-lib/actions/setup-r-dependencies@v2 32 | with: 33 | extra-packages: any::pkgdown, local::. 34 | needs: website 35 | 36 | - name: Build site 37 | run: pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE) 38 | shell: Rscript {0} 39 | 40 | - name: Deploy to GitHub pages 🚀 41 | if: github.event_name != 'pull_request' 42 | uses: JamesIves/github-pages-deploy-action@v4.4.1 43 | with: 44 | clean: false 45 | branch: gh-pages 46 | folder: docs 47 | -------------------------------------------------------------------------------- /.github/workflows/test-coverage.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | 9 | name: test-coverage 10 | 11 | jobs: 12 | test-coverage: 13 | runs-on: ubuntu-latest 14 | env: 15 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | - uses: r-lib/actions/setup-r@v2 21 | with: 22 | use-public-rspm: true 23 | 24 | - uses: r-lib/actions/setup-r-dependencies@v2 25 | with: 26 | extra-packages: any::covr 27 | needs: coverage 28 | 29 | - name: Test coverage 30 | run: covr::codecov(quiet = FALSE) 31 | shell: Rscript {0} 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | .Rdata 6 | .httr-oauth 7 | .DS_Store 8 | inst/doc 9 | docs 10 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Type: Package 2 | Package: crashapi 3 | Title: CrashAPI 4 | Version: 0.1.2 5 | Authors@R: c( 6 | person("Eli", "Pousson", , "eli.pousson@gmail.com", role = c("aut", "cre"), 7 | comment = c(ORCID = "0000-0001-8280-1706")), 8 | person("Kyle", "Walker", , "kyle@walker-data.com", role = "cph", 9 | comment = "Author of tigris helper functions bundled with crashapi (see tigris-utils.R).") 10 | ) 11 | Description: Get Fatality Analysis Reporting System (FARS) data with the 12 | FARS API from the U.S. National Highway Traffic Safety Administration 13 | (NHTSA). 14 | License: MIT + file LICENSE 15 | URL: https://github.com/elipousson/crashapi, 16 | https://elipousson.github.io/crashapi/ 17 | BugReports: https://github.com/elipousson/crashapi/issues 18 | Depends: 19 | R (>= 2.10) 20 | Imports: 21 | cli, 22 | dplyr (>= 1.1.0), 23 | glue, 24 | httr2 (>= 0.2.3), 25 | janitor, 26 | rlang, 27 | stats, 28 | stringr, 29 | utils, 30 | vctrs 31 | Suggests: 32 | covr, 33 | httptest2, 34 | knitr, 35 | readr, 36 | rmarkdown, 37 | sf, 38 | testthat (>= 3.0.0) 39 | VignetteBuilder: 40 | knitr 41 | Config/testthat/edition: 3 42 | Config/testthat/parallel: true 43 | Encoding: UTF-8 44 | LazyData: true 45 | Roxygen: list(markdown = TRUE) 46 | RoxygenNote: 7.3.2 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | YEAR: 2021 2 | COPYRIGHT HOLDER: crashapi authors 3 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2021 crashapi authors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(fars_vars) 4 | export(format_crashes) 5 | export(get_crss_zip) 6 | export(get_fars) 7 | export(get_fars_cases) 8 | export(get_fars_crash_list) 9 | export(get_fars_crash_persons) 10 | export(get_fars_crash_vehicles) 11 | export(get_fars_crashes) 12 | export(get_fars_summary) 13 | export(get_fars_year) 14 | export(get_fars_zip) 15 | export(read_crashapi) 16 | importFrom(cli,cli_abort) 17 | importFrom(cli,cli_bullets) 18 | importFrom(cli,cli_progress_along) 19 | importFrom(cli,cli_warn) 20 | importFrom(dplyr,across) 21 | importFrom(dplyr,all_of) 22 | importFrom(dplyr,mutate) 23 | importFrom(glue,glue) 24 | importFrom(httr2,req_perform) 25 | importFrom(httr2,req_template) 26 | importFrom(httr2,request) 27 | importFrom(httr2,resp_body_json) 28 | importFrom(janitor,clean_names) 29 | importFrom(rlang,"%||%") 30 | importFrom(rlang,as_function) 31 | importFrom(rlang,caller_env) 32 | importFrom(rlang,check_dots_empty) 33 | importFrom(rlang,check_installed) 34 | importFrom(rlang,current_env) 35 | importFrom(rlang,global_env) 36 | importFrom(rlang,has_name) 37 | importFrom(rlang,zap) 38 | importFrom(stats,setNames) 39 | importFrom(stringr,str_pad) 40 | importFrom(stringr,str_to_sentence) 41 | importFrom(stringr,str_trim) 42 | importFrom(utils,URLencode) 43 | importFrom(utils,download.file) 44 | importFrom(utils,unzip) 45 | importFrom(vctrs,vec_rbind) 46 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # crashapi 0.1.2 4 | 5 | - Update year range to cover 2022 data. 6 | 7 | # crashapi 0.1.1.9 8 | 9 | - Update year range to cover 2021 data. 10 | - Add `get_crss_zip()` function 11 | 12 | # crashapi 0.1.1 13 | 14 | CrashAPI now has data from 2010 to 2020. `get_fars_year()` is also updated to support multiple years and to include a state parameter which makes it much easier to use. 15 | 16 | - refactor: update 2019 -> 2020 max year 17 | - feat: add geometry and state parameter support to `get_fars_year()` 18 | - refactor: set default crs to NULL and switch to use `sfext::df_to_sf` 19 | - refactor: switch to use `httr2` package + `read_crashapi()` for data access (except for zip) 20 | - test: add tests and set up code coverage tests 21 | 22 | # crashapi 0.1.0.12 23 | 24 | - feat: Add `get_fars_crash_persons()` function 25 | - refactor: Rename `tidy_crashes()` to `format_crashes()` 26 | - feat: rename `get_fars_crash_details()` to `get_fars_cases()` 27 | - feat: Add details parameter to `get_fars_crashes()` to supported appending detailed case information 28 | - feat: Add `fars_vars_labels` with names and labels derived from current analytical manual 29 | 30 | # crashapi 0.1.0.11 31 | 32 | - feat: add `get_fars()` function that uses an api parameter to call different APIs 33 | - feat: import helper functions from {tigris} package to improve renamed `lookup_fips()` function 34 | - feat: Add `get_fars_crash_vehicles` to support downloading crash data by vehicle make, model, and/or body type 35 | - fix: `get_fars_year` was not using the correct query URL if download = TRUE 36 | - refactor: relocate helper functions to utils.R 37 | - refactor: rename `make_query()` helper function to `read_api()` 38 | - refactor: update `validate_year()` helper function to work with {checkmate} package 39 | - refactor: update default values for year, start_year, end_year and other parameters 40 | - docs: Update README and pkgdown site 41 | 42 | # crashapi 0.1.0.10 43 | 44 | - feat: `get_fars_zip` added to provide alternate (non-API) method for downloading zipped CSV or SAS data files 45 | - fix: `get_fars_crash_details` updated to return data frame w/o list columns 46 | - feat: `get_fars_crash_details` updated to optionally return vehicle or crash events data frames 47 | 48 | # crashapi 0.1.0.9 49 | 50 | - docs: Revise README and update pkgdown site 51 | - fix: Add missing imports to `DESCRIPTION` 52 | - fix: Update `county_to_fips()` to support partial county names, e.g. "Adams" instead of "Adams County" and avoiding matching multiple counties (closes [#1](https://github.com/elipousson/crashapi/issues/1)) 53 | - feat: Update `get_fars_crash_details()` to return sf objects using geometry parameter 54 | - refactor: Set up API calls w/ unexported utility function (`make_query`) 55 | 56 | # crashapi 0.1.0 57 | 58 | * Added functions for accessing FARS APIs including Get Crash List Information, Get Crash Details, Get Crashes By Location, Get Summary Counts, and Get FARS Data By Year (documented in `get_fars()`) 59 | * Added functions for accessing FARS APIs including Get Variables and Get Variable Attributes (documented in `get_fars_vars()`) 60 | * Added `fars_terms` data with terms and definitions from National Highway Traffic Safety Administration (NHTSA) website 61 | * Added a `NEWS.md` file to track changes to the package. 62 | * Set up a pkgdown website 63 | -------------------------------------------------------------------------------- /R/crashapi-package.R: -------------------------------------------------------------------------------- 1 | #' @keywords internal 2 | "_PACKAGE" 3 | 4 | ## usethis namespace: start 5 | #' @importFrom rlang %||% 6 | #' @importFrom rlang caller_env 7 | #' @importFrom cli cli_abort 8 | #' @importFrom cli cli_bullets 9 | ## usethis namespace: end 10 | NULL 11 | -------------------------------------------------------------------------------- /R/data.R: -------------------------------------------------------------------------------- 1 | #' NHSTA Terms and Definitions 2 | #' 3 | #' FARS-related terms defined by the National Highway Traffic 4 | #' Safety Administration based on ANSI D16.1-1996: Manual on Classification of 5 | #' Motor Vehicle Traffic Accidents. 6 | #' 7 | #' `r pkg_data_date("fars_terms", "added")` 8 | #' `r pkg_data_date("fars_terms", "updated")` 9 | #' 10 | #' @format A data frame with 66 rows and 2 variables: 11 | #' \describe{ 12 | #' \item{\code{term}}{character Term} 13 | #' \item{\code{definition}}{character Term definition} 14 | #' } 15 | #' @source \href{https://www-fars.nhtsa.dot.gov/Help/Terms.aspx}{NHTSA FARS Terms} 16 | "fars_terms" 17 | 18 | 19 | #' FARS variable names and labels 20 | #' 21 | #' A table of FARS table variable names extracted from the Fatality 22 | #' Analysis Reporting System (FARS) Analytical User's Manual, 1975-2019, 23 | #' documentation of the SAS format data files. 24 | #' 25 | #' `r pkg_data_date("fars_vars_labels", "added")` 26 | #' `r pkg_data_date("fars_vars_labels", "updated")` 27 | #' 28 | #' @format A data frame with 498 rows and 14 variables: 29 | #' \describe{ 30 | #' \item{\code{name}}{character Variable name} 31 | #' \item{\code{label}}{character Variable label} 32 | #' \item{\code{order}}{double Sort order} 33 | #' \item{\code{data_file}}{character SAS data file name} 34 | #' \item{\code{data_file_id}}{double SAS data file ID} 35 | #' \item{\code{file_id}}{character File ID} 36 | #' \item{\code{key}}{logical Indicator for key variables} 37 | #' \item{\code{location}}{double Location in SAS data file} 38 | #' \item{\code{mmuc_equivalent}}{logical Equivalent term in MMUC (placeholder)} 39 | #' \item{\code{discontinued}}{logical Indicator for discontinued variables} 40 | #' \item{\code{api_only}}{logical Indicator for variables only used by API} 41 | #' \item{\code{api}}{character Name(s) of corresponding CrashAPI service} 42 | #' \item{\code{name_var}}{logical Indicator for "NAME" variable returned by API} 43 | #' \item{\code{nm}}{Short version of the variable name} 44 | #' \item{\code{api_list_col}}{logical Indicator for list columns returned by API} 45 | #' } 46 | "fars_vars_labels" 47 | 48 | 49 | #' @title Model Minimum Uniform Crash Criteria (MMUCC) codes (simple) 50 | #' 51 | #' @description 52 | #' 53 | #' A collection of the 73 unique codes identified as simple codes: 54 | #' 55 | #' 56 | #' See the MMUCC Guideline Fifth Edition (2017) for more information: 57 | #' 58 | #' 59 | #' About MMUC from NHTSA: 60 | #' 61 | #' To encourage greater uniformity, the National Highway Traffic Safety 62 | #' Administration (NHTSA) and the Governors Highway Safety Association (GHSA) 63 | #' cooperatively developed a voluntary data collection guideline in 1998. The 64 | #' MMUCC guideline identifies a minimum set of motor vehicle crash data elements 65 | #' and their attributes that States should consider collecting and including in 66 | #' their State crash data system. 67 | #' 68 | #' The MMUCC 5th Edition is the result of an 18-month collaboration between 69 | #' NHTSA, the Federal Highway Administration (FHWA), the Federal Motor Carrier 70 | #' Safety Administration (FMCSA), the National Transportation Safety Board 71 | #' (NTSB), the GHSA, and subject matter experts from State DOTs, local law 72 | #' enforcement, emergency medical services, safety organizations, industry 73 | #' partners, and academia. The traffic records community and general public also 74 | #' contributed through external forums (Federal Register) and at the 2016 75 | #' Traffic Records Forum. 76 | #' 77 | #' - `r pkg_data_date("mmucc_codes", "added")` 78 | #' - `r pkg_data_date("mmucc_codes", "updated")` 79 | #' 80 | #' @format A data frame with 700 rows and 6 variables: 81 | #' \describe{ 82 | #' \item{\code{code}}{Attribute code} 83 | #' \item{\code{name}}{Attribute code name} 84 | #' \item{\code{type}}{Attribute code type} 85 | #' \item{\code{definition}}{Code definition} 86 | #' \item{\code{restriction_id}}{Restriction id number} 87 | #' \item{\code{restriction}}{Restriction value} 88 | #' } 89 | "mmucc_codes" 90 | 91 | 92 | #' U.S. vehicular crash data index (city, county, regional, and state) 93 | #' 94 | #' This index include identified data from cities, counties, or regional 95 | #' entities in 43 of 50 U.S. states. Statewide data sources are included from 33 96 | #' states. In 4 states (NE, OH, ME, and CT), the only identified statewide data 97 | #' sources allow limited access through a web-based public query form. In 1 98 | #' state (MN), data only available through restricted access mapping/query tool. 99 | #' Not all statewide data sources include all crashes (some include only 100 | #' cyclist/pedestrian crashes or fatal crashes) and the structure and format of 101 | #' the crash data provided varies considerably. 102 | #' 103 | #' This index was compiled by Eli Pousson between October 2021 and February 104 | #' 2022 with additional contributions from Mae Hanzlik. 105 | #' 106 | #' `r pkg_data_date("crash_data_index", "added")` 107 | #' `r pkg_data_date("crash_data_index", "updated")` 108 | #' 109 | #' Corrections, updates, or additional sources should be added to this public 110 | #' Google Sheet: 111 | #' 112 | #' 113 | #' @format A data frame with 75 rows and 22 variables: 114 | #' \describe{ 115 | #' \item{\code{name}}{Name of data set from provider.} 116 | #' \item{\code{level}}{Geographic scope/level (e.g. city, county, region, state, national)} 117 | #' \item{\code{city}}{City name} 118 | #' \item{\code{county}}{County name} 119 | #' \item{\code{region}}{logical COLUMN_DESCRIPTION} 120 | #' \item{\code{state_name}}{U.S. state name} 121 | #' \item{\code{state_abb}}{U.S. state abbreviation} 122 | #' \item{\code{info_url}}{Informational URL (e.g. informational page about file download options)} 123 | #' \item{\code{data_url}}{Data URL (e.g. direct link to ArcGIS FeatureServer layer)} 124 | #' \item{\code{format}}{Data format (e.g. Socrata, CKAN, ArcGIS MapServer, etc.)} 125 | #' \item{\code{statewide_yn}}{Yes for data with statewide geographic scope; NA for data from city, county, or regional level providers} 126 | #' \item{\code{batch_download_yn}}{Yes for data where batch download is possible} 127 | #' \item{\code{start_year}}{Earliest year for crashes in dataset} 128 | #' \item{\code{end_year}}{Latest year for crashes in dataset} 129 | #' \item{\code{publisher}}{Agency/organization responsible for publishing the data online} 130 | #' \item{\code{description}}{Description of the dataset from provider} 131 | #' \item{\code{bike_ped_only}}{Yes for data that only includes bike/ped involved crashes (common for Vision Zero programs)} 132 | #' \item{\code{rolling_window}}{Description of rolling time window if data is only available within a rolling window} 133 | #' \item{\code{fatal_severe_only}}{Yes for data that only includes fatal/severe crashes (common for Vision Zero programs)} 134 | #' \item{\code{date_note}}{Note on the dates for the crash data} 135 | #' \item{\code{updates}}{Information on update schedule if available} 136 | #' \item{\code{note}}{General notes} 137 | #' } 138 | "crash_data_index" 139 | -------------------------------------------------------------------------------- /R/fars_vars.R: -------------------------------------------------------------------------------- 1 | #' @title Get variables and variable attributes for the Fatality Analysis 2 | #' Reporting System (FARS) API 3 | #' @description By default, this function returns the returns the list of 4 | #' variables for the data year specified. If `vars` is "make", "model", or 5 | #' "bodytype", the function returns #' list of variable attributes for the 6 | #' specified variable name or attributes for make model and body type 7 | #' specified in the FARS dataset. 8 | #' @param year Case year. Year must be between 2010 and 2019. 9 | #' @param var Default NULL. Supported values are "make", "model", and 10 | #' "bodytype". Using the var parameter returns variable attributes for the 11 | #' specified variable name or attributes for make model and body type 12 | #' specified in the dataset. 13 | #' @param make Integer. Make ID number. Required to return variables for "model" 14 | #' and "bodytype". Get a list of make ID numbers using the "make" var for the 15 | #' selected year, e.g. `fars_vars(year = 2010, var = "make")`. 16 | #' @param model Integer. Model ID number. Required to return variables for 17 | #' "bodytype". Get a list of model ID numbers using the "model" var for the 18 | #' selected year with a valid make ID number, e.g. `fars_vars(year = 2010, var 19 | #' = "model", make = 37)` 20 | #' @rdname fars_vars 21 | #' @aliases get_vars 22 | #' @examples 23 | #' 24 | #' head(fars_vars(year = 2022, var = "make"), 5) 25 | #' 26 | #' head(fars_vars(year = 2022, var = "model", make = 12), 5) 27 | #' 28 | #' fars_vars(year = 2022, var = "bodytype", make = 12, model = 37) 29 | #' 30 | #' @export 31 | fars_vars <- function(year, var = NULL, make = NULL, model = NULL) { 32 | year <- validate_year(year, year_range = c(2010, 2022)) 33 | data <- "definitions" 34 | 35 | if (is.null(var)) { 36 | return( 37 | read_crashapi( 38 | data = data, 39 | type = "GetVariables", 40 | dataYear = year 41 | ) 42 | ) 43 | } 44 | 45 | var <- match.arg(var, c("make", "model", "bodytype")) 46 | 47 | switch(var, 48 | "make" = read_crashapi( 49 | data = data, 50 | type = "GetVariableAttributes", 51 | variable = "make", 52 | caseYear = year 53 | ), 54 | "model" = read_crashapi( 55 | data = data, 56 | type = "GetVariableAttributesForModel", 57 | variable = "model", 58 | make = make, 59 | caseYear = year 60 | ), 61 | "bodytype" = read_crashapi( 62 | data = data, 63 | type = "GetVariableAttributesForbodyType", 64 | variable = "bodytype", 65 | make = make, 66 | model = model 67 | ), 68 | ) 69 | } 70 | -------------------------------------------------------------------------------- /R/get_crss_zip.R: -------------------------------------------------------------------------------- 1 | #' Download CRSS data files as zipped CSV or SAS files 2 | #' 3 | #' This function is similar to [get_fars_zip()] to download files directly from 4 | #' NHTSA FTP site. If read is `TRUE`, the function reads a list containing data 5 | #' frames for each table available in the selected year. If geometry is `TRUE`, 6 | #' the accident table is converted to an sf object. 7 | #' 8 | #' @param year Year of data from 2016 to 2022, Default: 2022 9 | #' @param format Format of zipped data tables ('csv' or 'sas'). Default: 'csv'. 10 | #' unzip and geo options are only supported if format is "csv". 11 | #' @param aux If `TRUE`, download auxiliary 12 | #' CRSS datasets . 13 | #' @param read If `TRUE`, unzip the downloaded file and read CSV files into a 14 | #' list of tables with each list item corresponding to one CSV file. 15 | #' @param geometry If `TRUE`, convert the accident table to a sf object. 16 | #' @inheritParams get_fars_zip 17 | #' @return Downloads zip file with CSV or SAS tables and returns the zip file 18 | #' path invisibly or returns a list of data frames (if geo is `FALSE`), or 19 | #' returns a list of data frames with the accident table converted to a sf 20 | #' object. 21 | #' @rdname get_crss_zip 22 | #' @export 23 | #' @importFrom glue glue 24 | #' @importFrom cli cli_bullets cli_progress_along 25 | #' @importFrom utils unzip 26 | #' @importFrom rlang check_installed 27 | #' @importFrom stats setNames 28 | get_crss_zip <- function(year = 2022, 29 | format = "csv", 30 | path = NULL, 31 | aux = FALSE, 32 | read = TRUE, 33 | geometry = FALSE, 34 | overwrite = FALSE) { 35 | year <- validate_year(year = year, year_range = c(2016:2022)) 36 | format <- match.arg(format, c("csv", "sas")) 37 | 38 | auxiliary <- "" 39 | 40 | if (isTRUE(aux)) { 41 | auxiliary <- "Auxiliary" 42 | } 43 | 44 | filename <- glue::glue("CRSS{year}{auxiliary}{toupper(format)}.zip") 45 | 46 | url <- 47 | glue::glue( 48 | "https://static.nhtsa.gov/nhtsa/downloads/CRSS/{year}/{filename}" 49 | ) 50 | 51 | if (is.null(path)) { 52 | path <- getwd() 53 | } 54 | 55 | destfile <- file.path(path, filename) 56 | 57 | if (file.exists(destfile)) { 58 | if (isTRUE(overwrite)) { 59 | file.remove(destfile) 60 | } else { 61 | cli_bullets( 62 | c( 63 | ">" = "Reading existing {.file {filename}} at {.path {path}}.", 64 | "i" = "Set {.code overwrite = TRUE} to replace existing file." 65 | ) 66 | ) 67 | } 68 | } 69 | 70 | if (!file.exists(destfile)) { 71 | download.file( 72 | url = url, 73 | destfile = destfile, 74 | method = "auto" 75 | ) 76 | } 77 | 78 | if (!read) { 79 | return(invisible(destfile)) 80 | } 81 | 82 | exdir <- file.path(path, gsub("\\.zip$", "", filename)) 83 | 84 | utils::unzip( 85 | zipfile = destfile, 86 | exdir = exdir, 87 | overwrite = TRUE, 88 | list = FALSE 89 | ) 90 | 91 | files <- 92 | list.files( 93 | path = exdir, 94 | full.names = TRUE 95 | ) 96 | 97 | stopifnot(format == "csv") 98 | 99 | rlang::check_installed("readr") 100 | 101 | crash_tables <- 102 | stats::setNames( 103 | map( 104 | cli::cli_progress_along(files, "Reading data"), 105 | ~ readr::read_csv( 106 | file = files[.x], 107 | progress = FALSE, 108 | show_col_types = FALSE 109 | ) 110 | ), 111 | nm = tolower(gsub(".CSV", "", basename(files), ignore.case = TRUE)) 112 | ) 113 | 114 | if (geometry) { 115 | crash_tables[["accident"]] <- df_to_sf(crash_tables[["accident"]]) 116 | } 117 | 118 | crash_tables 119 | } 120 | -------------------------------------------------------------------------------- /R/get_fars_crash_persons.R: -------------------------------------------------------------------------------- 1 | #' Get Crashes By Occupant 2 | #' 3 | #' This function returns a list of fatal crashes by occupant that have occurred 4 | #' throughout United States. This function is not currently working. 5 | #' 6 | #' @rdname get_fars_crash_persons 7 | #' @inheritParams get_fars 8 | #' @param year numeric vector. Year or range with start and end year. 2010 to 9 | #' 2022 supported. 10 | #' @param state Required. State name, abbreviation, or FIPS number. 11 | #' @param age numeric 12 | #' @param sex Options "m", "f", "male", "female", "unknown", "not reported." 13 | #' @param seat Seat position 14 | #' @param injury Options "unknown", "not reported", "died prior", "injured", 15 | #' "fatal", "suspected serious", "suspected minor", "possible", "no apparent" 16 | #' @param occupants Include vehicle occupants in query; defaults to `TRUE` 17 | #' @param nonoccupants Include non-occupants in query; defaults to `TRUE` 18 | #' @export 19 | #' @importFrom glue glue 20 | get_fars_crash_persons <- function(year = NULL, 21 | start_year, 22 | end_year = NULL, 23 | state, 24 | age = NULL, 25 | sex = NULL, 26 | seat, 27 | injury, 28 | occupants = TRUE, 29 | nonoccupants = TRUE) { 30 | year <- validate_year(year, start_year = start_year, end_year = end_year) 31 | 32 | if (is.character(seat)) { 33 | front <- grepl("front", seat) 34 | second <- grepl("second", seat) 35 | third <- grepl("third", seat) 36 | fourth <- grepl("fourth", seat) 37 | 38 | left <- grepl("left", seat) 39 | middle <- grepl("middle", seat) 40 | right <- grepl("right", seat) 41 | other <- grepl("other", seat) 42 | } 43 | 44 | injury <- switch(tolower(injury), 45 | "unknown" = 9, 46 | "not reported" = 9, 47 | "died prior" = 6, 48 | "injured" = 5, 49 | "fatal" = 4, 50 | "suspected serious" = 3, 51 | "suspected minor" = 2, 52 | "possible" = 1, 53 | "no apparent" = 0 54 | ) 55 | 56 | sex <- switch(tolower(sex), 57 | "m" = 1, 58 | "male" = 1, 59 | "f" = 2, 60 | "female" = 2, 61 | "not reported" = 8, 62 | "unknown" = 9 63 | ) 64 | 65 | stopifnot( 66 | is.numeric(age), 67 | is.numeric(sex), 68 | is.numeric(seat), 69 | is.numeric(injury) 70 | ) 71 | 72 | read_crashapi( 73 | data = "crashes", 74 | type = "GetCrashesByPerson", 75 | age = as.integer(age), 76 | sex = sex, 77 | seatPos = as.integer(seat), 78 | injurySeverity = as.integer(injury), 79 | fromCaseYear = min(year), 80 | toCaseYear = max(year), 81 | state = lookup_fips(state), 82 | includeOccupants = tolower(occupants), 83 | includeNonOccupants = tolower(nonoccupants), 84 | format = "json" 85 | ) 86 | } 87 | -------------------------------------------------------------------------------- /R/get_fars_crash_vehicles.R: -------------------------------------------------------------------------------- 1 | #' @rdname get_fars_crash_vehicles 2 | #' @title Get Crashes By Vehicle 3 | #' @description This function returns a list of fatal crashes by vehicle type 4 | #' that have occurred throughout United States. The make, model, and body type 5 | #' must match the options returned by `fars_vars`. This function accepts named 6 | #' options that are converted to ID numbers for use in the API query. 7 | #' 8 | #' @inheritParams get_fars 9 | #' @param year numeric vector. Year or range with start and end year. 2010 to 10 | #' 2022 supported. 11 | #' @param state Required. State name, abbreviation, or FIPS number. 12 | #' @param make Make name or ID, Required. The start_year is used to return a 13 | #' list of support make options. Default: `NULL` 14 | #' @param model Model name or ID, Optional. Default: `NULL` 15 | #' @param model_year Model year, Optional. Default: `NULL` 16 | #' @param body_type Body type, Optional. `model` must be provided to use 17 | #' body_type parameter. Default: `NULL` 18 | #' @export 19 | #' @importFrom glue glue 20 | get_fars_crash_vehicles <- function(year = NULL, 21 | start_year, 22 | end_year = NULL, 23 | state, 24 | make = NULL, 25 | model = NULL, 26 | model_year = 2010, 27 | body_type = NULL) { 28 | year <- validate_year(year, start_year = start_year, end_year = end_year) 29 | state_fips <- lookup_fips(state) 30 | 31 | make_options <- fars_vars(year = min(year), var = "make") 32 | 33 | if (make %in% make_options$TEXT) { 34 | make <- make_options[make_options$TEXT == make, ]$ID 35 | } 36 | 37 | make <- match.arg(make, make_options$ID) 38 | 39 | if (!is.null(model)) { 40 | model_options <- fars_vars(year = model_year, make = make, var = "model") 41 | 42 | if (model %in% model_options$MODELNAME) { 43 | model <- 44 | as.character(model_options[model_options$MODELNAME == model, ]$ID) 45 | } 46 | 47 | model <- match.arg(as.character(model), as.character(model_options$ID)) 48 | 49 | if (!is.null(body_type)) { 50 | body_type_options <- 51 | fars_vars( 52 | year = model_year, 53 | make = make, 54 | model = model, 55 | var = "bodytype" 56 | ) 57 | 58 | if (body_type %in% body_type_options$BODY_DEF) { 59 | body_type <- 60 | as.character( 61 | body_type_options[body_type_options$BODY_DEF == body_type, ]$BODY_ID 62 | ) 63 | } 64 | 65 | body_type <- match.arg(body_type, body_type_options$BODY_ID) 66 | } 67 | } 68 | 69 | read_crashapi( 70 | data = "crashes", 71 | type = "GetCrashesByVehicle", 72 | make = make, 73 | bodyType = body_type, 74 | model = model, 75 | modelyear = model_year, 76 | fromCaseYear = min(year), 77 | toCaseYear = max(year), 78 | state = state_fips, 79 | format = "json", 80 | results = TRUE 81 | ) 82 | } 83 | -------------------------------------------------------------------------------- /R/get_fars_zip.R: -------------------------------------------------------------------------------- 1 | #' Download FARS data files as zipped CSV or SAS files 2 | #' 3 | #' This function provides an alternative to [get_fars_year()] that downloads 4 | #' files directly from NHTSA FTP site. If read is `TRUE`, the function reads a 5 | #' list containing data frames for each table available in the selected year. If 6 | #' geometry is `TRUE`, the accident table is converted to an sf object. 7 | #' 8 | #' @param year Year of data from 1975 to 2022, Default: 2022 9 | #' @param format Format of zipped data tables ('csv' or 'sas'). Default: 'csv'. 10 | #' unzip and geo options are only supported if format is "csv". 11 | #' @param path Path to download zip file. Set to [getwd()] if `NULL` (default). 12 | #' @param pr If `TRUE`, download FARS data for Puerto Rico. No Puerto Rico data 13 | #' available for years 1975-1977. Default: `FALSE` 14 | #' @param aux If `TRUE` and year is after 1982, download auxiliary 15 | #' FARS datasets that "contain data derived from the regular FARS/GES 16 | #' variables using NCSA analytical data classifications." In 2010, the NHTSA 17 | #' explained: "These classifications are widely used in NCSA publications and 18 | #' research. Many definitions such as "speeding-related" or "distracted 19 | #' driving" comprise a combination of variables whose names or attributes have 20 | #' changed over time. The derived variables in the auxiliary files incorporate 21 | #' these nuances, thus simplifying the use of standard classifications in any 22 | #' traffic safety research." Learn more from the FARS and GES Auxiliary 23 | #' Datasets Q & A: 24 | #' 25 | #' @param read If `TRUE`, unzip the downloaded file and read CSV files into a 26 | #' list of tables with each list item corresponding to one CSV file. 27 | #' @param geometry If `TRUE`, convert the accident table to a sf object. 28 | #' @param overwrite If `FALSE`, abort if file exists at the provided path. If 29 | #' `TRUE`, overwrite file. 30 | #' @return Downloads zip file with CSV or SAS tables and returns the zip file 31 | #' path invisibly or returns a list of data frames (if geometry is `FALSE`), 32 | #' or returns a list of data frames with the accident table converted to a sf 33 | #' object. 34 | #' @rdname get_fars_zip 35 | #' @export 36 | #' @importFrom utils URLencode unzip 37 | #' @importFrom glue glue 38 | #' @importFrom cli cli_bullets cli_progress_along 39 | #' @importFrom rlang check_installed 40 | #' @importFrom stats setNames 41 | get_fars_zip <- function(year = 2022, 42 | format = "csv", 43 | path = NULL, 44 | pr = FALSE, 45 | aux = FALSE, 46 | read = TRUE, 47 | geometry = FALSE, 48 | overwrite = FALSE) { 49 | year <- validate_year(year = year, year_range = c(1975:2021)) 50 | format <- match.arg(format, c("csv", "sas")) 51 | scope <- "National" 52 | 53 | if (pr) { 54 | scope <- utils::URLencode("Puerto Rico") 55 | } 56 | 57 | auxiliary <- "" 58 | 59 | if (isTRUE(aux)) { 60 | if (year < 1982) { 61 | cli_warn( 62 | c("Auxiliary data (when {.code aux = TRUE}) is only available for years 63 | after 1982.", 64 | "i" = "Returning non-auxiliary data only." 65 | ) 66 | ) 67 | } else { 68 | auxiliary <- "Auxiliary" 69 | } 70 | } 71 | 72 | filename <- glue::glue("FARS{year}{scope}{auxiliary}{toupper(format)}.zip") 73 | 74 | url <- 75 | glue::glue( 76 | "https://static.nhtsa.gov/nhtsa/downloads/FARS/{year}/{scope}/{filename}" 77 | ) 78 | 79 | if (is.null(path)) { 80 | path <- getwd() 81 | } 82 | 83 | destfile <- file.path(path, filename) 84 | 85 | if (file.exists(destfile)) { 86 | if (isTRUE(overwrite)) { 87 | file.remove(destfile) 88 | } else { 89 | cli_bullets( 90 | c( 91 | ">" = "Reading existing {.file {filename}} at {.path {path}}.", 92 | "i" = "Set {.code overwrite = TRUE} to overwrite existing file." 93 | ) 94 | ) 95 | } 96 | } 97 | 98 | if (!file.exists(destfile)) { 99 | download.file( 100 | url = url, 101 | destfile = destfile, 102 | method = "auto" 103 | ) 104 | } 105 | 106 | if (!read) { 107 | return(invisible(destfile)) 108 | } 109 | 110 | exdir <- 111 | file.path(path, gsub("\\.zip$", "", filename)) 112 | 113 | utils::unzip( 114 | zipfile = destfile, 115 | exdir = exdir, 116 | overwrite = TRUE, 117 | list = FALSE 118 | ) 119 | 120 | files <- 121 | list.files( 122 | path = exdir, 123 | full.names = TRUE 124 | ) 125 | 126 | stopifnot(format == "csv") 127 | 128 | rlang::check_installed("readr") 129 | 130 | crash_tables <- 131 | stats::setNames( 132 | map( 133 | cli::cli_progress_along(files, "Reading data"), 134 | ~ readr::read_csv( 135 | file = files[.x], 136 | progress = FALSE, 137 | show_col_types = FALSE 138 | ) 139 | ), 140 | nm = tolower(gsub(".CSV", "", basename(files), ignore.case = TRUE)) 141 | ) 142 | 143 | if (geometry) { 144 | crash_tables[["accident"]] <- df_to_sf(crash_tables[["accident"]]) 145 | } 146 | 147 | crash_tables 148 | } 149 | -------------------------------------------------------------------------------- /R/sysdata.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/R/sysdata.rda -------------------------------------------------------------------------------- /R/tigris-utils.R: -------------------------------------------------------------------------------- 1 | # Import unexported functions from tigris to support lookup_fips utility function 2 | # https://github.com/walkerke/tigris/blob/acbd0cf29f86aa90ab1ee339905f3fd6f26c1ed6/R/utils.R 3 | 4 | # These functions use a compatable MIT license and have been cited as consistent 5 | # with the guidelines here: https://r-pkgs.org/license.html#how-to-include 6 | # via: http://www.epa.gov/envirofw/html/codes/state.html 7 | # 8 | # this somewhat duplicates "state_codes" but it's primarily intended 9 | # to validate_state. A TODO might be to refactor the code to eliminate this 10 | # but put "state_codes" to all lowercase for utility functions and then 11 | # use string transformations when presenting messages to the user 12 | 13 | fips_state_table <- structure( 14 | list(abb = c( 15 | "ak", "al", "ar", "as", "az", "ca", "co", 16 | "ct", "dc", "de", "fl", "ga", "gu", "hi", "ia", "id", "il", "in", 17 | "ks", "ky", "la", "ma", "md", "me", "mi", "mn", "mo", "ms", "mt", 18 | "nc", "nd", "ne", "nh", "nj", "nm", "nv", "ny", "oh", "ok", "or", 19 | "pa", "pr", "ri", "sc", "sd", "tn", "tx", "ut", "va", "vi", "vt", 20 | "wa", "wi", "wv", "wy", "mp" 21 | ), fips = c( 22 | "02", "01", "05", "60", "04", 23 | "06", "08", "09", "11", "10", "12", "13", "66", "15", "19", "16", 24 | "17", "18", "20", "21", "22", "25", "24", "23", "26", "27", "29", 25 | "28", "30", "37", "38", "31", "33", "34", "35", "32", "36", "39", 26 | "40", "41", "42", "72", "44", "45", "46", "47", "48", "49", "51", 27 | "78", "50", "53", "55", "54", "56", "69" 28 | ), name = c( 29 | "alaska", "alabama", 30 | "arkansas", "american samoa", "arizona", "california", "colorado", 31 | "connecticut", "district of columbia", "delaware", "florida", 32 | "georgia", "guam", "hawaii", "iowa", "idaho", "illinois", "indiana", 33 | "kansas", "kentucky", "louisiana", "massachusetts", "maryland", 34 | "maine", "michigan", "minnesota", "missouri", "mississippi", 35 | "montana", "north carolina", "north dakota", "nebraska", "new hampshire", 36 | "new jersey", "new mexico", "nevada", "new york", "ohio", "oklahoma", 37 | "oregon", "pennsylvania", "puerto rico", "rhode island", "south carolina", 38 | "south dakota", "tennessee", "texas", "utah", "virginia", "virgin islands", 39 | "vermont", "washington", "wisconsin", "west virginia", "wyoming", 40 | "northern mariana islands" 41 | )), 42 | .Names = c("abb", "fips", "name"), 43 | row.names = c(NA, -56L), 44 | class = "data.frame" 45 | ) 46 | 47 | # Called to check to see if "state" is a FIPS code, full name or abbreviation. 48 | # 49 | # returns `NULL` if input is `NULL` 50 | # returns valid state FIPS code if input is even pseud-valid (i.e. single digit 51 | # but w/in range) 52 | # returns `NULL` if input is not a valid FIPS code 53 | #' @noRd 54 | #' @importFrom stringr str_trim 55 | validate_state <- function(state, .msg = interactive()) { 56 | if (is.null(state)) { 57 | return(NULL) 58 | } 59 | 60 | state <- tolower(stringr::str_trim(state)) # forgive white space 61 | 62 | if (grepl("^[[:digit:]]+$", state)) { 63 | # we prbly have FIPS 64 | 65 | state <- sprintf("%02d", as.numeric(state)) # forgive 1-digit FIPS codes 66 | 67 | if (state %in% fips_state_table$fips) { 68 | return(state) 69 | } else { 70 | # perhaps they passed in a county FIPS by accident so forgive that, too, 71 | # but warn the caller 72 | state_sub <- substr(state, 1, 2) 73 | if (state_sub %in% fips_state_table$fips) { 74 | message( 75 | sprintf( 76 | "Using first two digits of %s - '%s' (%s) - for FIPS code.", 77 | state, state_sub, 78 | fips_state_table[fips_state_table$fips == state_sub, "name"] 79 | ), 80 | call. = FALSE 81 | ) 82 | return(state_sub) 83 | } else { 84 | cli::cli_warn( 85 | "{.arg state} ({.val state}) is not a valid FIPS code or 86 | state name/abbreviation." 87 | ) 88 | return(invisible(NULL)) 89 | } 90 | } 91 | } else if (grepl("^[[:alpha:]]+", state)) { 92 | # we might have state abbrev or name 93 | 94 | if (nchar(state) == 2 & state %in% fips_state_table$abb) { 95 | # yay, an abbrev! 96 | 97 | if (.msg) { 98 | message(sprintf( 99 | "Using FIPS code '%s' for state '%s'", 100 | fips_state_table[fips_state_table$abb == state, "fips"], 101 | toupper(state) 102 | )) 103 | } 104 | return(fips_state_table[fips_state_table$abb == state, "fips"]) 105 | } else if (nchar(state) > 2 & state %in% fips_state_table$name) { 106 | # yay, a name! 107 | 108 | if (.msg) { 109 | message(sprintf( 110 | "Using FIPS code '%s' for state '%s'", 111 | fips_state_table[fips_state_table$name == state, "fips"], 112 | simpleCapSO(state) 113 | )) 114 | } 115 | return(fips_state_table[fips_state_table$name == state, "fips"]) 116 | } else { 117 | cli::cli_warn( 118 | "{.arg state} ({.val state}) is not a valid FIPS code or 119 | state name/abbreviation." 120 | ) 121 | return(NULL) 122 | } 123 | } else { 124 | cli::cli_warn( 125 | "{.arg state} ({.val state}) is not a valid FIPS code or 126 | state name/abbreviation." 127 | ) 128 | return(NULL) 129 | } 130 | } 131 | 132 | # Some work on a validate_county function 133 | # 134 | # 135 | validate_county <- function(state, county, .msg = interactive()) { 136 | if (is.null(state)) { 137 | return(NULL) 138 | } 139 | 140 | if (is.null(county)) { 141 | return(NULL) 142 | } 143 | 144 | # Get the state of the county 145 | state <- validate_state(state, .msg = .msg) 146 | 147 | # Get a df for the requested state to work with 148 | county_table <- fips_codes[fips_codes$state_code == state, ] 149 | if (grepl("^[[:digit:]]+$", county)) { 150 | # if probably a FIPS code 151 | 152 | # in case they passed in 1 or 2 digit county codes 153 | county <- sprintf("%03d", as.numeric(county)) 154 | 155 | if (county %in% county_table$county_code) { 156 | return(county) 157 | } else { 158 | warning( 159 | sprintf( 160 | "'%s' is not a valid FIPS code for counties in %s", 161 | county, county_table$state_name[1] 162 | ), 163 | call. = FALSE 164 | ) 165 | return(NULL) 166 | } 167 | } else if ((grepl("^[[:alpha:]]+", county))) { 168 | # should be a county name 169 | 170 | county_index <- grepl(sprintf("^%s", county), 171 | county_table$county, 172 | ignore.case = TRUE 173 | ) 174 | 175 | matching_counties <- county_table$county[county_index] # Get the counties that match 176 | 177 | if (length(matching_counties) == 0) { 178 | warning( 179 | sprintf( 180 | "'%s' is not a valid name for counties in %s", 181 | county, county_table$state_name[1] 182 | ), 183 | call. = FALSE 184 | ) 185 | return(NULL) 186 | } else if (length(matching_counties) == 1) { 187 | if (.msg) { 188 | message(sprintf( 189 | "Using FIPS code '%s' for '%s'", 190 | county_table[county_table$county == matching_counties, "county_code"], 191 | matching_counties 192 | )) 193 | } 194 | 195 | return( 196 | county_table[county_table$county == matching_counties, "county_code"] 197 | ) 198 | } else if (length(matching_counties) > 1) { 199 | ctys <- format_vec(matching_counties) 200 | 201 | warning(paste0( 202 | "Your county string matches ", ctys, 203 | " Please refine your selection." 204 | ), call. = FALSE) 205 | return(NULL) 206 | } 207 | } 208 | } 209 | 210 | 211 | 212 | # Quick function to return formatted string for county codes 213 | 214 | format_vec <- function(vec) { 215 | out <- paste0(vec, ", ") 216 | 217 | l <- length(out) 218 | 219 | out[l - 1] <- paste0(out[l - 1], "and ") 220 | 221 | out[l] <- gsub(", ", ".", out[l]) 222 | 223 | return(paste0(out, collapse = "")) 224 | } 225 | 226 | # Function from SO to do proper capitalization 227 | 228 | simpleCapSO <- function(x) { 229 | s <- strsplit(x, " ")[[1]] 230 | paste(toupper(substring(s, 1, 1)), substring(s, 2), 231 | sep = "", collapse = " " 232 | ) 233 | } 234 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: github_document 3 | --- 4 | 5 | 6 | 7 | ```{r, include = FALSE} 8 | knitr::opts_chunk$set( 9 | collapse = TRUE, 10 | comment = "#>", 11 | fig.path = "man/figures/README-", 12 | out.width = "100%" 13 | ) 14 | ``` 15 | 16 | # crashapi 17 | 18 | 19 | [![CRAN status](https://www.r-pkg.org/badges/version/crashapi)](https://CRAN.R-project.org/package=crashapi) 20 | [![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental) 21 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 22 | [![Codecov test coverage](https://codecov.io/gh/elipousson/crashapi/branch/main/graph/badge.svg)](https://app.codecov.io/gh/elipousson/crashapi?branch=main) 23 | [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) 24 | 25 | 26 | The goal of the crashapi R package is to provide functions for downloading data from the National Highway Traffic Safety Administration (NHTSA) [Fatality Analysis Reporting System (FARS) API](https://crashviewer.nhtsa.dot.gov/CrashAPI/). 27 | 28 | What is FARS? NHTSA explains: "The Fatality Analysis Reporting System (FARS) contains data on all vehicle crashes in the United States that occur on a public roadway and involve a fatality." 29 | 30 | ## Installation 31 | 32 | You can install the development version of crashapi using the pak package: 33 | 34 | ``` r 35 | pak::pkg_install("elipousson/crashapi") 36 | ``` 37 | 38 | ## Background 39 | 40 | ### Fatality Analysis Reporting System (FARS) API support 41 | 42 | Supported APIs for this package include: 43 | 44 | - [x] Get Crash List Information 45 | - [X] Get Crash Details 46 | - [x] Get Crashes By Location 47 | - [X] Get Crashes By Vehicle 48 | - [x] Get Summary Counts 49 | - [x] Get Variables and Get Variable Attributes 50 | - [x] Get FARS Data By Year 51 | - [X] Get Crashes By Occupant (partial support) 52 | 53 | Most of these APIs support XML, JSV, CSV, and JSON output formats. This package only uses JSON with the exception of `get_fars_year()` (which supports downloading CSV files). 54 | 55 | For reference, this package also includes a list of terms and NHTSA technical definitions in `fars_terms` and a list of variable labels in `fars_vars_labels`. 56 | 57 | The FARS API currently provides access to data from 2010 to 2022. The [NHTSA website](https://www-fars.nhtsa.dot.gov/Help/helplinks.aspx) also provides additional information on the release data and version status for the FARS data files available through the API: 58 | 59 | | Data Year | File Version | Release Date | 60 | |-----------|--------------|-------------------| 61 | | 2010 | Final | December 11, 2012 | 62 | | 2011 | Final | November 13, 2013 | 63 | | 2012 | Final | December 12, 2013 | 64 | | 2013 | Final | December 14, 2014 | 65 | | 2014 | Final | December 18, 2015 | 66 | | 2015 | Final | December 16, 2016 | 67 | | 2016 | Final | December 14, 2017 | 68 | | 2017 | Final | December 18, 2018 | 69 | | 2018 | Final | June 24, 2021 | 70 | | 2019 | Final | March 2, 2022 | 71 | | 2020 | Final | April 3, 2023 | 72 | | 2021 | Final | August 19, 2024 | 73 | | 2022 | Annual | August 19, 2024 | 74 | 75 | 76 | ### Additional data access functionality 77 | 78 | The `get_fars_zip()` function can be used to access FARS data files from 1975 to 2020 that that are not available via the API but are available for download on through [the NHTSA File Downloads site](https://www.nhtsa.gov/file-downloads?p=nhtsa/downloads/FARS/) as zipped CSV or SAS files (not available through the NHTSA FARS API). This site also provides extensive technical documentation on coding and use of the FARS data files. 79 | 80 | Earlier data along with data from the the [General Estimates System](https://www.nhtsa.gov/national-automotive-sampling-system-nass/nass-general-estimates-system) (GES) / [Crash Report Sampling System](https://www.nhtsa.gov/crash-data-systems/crash-report-sampling-system-crss) (CRSS) is also available through the [Fatality and Injury Reporting System Tool](https://cdan.dot.gov/query) (FIRST). 81 | 82 | ## Examples 83 | 84 | ```{r} 85 | library(crashapi) 86 | library(ggplot2) 87 | ``` 88 | 89 | Most features for the package can be accessed using the `get_fars()` function that selects the appropriate API-specific function based on the provided parameters. You can also set the API to use with the `api` parameter or use an API-specific function (e.g. `get_fars_summary()`). 90 | 91 | For example, you can use the `get_fars()` access state-level summary data on crash and fatality counts. 92 | 93 | ```{r get_fars_summary} 94 | # Get summary crash count and fatality count data for Maryland from 2010 to 2019 95 | md_summary <- 96 | get_fars( 97 | year = c(2010, 2021), 98 | state = "MD", 99 | api = "summary count" 100 | ) 101 | 102 | ggplot(md_summary, aes(x = CaseYear, y = TotalFatalCounts)) + 103 | geom_point(color = "red") + 104 | geom_line(color = "red", group = 1) + 105 | theme_minimal() 106 | ``` 107 | 108 | You can download crash data and set geometry to TRUE optionally convert the data frame into an `sf` object for mapping. 109 | 110 | ```{r map_fars_crashes} 111 | crashes_sf <- 112 | get_fars( 113 | year = c(2018, 2021), 114 | state = "NC", 115 | county = "Wake County", 116 | geometry = TRUE 117 | ) 118 | 119 | nc <- sf::st_read(system.file("shape/nc.shp", package = "sf")) 120 | wake_co <- sf::st_transform(nc[nc$NAME == "Wake", ], 4326) 121 | 122 | # Map crashes 123 | ggplot() + 124 | geom_sf( 125 | data = wake_co, 126 | fill = NA, color = "black" 127 | ) + 128 | geom_sf( 129 | data = sf::st_crop(crashes_sf, wake_co), 130 | aes(color = TOTALVEHICLES), 131 | alpha = 0.75 132 | ) + 133 | theme_void() 134 | ``` 135 | 136 | You can list crashes and filter by the number of vehicles involved. 137 | 138 | ```{r get_fars_crash_list} 139 | # Get fatal crashes in New York state from 2019 with 5 to 10 vehicles 140 | get_fars( 141 | year = 2019, 142 | state = "NY", 143 | vehicles = c(5, 10) 144 | ) 145 | ``` 146 | 147 | If you call `get_fars()` or `get_fars_crashes()` with details set to TRUE, additional information from `get_fars_cases()` (including the crash date and time) is appended to the crash data frame. 148 | 149 | ```{r get_fars_crashes} 150 | # Get fatal crashes for Anne Arundel County, MD for 2019 and append details 151 | crashes_detailed <- 152 | get_fars( 153 | year = 2019, 154 | state = "MD", 155 | county = "Anne Arundel County", 156 | details = TRUE 157 | ) 158 | 159 | # Show 10 fatal crashes at random 160 | dplyr::slice_sample(crashes_detailed, n = 10) 161 | ``` 162 | 163 | ## Related packages and projects 164 | 165 | - [rfars](https://github.com/s87jackson/rfars) aims to "simplify the process of analyzing FARS data" by providing access to FARS downloads and preprocessed data back to 2015. 166 | - [stats19](https://github.com/ropensci/stats19) "provides functions for downloading and formatting road crash data" from "the UK's official road traffic casualty database, STATS19." 167 | - [njtr1](https://github.com/gavinrozzi/njtr1): "An R interface to New Jersey traffic crash data reported on form NJTR-1." 168 | - [wisdotcrashdatabase](https://github.com/jacciz/wisdotcrashdatabase): "A package used for internal WisDOT crash database pulls and analysis." 169 | - [nzcrash](https://github.com/nacnudus/nzcrash): "An R package to distribute New Zealand crash data in a convenient form." 170 | - [GraphHopper Open Traffic Collection](https://github.com/graphhopper/open-traffic-collection): "Collections of URLs pointing to traffic information portals which contain open data or at least data which is free to use." 171 | - [Open Crash Data Index](https://docs.google.com/spreadsheets/d/1rmn6GbHNkfWLLDEEmA87iuy2yHdh7hBybCTZiQJEY0k/edit?usp=sharing): A Google Sheet listing a range of city, county, regional and state sources for crash data including non-injury crashes as well as the fatal crashes available through the FARS API. Contributions for crash data from other U.S. cities and states are welcome. 172 | -------------------------------------------------------------------------------- /_pkgdown.yml: -------------------------------------------------------------------------------- 1 | url: https://elipousson.github.io/crashapi/ 2 | template: 3 | bootstrap: 5 4 | reference: 5 | - title: Get data from the FARS API 6 | contents: 7 | - starts_with("get") 8 | - read_crashapi 9 | - title: Get variable definitions 10 | contents: fars_vars 11 | - title: Data formatting functions 12 | contents: starts_with("format") 13 | - title: Reference information 14 | contents: 15 | - fars_terms 16 | - fars_vars_labels 17 | - mmucc_codes 18 | - crash_data_index 19 | 20 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | comment: false 2 | 3 | coverage: 4 | status: 5 | project: 6 | default: 7 | target: auto 8 | threshold: 1% 9 | informational: true 10 | patch: 11 | default: 12 | target: auto 13 | threshold: 1% 14 | informational: true 15 | -------------------------------------------------------------------------------- /codemeta.json: -------------------------------------------------------------------------------- 1 | { 2 | "@context": "https://doi.org/10.5063/schema/codemeta-2.0", 3 | "@type": "SoftwareSourceCode", 4 | "identifier": "crashapi", 5 | "description": "Get Fatality Analysis Reporting System (FARS) data with the FARS API from the U.S. National Highway Traffic Safety Administration (NHTSA).", 6 | "name": "crashapi: CrashAPI", 7 | "relatedLink": "https://elipousson.github.io/crashapi/", 8 | "codeRepository": "https://github.com/elipousson/crashapi", 9 | "issueTracker": "https://github.com/elipousson/crashapi/issues", 10 | "license": "https://spdx.org/licenses/MIT", 11 | "version": "0.1.1", 12 | "programmingLanguage": { 13 | "@type": "ComputerLanguage", 14 | "name": "R", 15 | "url": "https://r-project.org" 16 | }, 17 | "runtimePlatform": "R version 4.2.3 (2023-03-15)", 18 | "author": [ 19 | { 20 | "@type": "Person", 21 | "givenName": "Eli", 22 | "familyName": "Pousson", 23 | "email": "eli.pousson@gmail.com", 24 | "@id": "https://orcid.org/0000-0001-8280-1706" 25 | } 26 | ], 27 | "copyrightHolder": [ 28 | { 29 | "@type": "Person", 30 | "givenName": "Kyle", 31 | "familyName": "Walker", 32 | "email": "kyle@walker-data.com" 33 | } 34 | ], 35 | "maintainer": [ 36 | { 37 | "@type": "Person", 38 | "givenName": "Eli", 39 | "familyName": "Pousson", 40 | "email": "eli.pousson@gmail.com", 41 | "@id": "https://orcid.org/0000-0001-8280-1706" 42 | } 43 | ], 44 | "softwareSuggestions": [ 45 | { 46 | "@type": "SoftwareApplication", 47 | "identifier": "covr", 48 | "name": "covr", 49 | "provider": { 50 | "@id": "https://cran.r-project.org", 51 | "@type": "Organization", 52 | "name": "Comprehensive R Archive Network (CRAN)", 53 | "url": "https://cran.r-project.org" 54 | }, 55 | "sameAs": "https://CRAN.R-project.org/package=covr" 56 | }, 57 | { 58 | "@type": "SoftwareApplication", 59 | "identifier": "httptest2", 60 | "name": "httptest2", 61 | "provider": { 62 | "@id": "https://cran.r-project.org", 63 | "@type": "Organization", 64 | "name": "Comprehensive R Archive Network (CRAN)", 65 | "url": "https://cran.r-project.org" 66 | }, 67 | "sameAs": "https://CRAN.R-project.org/package=httptest2" 68 | }, 69 | { 70 | "@type": "SoftwareApplication", 71 | "identifier": "knitr", 72 | "name": "knitr", 73 | "provider": { 74 | "@id": "https://cran.r-project.org", 75 | "@type": "Organization", 76 | "name": "Comprehensive R Archive Network (CRAN)", 77 | "url": "https://cran.r-project.org" 78 | }, 79 | "sameAs": "https://CRAN.R-project.org/package=knitr" 80 | }, 81 | { 82 | "@type": "SoftwareApplication", 83 | "identifier": "readr", 84 | "name": "readr", 85 | "provider": { 86 | "@id": "https://cran.r-project.org", 87 | "@type": "Organization", 88 | "name": "Comprehensive R Archive Network (CRAN)", 89 | "url": "https://cran.r-project.org" 90 | }, 91 | "sameAs": "https://CRAN.R-project.org/package=readr" 92 | }, 93 | { 94 | "@type": "SoftwareApplication", 95 | "identifier": "rmarkdown", 96 | "name": "rmarkdown", 97 | "provider": { 98 | "@id": "https://cran.r-project.org", 99 | "@type": "Organization", 100 | "name": "Comprehensive R Archive Network (CRAN)", 101 | "url": "https://cran.r-project.org" 102 | }, 103 | "sameAs": "https://CRAN.R-project.org/package=rmarkdown" 104 | }, 105 | { 106 | "@type": "SoftwareApplication", 107 | "identifier": "sf", 108 | "name": "sf", 109 | "provider": { 110 | "@id": "https://cran.r-project.org", 111 | "@type": "Organization", 112 | "name": "Comprehensive R Archive Network (CRAN)", 113 | "url": "https://cran.r-project.org" 114 | }, 115 | "sameAs": "https://CRAN.R-project.org/package=sf" 116 | }, 117 | { 118 | "@type": "SoftwareApplication", 119 | "identifier": "testthat", 120 | "name": "testthat", 121 | "version": ">= 3.0.0", 122 | "provider": { 123 | "@id": "https://cran.r-project.org", 124 | "@type": "Organization", 125 | "name": "Comprehensive R Archive Network (CRAN)", 126 | "url": "https://cran.r-project.org" 127 | }, 128 | "sameAs": "https://CRAN.R-project.org/package=testthat" 129 | } 130 | ], 131 | "softwareRequirements": { 132 | "1": { 133 | "@type": "SoftwareApplication", 134 | "identifier": "R", 135 | "name": "R", 136 | "version": ">= 2.10" 137 | }, 138 | "2": { 139 | "@type": "SoftwareApplication", 140 | "identifier": "cli", 141 | "name": "cli", 142 | "provider": { 143 | "@id": "https://cran.r-project.org", 144 | "@type": "Organization", 145 | "name": "Comprehensive R Archive Network (CRAN)", 146 | "url": "https://cran.r-project.org" 147 | }, 148 | "sameAs": "https://CRAN.R-project.org/package=cli" 149 | }, 150 | "3": { 151 | "@type": "SoftwareApplication", 152 | "identifier": "dplyr", 153 | "name": "dplyr", 154 | "version": ">= 1.1.0", 155 | "provider": { 156 | "@id": "https://cran.r-project.org", 157 | "@type": "Organization", 158 | "name": "Comprehensive R Archive Network (CRAN)", 159 | "url": "https://cran.r-project.org" 160 | }, 161 | "sameAs": "https://CRAN.R-project.org/package=dplyr" 162 | }, 163 | "4": { 164 | "@type": "SoftwareApplication", 165 | "identifier": "glue", 166 | "name": "glue", 167 | "provider": { 168 | "@id": "https://cran.r-project.org", 169 | "@type": "Organization", 170 | "name": "Comprehensive R Archive Network (CRAN)", 171 | "url": "https://cran.r-project.org" 172 | }, 173 | "sameAs": "https://CRAN.R-project.org/package=glue" 174 | }, 175 | "5": { 176 | "@type": "SoftwareApplication", 177 | "identifier": "httr2", 178 | "name": "httr2", 179 | "provider": { 180 | "@id": "https://cran.r-project.org", 181 | "@type": "Organization", 182 | "name": "Comprehensive R Archive Network (CRAN)", 183 | "url": "https://cran.r-project.org" 184 | }, 185 | "sameAs": "https://CRAN.R-project.org/package=httr2" 186 | }, 187 | "6": { 188 | "@type": "SoftwareApplication", 189 | "identifier": "janitor", 190 | "name": "janitor", 191 | "provider": { 192 | "@id": "https://cran.r-project.org", 193 | "@type": "Organization", 194 | "name": "Comprehensive R Archive Network (CRAN)", 195 | "url": "https://cran.r-project.org" 196 | }, 197 | "sameAs": "https://CRAN.R-project.org/package=janitor" 198 | }, 199 | "7": { 200 | "@type": "SoftwareApplication", 201 | "identifier": "rlang", 202 | "name": "rlang", 203 | "provider": { 204 | "@id": "https://cran.r-project.org", 205 | "@type": "Organization", 206 | "name": "Comprehensive R Archive Network (CRAN)", 207 | "url": "https://cran.r-project.org" 208 | }, 209 | "sameAs": "https://CRAN.R-project.org/package=rlang" 210 | }, 211 | "8": { 212 | "@type": "SoftwareApplication", 213 | "identifier": "stats", 214 | "name": "stats" 215 | }, 216 | "9": { 217 | "@type": "SoftwareApplication", 218 | "identifier": "stringr", 219 | "name": "stringr", 220 | "provider": { 221 | "@id": "https://cran.r-project.org", 222 | "@type": "Organization", 223 | "name": "Comprehensive R Archive Network (CRAN)", 224 | "url": "https://cran.r-project.org" 225 | }, 226 | "sameAs": "https://CRAN.R-project.org/package=stringr" 227 | }, 228 | "10": { 229 | "@type": "SoftwareApplication", 230 | "identifier": "utils", 231 | "name": "utils" 232 | }, 233 | "11": { 234 | "@type": "SoftwareApplication", 235 | "identifier": "vctrs", 236 | "name": "vctrs", 237 | "provider": { 238 | "@id": "https://cran.r-project.org", 239 | "@type": "Organization", 240 | "name": "Comprehensive R Archive Network (CRAN)", 241 | "url": "https://cran.r-project.org" 242 | }, 243 | "sameAs": "https://CRAN.R-project.org/package=vctrs" 244 | }, 245 | "SystemRequirements": null 246 | }, 247 | "fileSize": "786.078KB", 248 | "releaseNotes": "https://github.com/elipousson/crashapi/blob/master/NEWS.md", 249 | "readme": "https://github.com/elipousson/crashapi/blob/main/README.md", 250 | "contIntegration": "https://app.codecov.io/gh/elipousson/crashapi?branch=main", 251 | "developmentStatus": ["https://lifecycle.r-lib.org/articles/stages.html#experimental", "https://www.repostatus.org/#active"], 252 | "keywords": ["rstats", "rspatial", "r", "r-package"] 253 | } 254 | -------------------------------------------------------------------------------- /crashapi.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | -------------------------------------------------------------------------------- /data-raw/crash_data_index.R: -------------------------------------------------------------------------------- 1 | pkg_data <- 2 | utils::data(package = "crashapi", envir = .GlobalEnv)$results[, "Item"] 3 | 4 | names(pkg_data) <- 5 | c( 6 | "U.S. vehicular crash data index", 7 | "NHSTA Terms and Definitions", 8 | "FARS variable names and labels", 9 | "Model Minimum Uniform Crash Criteria (MMUCC) codes (simple)" 10 | ) 11 | 12 | pkg_data_index <- 13 | tibble::enframe( 14 | pkg_data, 15 | value = "data" 16 | ) 17 | 18 | pkg_data_index <- 19 | dplyr::bind_cols( 20 | pkg_data_index, 21 | "date_updated" = c("2022-06-05", "2021-10-25", "2022-03-27", "2022-03-26"), 22 | "date_added" = c("2022-03-27", "2021-10-25", "2022-01-31", "2022-03-26") 23 | ) 24 | 25 | fips_codes <- tigris:::fips_codes 26 | 27 | usethis::use_data(fips_codes, pkg_data_index, internal = TRUE, overwrite = TRUE) 28 | 29 | crash_data_index <- 30 | googlesheets4::read_sheet( 31 | "https://docs.google.com/spreadsheets/d/1rmn6GbHNkfWLLDEEmA87iuy2yHdh7hBybCTZiQJEY0k/edit#gid=0" 32 | ) 33 | 34 | usethis::use_data(crash_data_index, overwrite = TRUE) 35 | -------------------------------------------------------------------------------- /data-raw/fars.R: -------------------------------------------------------------------------------- 1 | fars_terms <- readr::read_csv("inst/extdata/fars_terms.csv") 2 | 3 | usethis::use_data(fars_terms, overwrite = TRUE) 4 | 5 | fars_vars_labels <- 6 | googlesheets4::read_sheet( 7 | "https://docs.google.com/spreadsheets/d/1aqRsXKtumgt5umiVsDTC0ETQiNVFZdWaal9ttQZmSNw/edit?usp=sharing" 8 | ) 9 | 10 | fars_vars_labels <- 11 | fars_vars_labels |> 12 | dplyr::mutate( 13 | nm = janitor::make_clean_names(name), 14 | .after = dplyr::all_of("name") 15 | ) 16 | 17 | usethis::use_data(fars_vars_labels, overwrite = TRUE) 18 | -------------------------------------------------------------------------------- /data-raw/mmucc_codes.R: -------------------------------------------------------------------------------- 1 | library(dplyr) 2 | library(purrr) 3 | library(stringr) 4 | library(xml2) 5 | library(rvest) 6 | 7 | mmucc_url <- 8 | "https://release.niem.gov/niem/codes/mmucc/4.1/mmucc.xsd" 9 | 10 | x <- read_html(mmucc_url) 11 | # xml_structure(x) 12 | 13 | simpletypes <- 14 | x |> 15 | xml_find_all(xpath = "//simpletype") 16 | 17 | simpletypes_df <- 18 | tibble( 19 | "name" = simpletypes |> 20 | xml_attr("name") |> 21 | as_tibble(), 22 | "type" = "simpletype", 23 | "documentation" = simpletypes |> 24 | xml_find_all("annotation//documentation") |> 25 | xml_text() 26 | ) 27 | 28 | # simpletypes 29 | get_restriction <- 30 | function(x) { 31 | select <- 32 | simpletypes |> 33 | xml_find_all("restriction") |> 34 | xml_child(x) 35 | 36 | text <- select |> 37 | xml_text() 38 | 39 | parent <- select |> 40 | xml_parent() |> 41 | xml_parent() 42 | 43 | name <- parent |> 44 | xml_attr("name") 45 | 46 | definition <- parent |> 47 | xml_child() |> 48 | xml_text() 49 | 50 | tibble( 51 | "id" = x, 52 | "name" = name, 53 | "definition" = definition, 54 | "restriction" = text 55 | ) 56 | } 57 | 58 | restrictions <- 59 | map_dfr( 60 | c(1:700), 61 | ~ get_restriction(.x) 62 | ) 63 | 64 | restrictions |> 65 | mutate( 66 | type = "simple", 67 | code = snakecase::to_title_case(str_remove(name, "SimpleType$")) 68 | ) |> 69 | select( 70 | code, 71 | name, 72 | type, 73 | definition, 74 | restriction_id = id, 75 | restriction 76 | ) |> 77 | write_csv("mmucc_codes.csv") 78 | 79 | mmucc_codes <- 80 | readr::read_csv("inst/extdata/mmucc_codes.csv") 81 | 82 | usethis::use_data(mmucc_codes, overwrite = TRUE) 83 | -------------------------------------------------------------------------------- /data/crash_data_index.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/data/crash_data_index.rda -------------------------------------------------------------------------------- /data/fars_terms.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/data/fars_terms.rda -------------------------------------------------------------------------------- /data/fars_vars_labels.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/data/fars_vars_labels.rda -------------------------------------------------------------------------------- /data/mmucc_codes.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/data/mmucc_codes.rda -------------------------------------------------------------------------------- /docs/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Page not found (404) • crashapi 9 | 10 | 11 | 12 | 13 | 14 | 18 | 19 | 20 | Skip to contents 21 | 22 | 23 |
60 |
61 |
65 | 66 | Content not found. Please use links in the navbar. 67 | 68 |
69 |
70 | 71 | 72 |
76 | 77 | 81 | 82 |
83 |
84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /docs/LICENSE-text.html: -------------------------------------------------------------------------------- 1 | 2 | License • crashapi 6 | Skip to contents 7 | 8 | 9 |
41 |
42 |
46 | 47 |
YEAR: 2021
48 | COPYRIGHT HOLDER: crashapi authors
49 | 
50 | 51 |
52 | 53 | 54 |
57 | 58 | 61 | 62 |
63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /docs/LICENSE.html: -------------------------------------------------------------------------------- 1 | 2 | MIT License • crashapi 6 | Skip to contents 7 | 8 | 9 |
41 |
42 |
46 | 47 |
48 | 49 |

Copyright (c) 2021 crashapi authors

50 |

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

51 |

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

52 |

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

53 |
54 | 55 |
56 | 57 | 58 |
61 | 62 | 65 | 66 |
67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/authors.html: -------------------------------------------------------------------------------- 1 | 2 | Authors and Citation • crashapi 6 | Skip to contents 7 | 8 | 9 |
41 |
42 |
45 | 46 |
47 |

Authors

48 | 49 |
  • 50 |

    Eli Pousson. Author, maintainer. 51 |

    52 |
  • 53 |
  • 54 |

    Kyle Walker. Copyright holder. 55 |
    Author of tigris helper functions bundled with crashapi (see tigris-utils.R).

    56 |
  • 57 |
58 | 59 |
60 |

Citation

61 |

Source: DESCRIPTION

62 | 63 |

Pousson E (2022). 64 | crashapi: CrashAPI. 65 | https://github.com/elipousson/crashapi, 66 | https://elipousson.github.io/crashapi/. 67 |

68 |
@Manual{,
69 |   title = {crashapi: CrashAPI},
70 |   author = {Eli Pousson},
71 |   year = {2022},
72 |   note = {https://github.com/elipousson/crashapi,
73 | https://elipousson.github.io/crashapi/},
74 | }
75 |
76 |
78 | 79 | 80 |
83 | 84 | 87 | 88 |
89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /docs/deps/data-deps.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /docs/link.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /docs/pkgdown.js: -------------------------------------------------------------------------------- 1 | /* http://gregfranko.com/blog/jquery-best-practices/ */ 2 | (function($) { 3 | $(function() { 4 | 5 | $('nav.navbar').headroom(); 6 | 7 | Toc.init({ 8 | $nav: $("#toc"), 9 | $scope: $("main h2, main h3, main h4, main h5, main h6") 10 | }); 11 | 12 | if ($('#toc').length) { 13 | $('body').scrollspy({ 14 | target: '#toc', 15 | offset: $("nav.navbar").outerHeight() + 1 16 | }); 17 | } 18 | 19 | // Activate popovers 20 | $('[data-bs-toggle="popover"]').popover({ 21 | container: 'body', 22 | html: true, 23 | trigger: 'focus', 24 | placement: "top", 25 | sanitize: false, 26 | }); 27 | 28 | $('[data-bs-toggle="tooltip"]').tooltip(); 29 | 30 | /* Clipboard --------------------------*/ 31 | 32 | function changeTooltipMessage(element, msg) { 33 | var tooltipOriginalTitle=element.getAttribute('data-original-title'); 34 | element.setAttribute('data-original-title', msg); 35 | $(element).tooltip('show'); 36 | element.setAttribute('data-original-title', tooltipOriginalTitle); 37 | } 38 | 39 | if(ClipboardJS.isSupported()) { 40 | $(document).ready(function() { 41 | var copyButton = ""; 42 | 43 | $("div.sourceCode").addClass("hasCopyButton"); 44 | 45 | // Insert copy buttons: 46 | $(copyButton).prependTo(".hasCopyButton"); 47 | 48 | // Initialize tooltips: 49 | $('.btn-copy-ex').tooltip({container: 'body'}); 50 | 51 | // Initialize clipboard: 52 | var clipboard = new ClipboardJS('[data-clipboard-copy]', { 53 | text: function(trigger) { 54 | return trigger.parentNode.textContent.replace(/\n#>[^\n]*/g, ""); 55 | } 56 | }); 57 | 58 | clipboard.on('success', function(e) { 59 | changeTooltipMessage(e.trigger, 'Copied!'); 60 | e.clearSelection(); 61 | }); 62 | 63 | clipboard.on('error', function() { 64 | changeTooltipMessage(e.trigger,'Press Ctrl+C or Command+C to copy'); 65 | }); 66 | 67 | }); 68 | } 69 | 70 | /* Search marking --------------------------*/ 71 | var url = new URL(window.location.href); 72 | var toMark = url.searchParams.get("q"); 73 | var mark = new Mark("main#main"); 74 | if (toMark) { 75 | mark.mark(toMark, { 76 | accuracy: { 77 | value: "complementary", 78 | limiters: [",", ".", ":", "/"], 79 | } 80 | }); 81 | } 82 | 83 | /* Search --------------------------*/ 84 | /* Adapted from https://github.com/rstudio/bookdown/blob/2d692ba4b61f1e466c92e78fd712b0ab08c11d31/inst/resources/bs4_book/bs4_book.js#L25 */ 85 | // Initialise search index on focus 86 | var fuse; 87 | $("#search-input").focus(async function(e) { 88 | if (fuse) { 89 | return; 90 | } 91 | 92 | $(e.target).addClass("loading"); 93 | var response = await fetch($("#search-input").data("search-index")); 94 | var data = await response.json(); 95 | 96 | var options = { 97 | keys: ["what", "text", "code"], 98 | ignoreLocation: true, 99 | threshold: 0.1, 100 | includeMatches: true, 101 | includeScore: true, 102 | }; 103 | fuse = new Fuse(data, options); 104 | 105 | $(e.target).removeClass("loading"); 106 | }); 107 | 108 | // Use algolia autocomplete 109 | var options = { 110 | autoselect: true, 111 | debug: true, 112 | hint: false, 113 | minLength: 2, 114 | }; 115 | var q; 116 | async function searchFuse(query, callback) { 117 | await fuse; 118 | 119 | var items; 120 | if (!fuse) { 121 | items = []; 122 | } else { 123 | q = query; 124 | var results = fuse.search(query, { limit: 20 }); 125 | items = results 126 | .filter((x) => x.score <= 0.75) 127 | .map((x) => x.item); 128 | if (items.length === 0) { 129 | items = [{dir:"Sorry 😿",previous_headings:"",title:"No results found.",what:"No results found.",path:window.location.href}]; 130 | } 131 | } 132 | callback(items); 133 | } 134 | $("#search-input").autocomplete(options, [ 135 | { 136 | name: "content", 137 | source: searchFuse, 138 | templates: { 139 | suggestion: (s) => { 140 | if (s.title == s.what) { 141 | return `${s.dir} >
${s.title}
`; 142 | } else if (s.previous_headings == "") { 143 | return `${s.dir} >
${s.title}
> ${s.what}`; 144 | } else { 145 | return `${s.dir} >
${s.title}
> ${s.previous_headings} > ${s.what}`; 146 | } 147 | }, 148 | }, 149 | }, 150 | ]).on('autocomplete:selected', function(event, s) { 151 | window.location.href = s.path + "?q=" + q + "#" + s.id; 152 | }); 153 | }); 154 | })(window.jQuery || window.$) 155 | 156 | 157 | -------------------------------------------------------------------------------- /docs/pkgdown.yml: -------------------------------------------------------------------------------- 1 | pandoc: '2.18' 2 | pkgdown: 2.0.3 3 | pkgdown_sha: ~ 4 | articles: {} 5 | last_built: 2022-10-02T02:03Z 6 | urls: 7 | reference: https://elipousson.github.io/crashapi/reference 8 | article: https://elipousson.github.io/crashapi/articles 9 | 10 | -------------------------------------------------------------------------------- /docs/reference/crashapi-package.html: -------------------------------------------------------------------------------- 1 | 2 | crashapi: CrashAPI — crashapi-package • crashapi 6 | Skip to contents 7 | 8 | 9 |
41 |
42 |
47 | 48 |
49 |

Get Fatality Analysis Reporting System (FARS) data with the FARS API from the U.S. National Highway Traffic Safety Administration (NHTSA).

50 |
51 | 52 | 53 | 60 |
61 |

Author

62 |

Maintainer: Eli Pousson eli.pousson@gmail.com (ORCID)

63 |

Other contributors:

  • Kyle Walker kyle@walker-data.com (Author of tigris helper functions bundled with crashapi (see tigris-utils.R).) [copyright holder]

  • 64 |
65 | 66 |
68 | 69 | 70 |
73 | 74 | 77 | 78 |
79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /docs/reference/fars_terms.html: -------------------------------------------------------------------------------- 1 | 2 | NHSTA Terms and Definitions — fars_terms • crashapi 10 | Skip to contents 11 | 12 | 13 |
45 |
46 |
51 | 52 |
53 |

FARS-related terms defined by the National Highway Traffic 54 | Safety Administration based on ANSI D16.1-1996: Manual on Classification of 55 | Motor Vehicle Traffic Accidents.

56 |
57 | 58 |
59 |

Usage

60 |
fars_terms
61 |
62 | 63 |
64 |

Format

65 |

A data frame with 66 rows and 2 variables:

term
66 |

character Term

67 | 68 |
definition
69 |

character Term definition

70 | 71 | 72 |
73 |
74 |

Source

75 |

NHTSA FARS Terms

76 |
77 |
78 |

Details

79 |

Added: October 25 2021 80 | Updated: October 25 2021

81 |
82 | 83 |
85 | 86 | 87 |
90 | 91 | 94 | 95 |
96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /docs/reference/fars_vars.html: -------------------------------------------------------------------------------- 1 | 2 | Get variables and variable attributes for the Fatality Analysis 7 | Reporting System (FARS) API — fars_vars • crashapi 16 | Skip to contents 17 | 18 | 19 |
51 |
52 |
58 | 59 |
60 |

By default, this function returns the returns the list of 61 | variables for the data year specified. If vars is "make", "model", or 62 | "bodytype", the function returns #' list of variable attributes for the 63 | specified variable name or attributes for make model and body type 64 | specified in the FARS dataset.

65 |
66 | 67 |
68 |

Usage

69 |
fars_vars(year, var = NULL, make = NULL, model = NULL)
70 |
71 | 72 |
73 |

Arguments

74 |
year
75 |

Case year. Year must be between 2010 and 2019.

76 |
var
77 |

Default NULL. Supported values are "make", "model", and 78 | "bodytype". Using the var parameter returns variable attributes for the 79 | specified variable name or attributes for make model and body type 80 | specified in the dataset.

81 |
make
82 |

Integer. Make ID number. Required to return variables for "model" 83 | and "bodytype". Get a list of make ID numbers using the "make" var for the 84 | selected year, e.g. fars_vars(year = 2010, var = "make").

85 |
model
86 |

Integer. Model ID number. Required to return variables for 87 | "bodytype". Get a list of model ID numbers using the "model" var for the 88 | selected year with a valid make ID number, e.g. fars_vars(year = 2010, var = "model", make = 37)

89 |
90 | 91 |
93 | 94 | 95 |
98 | 99 | 102 | 103 |
104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /docs/reference/fars_vars_labels.html: -------------------------------------------------------------------------------- 1 | 2 | FARS variable names and labels — fars_vars_labels • crashapi 10 | Skip to contents 11 | 12 | 13 |
45 |
46 |
51 | 52 |
53 |

A table of FARS table variable names extracted from the Fatality 54 | Analysis Reporting System (FARS) Analytical User's Manual, 1975-2019, 55 | documentation of the SAS format data files.

56 |
57 | 58 |
59 |

Usage

60 |
fars_vars_labels
61 |
62 | 63 |
64 |

Format

65 |

A data frame with 498 rows and 14 variables:

name
66 |

character Variable name

67 | 68 |
label
69 |

character Variable label

70 | 71 |
order
72 |

double Sort order

73 | 74 |
data_file
75 |

character SAS data file name

76 | 77 |
data_file_id
78 |

double SAS data file ID

79 | 80 |
file_id
81 |

character File ID

82 | 83 |
key
84 |

logical Indicator for key variables

85 | 86 |
location
87 |

double Location in SAS data file

88 | 89 |
mmuc_equivalent
90 |

logical Equivalent term in MMUC (placeholder)

91 | 92 |
discontinued
93 |

logical Indicator for discontinued variables

94 | 95 |
api_only
96 |

logical Indicator for variables only used by API

97 | 98 |
api
99 |

character Name(s) of corresponding CrashAPI service

100 | 101 |
name_var
102 |

logical Indicator for "NAME" variable returned by API

103 | 104 |
api_list_col
105 |

logical Indicator for list columns returned by API

106 | 107 | 108 |
109 |
110 |

Details

111 |

Added: January 31 2022 112 | Updated: March 27 2022

113 |
114 | 115 |
117 | 118 | 119 |
122 | 123 | 126 | 127 |
128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /docs/reference/figures/README-get_fars_summary-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/docs/reference/figures/README-get_fars_summary-1.png -------------------------------------------------------------------------------- /docs/reference/figures/README-map_fars_crashes-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/docs/reference/figures/README-map_fars_crashes-1.png -------------------------------------------------------------------------------- /docs/reference/format_crashes.html: -------------------------------------------------------------------------------- 1 | 2 | Format crash data — format_crashes • crashapi 10 | Skip to contents 11 | 12 | 13 |
45 |
46 |
51 | 52 |
53 |

Reorder columns to match the order documented in Fatality Analysis Reporting 54 | System (FARS) Analytical User's Manual, 1975-2019 and append derived columns 55 | for date, time, and datetime.

56 |
57 | 58 |
59 |

Usage

60 |
format_crashes(x, details = TRUE)
61 |
62 | 63 |
64 |

Arguments

65 |
x
66 |

Data frame with crash data.

67 |
details
68 |

If TRUE, append date, time, datetime columns to formatted 69 | crash data; defaults to TRUE

70 |
71 | 72 |
74 | 75 | 76 |
79 | 80 | 83 | 84 |
85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /docs/reference/get_fars_crash_persons.html: -------------------------------------------------------------------------------- 1 | 2 | Get Crashes By Occupant — get_fars_crash_persons • crashapi 8 | Skip to contents 9 | 10 | 11 |
43 |
44 |
49 | 50 |
51 |

This function returns a list of fatal crashes by occupant that have occurred 52 | throughout United States.

53 |
54 | 55 |
56 |

Usage

57 |
get_fars_crash_persons(
 58 |   year = NULL,
 59 |   start_year,
 60 |   end_year = NULL,
 61 |   state,
 62 |   age = NULL,
 63 |   sex = NULL,
 64 |   seat,
 65 |   injury,
 66 |   occupants = TRUE,
 67 |   nonoccupants = TRUE
 68 | )
69 |
70 | 71 |
72 |

Arguments

73 |
year
74 |

numeric vector. Year or range with start and end year. 2010 to 75 | 2020 supported.

76 |
start_year
77 |

Start year for crash reports.

78 |
end_year
79 |

End year for crash reports.

80 |
state
81 |

Required. State name, abbreviation, or FIPS number.

82 |
age
83 |

numeric

84 |
sex
85 |

Options "m", "f", "male", "female", "unknown", "not reported."

86 |
seat
87 |

Seat position

88 |
injury
89 |

Options "unknown", "not reported", "died prior", "injured", 90 | "fatal", "suspected serious", "suspected minor", "possible", "no apparent"

91 |
occupants
92 |

Include vehicle occupants in query; defaults to TRUE

93 |
nonoccupants
94 |

Include non-occupants in query; defaults to TRUE

95 |
96 | 97 |
99 | 100 | 101 |
104 | 105 | 108 | 109 |
110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /docs/reference/get_fars_crash_vehicles.html: -------------------------------------------------------------------------------- 1 | 2 | Get Crashes By Vehicle — get_fars_crash_vehicles • crashapi 12 | Skip to contents 13 | 14 | 15 |
47 |
48 |
53 | 54 |
55 |

This function returns a list of fatal crashes by vehicle type 56 | that have occurred throughout United States. The make, model, and body type 57 | must match the options returned by fars_vars. This function accepts named 58 | options that are converted to ID numbers for use in the API query.

59 |
60 | 61 |
62 |

Usage

63 |
get_fars_crash_vehicles(
 64 |   year = NULL,
 65 |   start_year,
 66 |   end_year = NULL,
 67 |   state,
 68 |   make = NULL,
 69 |   model = NULL,
 70 |   model_year = 2010,
 71 |   body_type = NULL
 72 | )
73 |
74 | 75 |
76 |

Arguments

77 |
year
78 |

numeric vector. Year or range with start and end year. 2010 to 79 | 2020 supported.

80 |
start_year
81 |

Start year for crash reports.

82 |
end_year
83 |

End year for crash reports.

84 |
state
85 |

Required. State name, abbreviation, or FIPS number.

86 |
make
87 |

Make name or ID, Required. The start_year is used to return a 88 | list of support make options. Default: NULL

89 |
model
90 |

Model name or ID, Optional. Default: NULL

91 |
model_year
92 |

Model year, Optional. Default: NULL

93 |
body_type
94 |

Body type, Optional. model must be provided to use 95 | body_type parameter. Default: NULL

96 |
97 | 98 |
100 | 101 | 102 |
105 | 106 | 109 | 110 |
111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /docs/reference/get_fars_zip.html: -------------------------------------------------------------------------------- 1 | 2 | Download FARS data files as zipped CSV or SAS files — get_fars_zip • crashapi 12 | Skip to contents 13 | 14 | 15 |
47 |
48 |
53 | 54 |
55 |

This function provides an alternative to get_fars_year() that downloads 56 | files directly from NHTSA FTP site. If read is TRUE, the function reads a 57 | list containing data frames for each table available in the selected year. If 58 | geo is TRUE, the accident table is converted to an sf object.

59 |
60 | 61 |
62 |

Usage

63 |
get_fars_zip(
 64 |   year = 2020,
 65 |   format = "csv",
 66 |   path = NULL,
 67 |   pr = FALSE,
 68 |   read = TRUE,
 69 |   geometry = FALSE
 70 | )
71 |
72 | 73 |
74 |

Arguments

75 |
year
76 |

Year of data from 1975 to 2020, Default: 2020

77 |
format
78 |

Format of zipped data tables ('csv' or 'sas'). Default: 'csv'. 79 | unzip and geo options are only supported if format is "csv".

80 |
path
81 |

Path to download zip file with FARS tables.

82 |
pr
83 |

If TRUE, download FARS data for Puerto Rico. No Puerto Rico data 84 | available for years 1975-1977. Default: FALSE

85 |
read
86 |

If TRUE, unzip the downloaded file and read CSV files into a 87 | list of tables with each list item corresponding to one CSV file.

88 |
geometry
89 |

If TRUE, convert the accident table to a sf object.

90 |
91 |
92 |

Value

93 |

Downloads zip file with CSV or SAS tables and returns NULL invisibly 94 | or returns a list of data frames (if geo is FALSE), or returns a list of 95 | data frames with the accident table converted to a sf object.

96 |
97 | 98 |
100 | 101 | 102 |
105 | 106 | 109 | 110 |
111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /docs/reference/index.html: -------------------------------------------------------------------------------- 1 | 2 | Function reference • crashapi 6 | Skip to contents 7 | 8 | 9 |
41 |
42 |
45 | 46 |
47 |

Get data from the FARS API

48 | 49 | 50 | 51 | 52 |
53 | 54 | 55 | 56 | 57 |
58 | 59 | fars_vars() 60 |
61 |
Get variables and variable attributes for the Fatality Analysis 62 | Reporting System (FARS) API
63 |
64 | 65 | get_fars() get_fars_crashes() get_fars_cases() get_fars_crash_list() get_fars_summary() get_fars_year() 66 |
67 |
Get Fatality Analysis Reporting System (FARS) data with the FARS API
68 |
69 | 70 | get_fars_crash_persons() 71 |
72 |
Get Crashes By Occupant
73 |
74 | 75 | get_fars_crash_vehicles() 76 |
77 |
Get Crashes By Vehicle
78 |
79 | 80 | get_fars_zip() 81 |
82 |
Download FARS data files as zipped CSV or SAS files
83 |
84 | 85 | read_crashapi() 86 |
87 |
Read data from the CrashAPI using a url template
88 |
89 |

Get variable definitions

90 | 91 | 92 | 93 | 94 |
95 | 96 | 97 | 98 | 99 |
100 | 101 | fars_vars() 102 |
103 |
Get variables and variable attributes for the Fatality Analysis 104 | Reporting System (FARS) API
105 |
106 |

Data formatting functions

107 | 108 | 109 | 110 | 111 |
112 | 113 | 114 | 115 | 116 |
117 | 118 | format_crashes() 119 |
120 |
Format crash data
121 |
122 |

Reference information

123 | 124 | 125 | 126 | 127 |
128 | 129 | 130 | 131 | 132 |
133 | 134 | fars_terms 135 |
136 |
NHSTA Terms and Definitions
137 |
138 | 139 | fars_vars_labels 140 |
141 |
FARS variable names and labels
142 |
143 | 144 | mmucc_codes 145 |
146 |
Model Minimum Uniform Crash Criteria (MMUCC) codes (simple)
147 |
148 | 149 | crash_data_index 150 |
151 |
U.S. vehicular crash data index (city, county, regional, and state)
152 |
153 |
155 | 156 | 157 |
160 | 161 | 164 | 165 |
166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /docs/reference/read_crashapi.html: -------------------------------------------------------------------------------- 1 | 2 | Read data from the CrashAPI using a url template — read_crashapi • crashapi 10 | Skip to contents 11 | 12 | 13 |
45 |
46 |
51 | 52 |
53 |

An updated utility function using the httr2 package to read data from the 54 | CrashAPI using the API URL templates listed on the NHSTA website: 55 | https://crashviewer.nhtsa.dot.gov/CrashAPI

56 |
57 | 58 |
59 |

Usage

60 |
read_crashapi(
 61 |   url = "https://crashviewer.nhtsa.dot.gov",
 62 |   data = "crashes",
 63 |   type = NULL,
 64 |   format = "json",
 65 |   results = TRUE,
 66 |   ...
 67 | )
68 |
69 | 70 |
71 |

Arguments

72 |
url
73 |

Base url for CrashAPI.

74 |
data
75 |

Data (crashes, analytics, or fars), Default: 'crashes'

76 |
type
77 |

Type of API to use, Default: NULL

78 |
format
79 |

Format to return, Default: 'json'

80 |
results
81 |

If FALSE, return formatted url, Default: TRUE

82 |
...
83 |

Additional parameters used in template (varies by type).

84 |
85 |
86 |

Value

87 |

Data frame with requested data or a formatted url (if results = FALSE)

88 |
89 | 90 |
92 | 93 | 94 |
97 | 98 | 101 | 102 |
103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /docs/sitemap.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | https://elipousson.github.io/crashapi/404.html 5 | 6 | 7 | https://elipousson.github.io/crashapi/LICENSE-text.html 8 | 9 | 10 | https://elipousson.github.io/crashapi/LICENSE.html 11 | 12 | 13 | https://elipousson.github.io/crashapi/authors.html 14 | 15 | 16 | https://elipousson.github.io/crashapi/index.html 17 | 18 | 19 | https://elipousson.github.io/crashapi/news/index.html 20 | 21 | 22 | https://elipousson.github.io/crashapi/reference/crash_data_index.html 23 | 24 | 25 | https://elipousson.github.io/crashapi/reference/crashapi-package.html 26 | 27 | 28 | https://elipousson.github.io/crashapi/reference/fars_terms.html 29 | 30 | 31 | https://elipousson.github.io/crashapi/reference/fars_vars.html 32 | 33 | 34 | https://elipousson.github.io/crashapi/reference/fars_vars_labels.html 35 | 36 | 37 | https://elipousson.github.io/crashapi/reference/format_crashes.html 38 | 39 | 40 | https://elipousson.github.io/crashapi/reference/get_fars.html 41 | 42 | 43 | https://elipousson.github.io/crashapi/reference/get_fars_crash_persons.html 44 | 45 | 46 | https://elipousson.github.io/crashapi/reference/get_fars_crash_vehicles.html 47 | 48 | 49 | https://elipousson.github.io/crashapi/reference/get_fars_zip.html 50 | 51 | 52 | https://elipousson.github.io/crashapi/reference/index.html 53 | 54 | 55 | https://elipousson.github.io/crashapi/reference/mmucc_codes.html 56 | 57 | 58 | https://elipousson.github.io/crashapi/reference/read_crashapi.html 59 | 60 | 61 | -------------------------------------------------------------------------------- /man/crash_data_index.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{crash_data_index} 5 | \alias{crash_data_index} 6 | \title{U.S. vehicular crash data index (city, county, regional, and state)} 7 | \format{ 8 | A data frame with 75 rows and 22 variables: 9 | \describe{ 10 | \item{\code{name}}{Name of data set from provider.} 11 | \item{\code{level}}{Geographic scope/level (e.g. city, county, region, state, national)} 12 | \item{\code{city}}{City name} 13 | \item{\code{county}}{County name} 14 | \item{\code{region}}{logical COLUMN_DESCRIPTION} 15 | \item{\code{state_name}}{U.S. state name} 16 | \item{\code{state_abb}}{U.S. state abbreviation} 17 | \item{\code{info_url}}{Informational URL (e.g. informational page about file download options)} 18 | \item{\code{data_url}}{Data URL (e.g. direct link to ArcGIS FeatureServer layer)} 19 | \item{\code{format}}{Data format (e.g. Socrata, CKAN, ArcGIS MapServer, etc.)} 20 | \item{\code{statewide_yn}}{Yes for data with statewide geographic scope; NA for data from city, county, or regional level providers} 21 | \item{\code{batch_download_yn}}{Yes for data where batch download is possible} 22 | \item{\code{start_year}}{Earliest year for crashes in dataset} 23 | \item{\code{end_year}}{Latest year for crashes in dataset} 24 | \item{\code{publisher}}{Agency/organization responsible for publishing the data online} 25 | \item{\code{description}}{Description of the dataset from provider} 26 | \item{\code{bike_ped_only}}{Yes for data that only includes bike/ped involved crashes (common for Vision Zero programs)} 27 | \item{\code{rolling_window}}{Description of rolling time window if data is only available within a rolling window} 28 | \item{\code{fatal_severe_only}}{Yes for data that only includes fatal/severe crashes (common for Vision Zero programs)} 29 | \item{\code{date_note}}{Note on the dates for the crash data} 30 | \item{\code{updates}}{Information on update schedule if available} 31 | \item{\code{note}}{General notes} 32 | } 33 | } 34 | \usage{ 35 | crash_data_index 36 | } 37 | \description{ 38 | This index include identified data from cities, counties, or regional 39 | entities in 43 of 50 U.S. states. Statewide data sources are included from 33 40 | states. In 4 states (NE, OH, ME, and CT), the only identified statewide data 41 | sources allow limited access through a web-based public query form. In 1 42 | state (MN), data only available through restricted access mapping/query tool. 43 | Not all statewide data sources include all crashes (some include only 44 | cyclist/pedestrian crashes or fatal crashes) and the structure and format of 45 | the crash data provided varies considerably. 46 | } 47 | \details{ 48 | This index was compiled by Eli Pousson between October 2021 and February 49 | 2022 with additional contributions from Mae Hanzlik. 50 | 51 | Added: March 27 2022 52 | Updated: June 05 2022 53 | 54 | Corrections, updates, or additional sources should be added to this public 55 | Google Sheet: 56 | \url{https://docs.google.com/spreadsheets/d/1rmn6GbHNkfWLLDEEmA87iuy2yHdh7hBybCTZiQJEY0k/edit?usp=sharing} 57 | } 58 | \keyword{datasets} 59 | -------------------------------------------------------------------------------- /man/crashapi-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/crashapi-package.R 3 | \docType{package} 4 | \name{crashapi-package} 5 | \alias{crashapi} 6 | \alias{crashapi-package} 7 | \title{crashapi: CrashAPI} 8 | \description{ 9 | Get Fatality Analysis Reporting System (FARS) data with the FARS API from the U.S. National Highway Traffic Safety Administration (NHTSA). 10 | } 11 | \seealso{ 12 | Useful links: 13 | \itemize{ 14 | \item \url{https://github.com/elipousson/crashapi} 15 | \item \url{https://elipousson.github.io/crashapi/} 16 | \item Report bugs at \url{https://github.com/elipousson/crashapi/issues} 17 | } 18 | 19 | } 20 | \author{ 21 | \strong{Maintainer}: Eli Pousson \email{eli.pousson@gmail.com} (\href{https://orcid.org/0000-0001-8280-1706}{ORCID}) 22 | 23 | Other contributors: 24 | \itemize{ 25 | \item Kyle Walker \email{kyle@walker-data.com} (Author of tigris helper functions bundled with crashapi (see tigris-utils.R).) [copyright holder] 26 | } 27 | 28 | } 29 | \keyword{internal} 30 | -------------------------------------------------------------------------------- /man/fars_terms.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{fars_terms} 5 | \alias{fars_terms} 6 | \title{NHSTA Terms and Definitions} 7 | \format{ 8 | A data frame with 66 rows and 2 variables: 9 | \describe{ 10 | \item{\code{term}}{character Term} 11 | \item{\code{definition}}{character Term definition} 12 | } 13 | } 14 | \source{ 15 | \href{https://www-fars.nhtsa.dot.gov/Help/Terms.aspx}{NHTSA FARS Terms} 16 | } 17 | \usage{ 18 | fars_terms 19 | } 20 | \description{ 21 | FARS-related terms defined by the National Highway Traffic 22 | Safety Administration based on ANSI D16.1-1996: Manual on Classification of 23 | Motor Vehicle Traffic Accidents. 24 | } 25 | \details{ 26 | Added: October 25 2021 27 | Updated: October 25 2021 28 | } 29 | \keyword{datasets} 30 | -------------------------------------------------------------------------------- /man/fars_vars.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fars_vars.R 3 | \name{fars_vars} 4 | \alias{fars_vars} 5 | \alias{get_vars} 6 | \title{Get variables and variable attributes for the Fatality Analysis 7 | Reporting System (FARS) API} 8 | \usage{ 9 | fars_vars(year, var = NULL, make = NULL, model = NULL) 10 | } 11 | \arguments{ 12 | \item{year}{Case year. Year must be between 2010 and 2019.} 13 | 14 | \item{var}{Default NULL. Supported values are "make", "model", and 15 | "bodytype". Using the var parameter returns variable attributes for the 16 | specified variable name or attributes for make model and body type 17 | specified in the dataset.} 18 | 19 | \item{make}{Integer. Make ID number. Required to return variables for "model" 20 | and "bodytype". Get a list of make ID numbers using the "make" var for the 21 | selected year, e.g. \code{fars_vars(year = 2010, var = "make")}.} 22 | 23 | \item{model}{Integer. Model ID number. Required to return variables for 24 | "bodytype". Get a list of model ID numbers using the "model" var for the 25 | selected year with a valid make ID number, e.g. \code{fars_vars(year = 2010, var = "model", make = 37)}} 26 | } 27 | \description{ 28 | By default, this function returns the returns the list of 29 | variables for the data year specified. If \code{vars} is "make", "model", or 30 | "bodytype", the function returns #' list of variable attributes for the 31 | specified variable name or attributes for make model and body type 32 | specified in the FARS dataset. 33 | } 34 | \examples{ 35 | 36 | head(fars_vars(year = 2022, var = "make"), 5) 37 | 38 | head(fars_vars(year = 2022, var = "model", make = 12), 5) 39 | 40 | fars_vars(year = 2022, var = "bodytype", make = 12, model = 37) 41 | 42 | } 43 | -------------------------------------------------------------------------------- /man/fars_vars_labels.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{fars_vars_labels} 5 | \alias{fars_vars_labels} 6 | \title{FARS variable names and labels} 7 | \format{ 8 | A data frame with 498 rows and 14 variables: 9 | \describe{ 10 | \item{\code{name}}{character Variable name} 11 | \item{\code{label}}{character Variable label} 12 | \item{\code{order}}{double Sort order} 13 | \item{\code{data_file}}{character SAS data file name} 14 | \item{\code{data_file_id}}{double SAS data file ID} 15 | \item{\code{file_id}}{character File ID} 16 | \item{\code{key}}{logical Indicator for key variables} 17 | \item{\code{location}}{double Location in SAS data file} 18 | \item{\code{mmuc_equivalent}}{logical Equivalent term in MMUC (placeholder)} 19 | \item{\code{discontinued}}{logical Indicator for discontinued variables} 20 | \item{\code{api_only}}{logical Indicator for variables only used by API} 21 | \item{\code{api}}{character Name(s) of corresponding CrashAPI service} 22 | \item{\code{name_var}}{logical Indicator for "NAME" variable returned by API} 23 | \item{\code{nm}}{Short version of the variable name} 24 | \item{\code{api_list_col}}{logical Indicator for list columns returned by API} 25 | } 26 | } 27 | \usage{ 28 | fars_vars_labels 29 | } 30 | \description{ 31 | A table of FARS table variable names extracted from the Fatality 32 | Analysis Reporting System (FARS) Analytical User's Manual, 1975-2019, 33 | documentation of the SAS format data files. 34 | } 35 | \details{ 36 | Added: January 31 2022 37 | Updated: March 27 2022 38 | } 39 | \keyword{datasets} 40 | -------------------------------------------------------------------------------- /man/figures/README-get_fars_summary-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/man/figures/README-get_fars_summary-1.png -------------------------------------------------------------------------------- /man/figures/README-map_fars_crashes-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elipousson/crashapi/d19acf8a301543d65f5107bbd354078d6db34f09/man/figures/README-map_fars_crashes-1.png -------------------------------------------------------------------------------- /man/format_crashes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{format_crashes} 4 | \alias{format_crashes} 5 | \title{Format crash data} 6 | \usage{ 7 | format_crashes(x, details = TRUE) 8 | } 9 | \arguments{ 10 | \item{x}{Data frame with crash data.} 11 | 12 | \item{details}{If \code{TRUE}, append date, time, datetime columns to formatted 13 | crash data; defaults to TRUE} 14 | } 15 | \description{ 16 | Reorder columns to match the order documented in Fatality Analysis Reporting 17 | System (FARS) Analytical User's Manual, 1975-2019 and append derived columns 18 | for date, time, and datetime. 19 | } 20 | -------------------------------------------------------------------------------- /man/get_crss_zip.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/get_crss_zip.R 3 | \name{get_crss_zip} 4 | \alias{get_crss_zip} 5 | \title{Download CRSS data files as zipped CSV or SAS files} 6 | \usage{ 7 | get_crss_zip( 8 | year = 2022, 9 | format = "csv", 10 | path = NULL, 11 | aux = FALSE, 12 | read = TRUE, 13 | geometry = FALSE, 14 | overwrite = FALSE 15 | ) 16 | } 17 | \arguments{ 18 | \item{year}{Year of data from 2016 to 2022, Default: 2022} 19 | 20 | \item{format}{Format of zipped data tables ('csv' or 'sas'). Default: 'csv'. 21 | unzip and geo options are only supported if format is "csv".} 22 | 23 | \item{path}{Path to download zip file. Set to \code{\link[=getwd]{getwd()}} if \code{NULL} (default).} 24 | 25 | \item{aux}{If \code{TRUE}, download auxiliary 26 | CRSS datasets .} 27 | 28 | \item{read}{If \code{TRUE}, unzip the downloaded file and read CSV files into a 29 | list of tables with each list item corresponding to one CSV file.} 30 | 31 | \item{geometry}{If \code{TRUE}, convert the accident table to a sf object.} 32 | 33 | \item{overwrite}{If \code{FALSE}, abort if file exists at the provided path. If 34 | \code{TRUE}, overwrite file.} 35 | } 36 | \value{ 37 | Downloads zip file with CSV or SAS tables and returns the zip file 38 | path invisibly or returns a list of data frames (if geo is \code{FALSE}), or 39 | returns a list of data frames with the accident table converted to a sf 40 | object. 41 | } 42 | \description{ 43 | This function is similar to \code{\link[=get_fars_zip]{get_fars_zip()}} to download files directly from 44 | NHTSA FTP site. If read is \code{TRUE}, the function reads a list containing data 45 | frames for each table available in the selected year. If geometry is \code{TRUE}, 46 | the accident table is converted to an sf object. 47 | } 48 | -------------------------------------------------------------------------------- /man/get_fars.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/get_fars.R 3 | \name{get_fars} 4 | \alias{get_fars} 5 | \alias{get_fars_crashes} 6 | \alias{get_fars_cases} 7 | \alias{get_fars_crash_details} 8 | \alias{get_fars_crash_list} 9 | \alias{get_fars_summary} 10 | \alias{get_fars_year} 11 | \title{Get Fatality Analysis Reporting System (FARS) data with the FARS API} 12 | \usage{ 13 | get_fars( 14 | year = 2022, 15 | state, 16 | county = NULL, 17 | api = c("crashes", "cases", "state list", "summary count", "year dataset", "zip"), 18 | type = NULL, 19 | details = FALSE, 20 | geometry = FALSE, 21 | crs = NULL, 22 | cases = NULL, 23 | vehicles = NULL, 24 | format = "json", 25 | pr = FALSE, 26 | path = NULL, 27 | download = FALSE 28 | ) 29 | 30 | get_fars_crashes( 31 | year = 2022, 32 | start_year, 33 | end_year = NULL, 34 | state, 35 | county, 36 | details = FALSE, 37 | geometry = FALSE, 38 | crs = NULL 39 | ) 40 | 41 | get_fars_cases( 42 | year = 2022, 43 | state, 44 | cases, 45 | details = FALSE, 46 | geometry = FALSE, 47 | crs = NULL 48 | ) 49 | 50 | get_fars_crash_list( 51 | year = 2022, 52 | start_year = NULL, 53 | end_year = NULL, 54 | state, 55 | vehicles = c(1, 50) 56 | ) 57 | 58 | get_fars_summary(year = 2022, start_year, end_year = NULL, state) 59 | 60 | get_fars_year( 61 | year = 2022, 62 | type = "accident", 63 | state, 64 | format = "json", 65 | path = NULL, 66 | geometry = FALSE, 67 | crs = NULL, 68 | download = FALSE 69 | ) 70 | } 71 | \arguments{ 72 | \item{year}{numeric vector. Year or range with start and end year. If \code{api} 73 | is "details", "year dataset", or "zip" (or using the 74 | \code{get_fars_crash_details}, \code{get_fars_year}, or \code{get_fars_zip} functions), a 75 | single year is required. All other \code{api} options support a range with the 76 | minimum value is used as a start year and the maximum value used as a end 77 | year. Most \code{api} options support the years from 2010 through the most 78 | recent year of release. "year dataset" only supports 2010 to 2017 and "zip" 79 | supports 1975 to 2022. \code{start_year} and \code{end_year} are ignored if \code{year} is 80 | not \code{NULL}.} 81 | 82 | \item{state}{Required. State name, abbreviation, or FIPS number. 83 | \code{get_fars_crash_list} supports multiple states.} 84 | 85 | \item{county}{County name or FIPS number. Required for \code{get_fars_crashes}.} 86 | 87 | \item{api}{character. API function to use. Supported values include 88 | "crashes", "cases", "state list", "summary count", "year dataset", and 89 | "zip". Default: "crashes".} 90 | 91 | \item{type}{Name of the dataset or data file to download when using the "year 92 | dataset" api or \code{get_fars_year}. Supported values include "ACCIDENT", 93 | "CEVENT", "DAMAGE", "DISTRACT", "DRIMPAIR", "FACTOR", "MANEUVER", 94 | "NMCRASH", "NMIMPAIR", "NMPRIOR", "PARKWORK", "PBTYPE", "PERSON", 95 | "SAFETYEQ", "VEHICLE", "VEVENT VINDECODE", "VINDERIVED", "VIOLATION", 96 | "VISION", and "VSOE". Lowercase or mixed case values are permitted.} 97 | 98 | \item{details}{Type of detailed crash data to return (either "events" or 99 | "vehicles"). If \code{TRUE} for \code{get_fars} or \code{get_fars_crashes}, detailed case 100 | data (excluding event and vehicle data) is attached to the returned crash 101 | data. If \code{NULL} for \code{get_fars_cases}, events and vehicle data are excluded 102 | from the returned case data. returned by \code{get_fars_cases}. Optional for 103 | \code{get_fars_crash_details}. Default: \code{NULL} for \code{get_fars_cases}; \code{FALSE} for 104 | \code{get_fars} and \code{get_fars_crashes}.} 105 | 106 | \item{geometry}{If \code{TRUE}, return sf object. Optional for \code{get_fars_crashes}.} 107 | 108 | \item{crs}{Coordinate reference system to return for \code{get_fars_crashes} if 109 | \code{geometry} is \code{TRUE}.} 110 | 111 | \item{cases}{One or more FARS case numbers. Required if \code{api} is "cases" or 112 | using \code{get_fars_cases}. Multiple case numbers can be provided.} 113 | 114 | \item{vehicles}{numeric vector with the minimum and maximum number of 115 | vehicles, e.g. c(1, 2) for minimum of 1 vehicle and maximum of 2. Required 116 | for \code{get_fars_crash_list}.} 117 | 118 | \item{format}{Default "json". "csv" is supported when using the "year 119 | dataset" api. "sas" is supporting for the "zip" api.} 120 | 121 | \item{pr}{logical. If \code{TRUE}, download zip file with FARS data for Puerto 122 | Rico. No Puerto Rico data available for years 1975-1977. Default: \code{FALSE} 123 | for \code{get_fars_zip} only.} 124 | 125 | \item{path}{File path used if download is \code{TRUE}.} 126 | 127 | \item{download}{logical. If \code{TRUE} and the \code{api} is "year dataset" or "zip", 128 | download the data to a file. Default \code{FALSE}.} 129 | 130 | \item{start_year}{Start year for crash reports.} 131 | 132 | \item{end_year}{End year for crash reports.} 133 | } 134 | \description{ 135 | This function provides a convenient interface for accessing FARS 136 | data or data summaries using a range of criteria. The \code{api} parameter 137 | allows you to call one of the following functions to access DOT NHTSA’s 138 | Crash API: 139 | \itemize{ 140 | \item \code{get_fars_crash_list} returns a list of fatal crashes that have occurred 141 | in multiple states in one or more years. 142 | \item \code{get_fars_crash_details} returns a details of a fatal crash that has 143 | occurred in a state for a single year. 144 | \item \code{get_fars_crashes} a list of fatal crashes by location that have occurred 145 | throughout U.S. 146 | \item \code{get_fars_summary} provides a count of injury severity that have occurred 147 | throughout U.S. including count of fatalities and crashes. 148 | \item \code{get_fars_year} provides one of 20 FARS data tables for a single year. 149 | Supports downloading to a CSV or JSON file. 150 | } 151 | 152 | Both \code{get_fars_crash_list} and \code{get_fars_crashes} limit the returned data 153 | to 5000 records so consider limiting the range of years requested if data 154 | exceeds that threshold. 155 | 156 | This package also enables access to the FARS data available through the 157 | NHTSA data downloads server in a zip format. Set \code{api} to "zip" or use the 158 | \code{get_fars_zip} function to download this data. 159 | } 160 | \examples{ 161 | 162 | head(get_fars_crashes(state = "MD", county = "Baltimore city"), 5) 163 | 164 | get_fars_cases(state = "MD", cases = "240274") 165 | 166 | get_fars_crash_list(state = "MD", vehicles = 5) 167 | 168 | get_fars_summary(state = "MD") 169 | 170 | head(get_fars_year(state = "MD", type = "PERSON"), 5) 171 | 172 | } 173 | -------------------------------------------------------------------------------- /man/get_fars_crash_persons.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/get_fars_crash_persons.R 3 | \name{get_fars_crash_persons} 4 | \alias{get_fars_crash_persons} 5 | \title{Get Crashes By Occupant} 6 | \usage{ 7 | get_fars_crash_persons( 8 | year = NULL, 9 | start_year, 10 | end_year = NULL, 11 | state, 12 | age = NULL, 13 | sex = NULL, 14 | seat, 15 | injury, 16 | occupants = TRUE, 17 | nonoccupants = TRUE 18 | ) 19 | } 20 | \arguments{ 21 | \item{year}{numeric vector. Year or range with start and end year. 2010 to 22 | 2022 supported.} 23 | 24 | \item{start_year}{Start year for crash reports.} 25 | 26 | \item{end_year}{End year for crash reports.} 27 | 28 | \item{state}{Required. State name, abbreviation, or FIPS number.} 29 | 30 | \item{age}{numeric} 31 | 32 | \item{sex}{Options "m", "f", "male", "female", "unknown", "not reported."} 33 | 34 | \item{seat}{Seat position} 35 | 36 | \item{injury}{Options "unknown", "not reported", "died prior", "injured", 37 | "fatal", "suspected serious", "suspected minor", "possible", "no apparent"} 38 | 39 | \item{occupants}{Include vehicle occupants in query; defaults to \code{TRUE}} 40 | 41 | \item{nonoccupants}{Include non-occupants in query; defaults to \code{TRUE}} 42 | } 43 | \description{ 44 | This function returns a list of fatal crashes by occupant that have occurred 45 | throughout United States. This function is not currently working. 46 | } 47 | -------------------------------------------------------------------------------- /man/get_fars_crash_vehicles.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/get_fars_crash_vehicles.R 3 | \name{get_fars_crash_vehicles} 4 | \alias{get_fars_crash_vehicles} 5 | \title{Get Crashes By Vehicle} 6 | \usage{ 7 | get_fars_crash_vehicles( 8 | year = NULL, 9 | start_year, 10 | end_year = NULL, 11 | state, 12 | make = NULL, 13 | model = NULL, 14 | model_year = 2010, 15 | body_type = NULL 16 | ) 17 | } 18 | \arguments{ 19 | \item{year}{numeric vector. Year or range with start and end year. 2010 to 20 | 2022 supported.} 21 | 22 | \item{start_year}{Start year for crash reports.} 23 | 24 | \item{end_year}{End year for crash reports.} 25 | 26 | \item{state}{Required. State name, abbreviation, or FIPS number.} 27 | 28 | \item{make}{Make name or ID, Required. The start_year is used to return a 29 | list of support make options. Default: \code{NULL}} 30 | 31 | \item{model}{Model name or ID, Optional. Default: \code{NULL}} 32 | 33 | \item{model_year}{Model year, Optional. Default: \code{NULL}} 34 | 35 | \item{body_type}{Body type, Optional. \code{model} must be provided to use 36 | body_type parameter. Default: \code{NULL}} 37 | } 38 | \description{ 39 | This function returns a list of fatal crashes by vehicle type 40 | that have occurred throughout United States. The make, model, and body type 41 | must match the options returned by \code{fars_vars}. This function accepts named 42 | options that are converted to ID numbers for use in the API query. 43 | } 44 | -------------------------------------------------------------------------------- /man/get_fars_zip.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/get_fars_zip.R 3 | \name{get_fars_zip} 4 | \alias{get_fars_zip} 5 | \title{Download FARS data files as zipped CSV or SAS files} 6 | \usage{ 7 | get_fars_zip( 8 | year = 2022, 9 | format = "csv", 10 | path = NULL, 11 | pr = FALSE, 12 | aux = FALSE, 13 | read = TRUE, 14 | geometry = FALSE, 15 | overwrite = FALSE 16 | ) 17 | } 18 | \arguments{ 19 | \item{year}{Year of data from 1975 to 2022, Default: 2022} 20 | 21 | \item{format}{Format of zipped data tables ('csv' or 'sas'). Default: 'csv'. 22 | unzip and geo options are only supported if format is "csv".} 23 | 24 | \item{path}{Path to download zip file. Set to \code{\link[=getwd]{getwd()}} if \code{NULL} (default).} 25 | 26 | \item{pr}{If \code{TRUE}, download FARS data for Puerto Rico. No Puerto Rico data 27 | available for years 1975-1977. Default: \code{FALSE}} 28 | 29 | \item{aux}{If \code{TRUE} and year is after 1982, download auxiliary 30 | FARS datasets that "contain data derived from the regular FARS/GES 31 | variables using NCSA analytical data classifications." In 2010, the NHTSA 32 | explained: "These classifications are widely used in NCSA publications and 33 | research. Many definitions such as "speeding-related" or "distracted 34 | driving" comprise a combination of variables whose names or attributes have 35 | changed over time. The derived variables in the auxiliary files incorporate 36 | these nuances, thus simplifying the use of standard classifications in any 37 | traffic safety research." Learn more from the FARS and GES Auxiliary 38 | Datasets Q & A: 39 | \url{https://crashstats.nhtsa.dot.gov/Api/Public/ViewPublication/811364}} 40 | 41 | \item{read}{If \code{TRUE}, unzip the downloaded file and read CSV files into a 42 | list of tables with each list item corresponding to one CSV file.} 43 | 44 | \item{geometry}{If \code{TRUE}, convert the accident table to a sf object.} 45 | 46 | \item{overwrite}{If \code{FALSE}, abort if file exists at the provided path. If 47 | \code{TRUE}, overwrite file.} 48 | } 49 | \value{ 50 | Downloads zip file with CSV or SAS tables and returns the zip file 51 | path invisibly or returns a list of data frames (if geometry is \code{FALSE}), 52 | or returns a list of data frames with the accident table converted to a sf 53 | object. 54 | } 55 | \description{ 56 | This function provides an alternative to \code{\link[=get_fars_year]{get_fars_year()}} that downloads 57 | files directly from NHTSA FTP site. If read is \code{TRUE}, the function reads a 58 | list containing data frames for each table available in the selected year. If 59 | geometry is \code{TRUE}, the accident table is converted to an sf object. 60 | } 61 | -------------------------------------------------------------------------------- /man/list_rbind.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{list_rbind} 4 | \alias{list_rbind} 5 | \title{Combine list elements into a single data structure} 6 | \usage{ 7 | list_rbind(x, ..., names_to = rlang::zap(), ptype = NULL) 8 | } 9 | \description{ 10 | \itemize{ 11 | \item \code{list_rbind()} combines elements into a data frame by row-binding them 12 | together with \code{\link[vctrs:vec_bind]{vctrs::vec_rbind()}}. 13 | } 14 | } 15 | \keyword{internal} 16 | -------------------------------------------------------------------------------- /man/mmucc_codes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{mmucc_codes} 5 | \alias{mmucc_codes} 6 | \title{Model Minimum Uniform Crash Criteria (MMUCC) codes (simple)} 7 | \format{ 8 | A data frame with 700 rows and 6 variables: 9 | \describe{ 10 | \item{\code{code}}{Attribute code} 11 | \item{\code{name}}{Attribute code name} 12 | \item{\code{type}}{Attribute code type} 13 | \item{\code{definition}}{Code definition} 14 | \item{\code{restriction_id}}{Restriction id number} 15 | \item{\code{restriction}}{Restriction value} 16 | } 17 | } 18 | \usage{ 19 | mmucc_codes 20 | } 21 | \description{ 22 | A collection of the 73 unique codes identified as simple codes: 23 | \url{https://release.niem.gov/niem/codes/mmucc/4.1/mmucc.xsd} 24 | 25 | See the MMUCC Guideline Fifth Edition (2017) for more information: 26 | \url{https://crashstats.nhtsa.dot.gov/Api/Public/Publication/812433} 27 | 28 | About MMUC from NHTSA: \url{https://www.nhtsa.gov/mmucc-1} 29 | 30 | To encourage greater uniformity, the National Highway Traffic Safety 31 | Administration (NHTSA) and the Governors Highway Safety Association (GHSA) 32 | cooperatively developed a voluntary data collection guideline in 1998. The 33 | MMUCC guideline identifies a minimum set of motor vehicle crash data elements 34 | and their attributes that States should consider collecting and including in 35 | their State crash data system. 36 | 37 | The MMUCC 5th Edition is the result of an 18-month collaboration between 38 | NHTSA, the Federal Highway Administration (FHWA), the Federal Motor Carrier 39 | Safety Administration (FMCSA), the National Transportation Safety Board 40 | (NTSB), the GHSA, and subject matter experts from State DOTs, local law 41 | enforcement, emergency medical services, safety organizations, industry 42 | partners, and academia. The traffic records community and general public also 43 | contributed through external forums (Federal Register) and at the 2016 44 | Traffic Records Forum. 45 | \itemize{ 46 | \item Added: March 26 2022 47 | \item Updated: March 26 2022 48 | } 49 | } 50 | \keyword{datasets} 51 | -------------------------------------------------------------------------------- /man/read_crashapi.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{read_crashapi} 4 | \alias{read_crashapi} 5 | \title{Read data from the CrashAPI using a url template} 6 | \usage{ 7 | read_crashapi( 8 | url = "https://crashviewer.nhtsa.dot.gov", 9 | data = "crashes", 10 | type = NULL, 11 | format = "json", 12 | results = TRUE, 13 | ..., 14 | call = caller_env() 15 | ) 16 | } 17 | \arguments{ 18 | \item{url}{Base url for CrashAPI.} 19 | 20 | \item{data}{Data (crashes, analytics, or fars), Default: 'crashes'} 21 | 22 | \item{type}{Type of API to use, Default: \code{NULL}} 23 | 24 | \item{format}{Format to return, Default: 'json'} 25 | 26 | \item{results}{If \code{FALSE}, return formatted url, Default: \code{TRUE}} 27 | 28 | \item{...}{Additional parameters used in template (varies by type).} 29 | 30 | \item{call}{The execution environment of a currently 31 | running function, e.g. \code{caller_env()}. The function will be 32 | mentioned in error messages as the source of the error. See the 33 | \code{call} argument of \code{\link[rlang:abort]{abort()}} for more information.} 34 | } 35 | \value{ 36 | Data frame with requested data or a formatted url (if \code{results = FALSE}) 37 | } 38 | \description{ 39 | An updated utility function using the httr2 package to read data from the 40 | CrashAPI using the API URL templates listed on the NHSTA website: 41 | \url{https://crashviewer.nhtsa.dot.gov/CrashAPI} 42 | } 43 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(crashapi) 3 | 4 | test_check("crashapi") 5 | -------------------------------------------------------------------------------- /tests/testthat/setup.R: -------------------------------------------------------------------------------- 1 | library(httptest2) 2 | -------------------------------------------------------------------------------- /tests/testthat/test-fars_vars.R: -------------------------------------------------------------------------------- 1 | test_that("fars_vars works", { 2 | with_mock_api({ 3 | expect_GET( 4 | fars_vars(year = 2010, var = "make") 5 | ) 6 | }) 7 | 8 | skip_if_offline() 9 | # Works with numeric years 10 | expect_s3_class(fars_vars(year = 2010, var = "make"), "data.frame") 11 | # Works with character years 12 | expect_s3_class(fars_vars(year = "2010"), "data.frame") 13 | # Does not work with years outside of API range 14 | expect_error(fars_vars(year = 2001), "must be greater than or equal to") 15 | # Does not work if var = model and make is not provided 16 | # expect_error(fars_vars(year = 2010, var = "model"), "Error in open.connection") 17 | # Works if var is model and a make ID number is provided 18 | expect_s3_class(fars_vars(year = 2010, var = "model", make = 54), "data.frame") 19 | # Works if var is bodytype and a make and model ID number are both provided 20 | expect_s3_class(fars_vars(year = 2010, var = "bodytype", make = 54, model = 37), "data.frame") 21 | }) 22 | -------------------------------------------------------------------------------- /tests/testthat/test-get_fars.R: -------------------------------------------------------------------------------- 1 | test_that("get_fars works", { 2 | with_mock_api({ 3 | expect_GET( 4 | get_fars(year = 2019, state = "MD", county = "Garrett County") 5 | ) 6 | expect_GET( 7 | get_fars(year = 2019, state = "MD", county = "Garrett County", cases = 240063) 8 | ) 9 | expect_GET( 10 | get_fars(year = 2019, state = "MD", county = "Garrett County", type = "ACCIDENT") 11 | ) 12 | }) 13 | 14 | expect_s3_class( 15 | get_fars(year = 2019, state = "MD", vehicles = 5), 16 | "data.frame" 17 | ) 18 | expect_s3_class( 19 | get_fars(year = 2019, state = "MD", county = "Garrett County"), 20 | "data.frame" 21 | ) 22 | expect_s3_class( 23 | get_fars(year = 2019, state = "MD", county = "Garrett County", details = TRUE), 24 | "data.frame" 25 | ) 26 | expect_s3_class( 27 | get_fars(year = 2019, state = "MD", county = "Garrett County", cases = 240063), 28 | "data.frame" 29 | ) 30 | expect_s3_class( 31 | get_fars(year = 2019, state = "MD", county = "Garrett County", type = "ACCIDENT"), 32 | "data.frame" 33 | ) 34 | expect_s3_class( 35 | get_fars(year = 2019, state = "MD", api = "summary count"), 36 | "data.frame" 37 | ) 38 | expect_s3_class( 39 | get_fars(year = 2019, state = "MD", api = "state list", vehicles = 1), 40 | "data.frame" 41 | ) 42 | }) 43 | 44 | test_that("get_fars warns and errors", { 45 | expect_warning( 46 | get_fars_crashes(year = 2022, state = "RI", county = "Bristol County"), 47 | "No records found with the provided parameters." 48 | ) 49 | expect_message( 50 | get_fars_crashes(year = c(2010, 2020), state = "California", county = "Los Angeles"), 51 | "Additional records may be available for this query." 52 | ) 53 | expect_error(get_fars(year = 2000), "must be greater than or equal to") 54 | expect_error(get_fars(year = 2019, state = "MD", api = "crashes"), "must be a valid county name or FIPS code") 55 | }) 56 | 57 | test_that("get_cases works", { 58 | # Works with character and numeric inputs 59 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = "240063"), "data.frame") 60 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = 240063), "data.frame") 61 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = 240063, details = "events"), "data.frame") 62 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = 240063, details = "vehicles"), "data.frame") 63 | 64 | skip_if_not_installed("sf") 65 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = "240063", geometry = TRUE), "sf") 66 | }) 67 | 68 | test_that("get_cases errors", { 69 | expect_error(get_fars_cases(year = 2019, state = "MD", cases = "0"), "subscript out of bounds") 70 | expect_error(get_fars_cases(year = 2019, state = "MD")) 71 | }) 72 | 73 | test_that("get_cases works", { 74 | # Works with character and numeric inputs 75 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = "240063"), "data.frame") 76 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = 240063), "data.frame") 77 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = 240063, details = "events"), "data.frame") 78 | expect_s3_class(get_fars_cases(year = 2019, state = "MD", cases = 240063, details = "vehicles"), "data.frame") 79 | 80 | skip_if_not_installed("sf") 81 | expect_s3_class(get_fars_crashes(year = 2022, state = "MD", county = "Garrett", geometry = TRUE), "sf") 82 | }) 83 | -------------------------------------------------------------------------------- /tests/testthat/test-get_fars_crash_vehicles.R: -------------------------------------------------------------------------------- 1 | test_that("get_fars_crash_vehicles works", { 2 | expect_s3_class( 3 | get_fars_crash_vehicles( 4 | year = 2019, 5 | state = "CA", 6 | make = "12", 7 | model = "481", 8 | body_type = "34", 9 | model_year = 2018 10 | ), 11 | "data.frame" 12 | ) 13 | }) 14 | -------------------------------------------------------------------------------- /tests/testthat/test-get_fars_year.R: -------------------------------------------------------------------------------- 1 | test_that("get_fars_year works", { 2 | expect_s3_class(get_fars_year(year = 2022, state = "VT", format = "csv"), "data.frame") 3 | expect_s3_class(get_fars_year(year = c(2019, 2020), state = "VT"), "data.frame") 4 | expect_error(get_fars_year(year = c(2019, 2020), state = "VT", type = "XYZ"), "'arg' should be one of") 5 | expect_error(get_fars_year(year = c(2017, 2018), state = "VT", type = "NMDISTRACT"), "'arg' should be one of") 6 | expect_s3_class(get_fars_year(year = 2019, state = "VT", type = "NMDISTRACT"), "data.frame") 7 | expect_warning(get_fars_year(year = 2019, state = "VT", type = "NMDISTRACT", geometry = TRUE), "Coordinate columns LONGITUD and LATITUDE can't be found") 8 | expect_s3_class(get_fars_year(year = 2019, state = "VT", type = "accident", geometry = TRUE), "sf") 9 | }) 10 | -------------------------------------------------------------------------------- /tests/testthat/test-get_fars_zip.R: -------------------------------------------------------------------------------- 1 | test_that("get_fars_zip works", { 2 | expect_true( 3 | file.exists( 4 | get_fars_zip( 5 | year = 1978, 6 | read = FALSE, 7 | path = tempdir(), 8 | overwrite = TRUE 9 | ) 10 | ) 11 | ) 12 | data <- 13 | suppressWarnings( 14 | get_fars_zip( 15 | year = 1978, 16 | read = TRUE, 17 | path = tempdir(), 18 | overwrite = TRUE 19 | ) 20 | ) 21 | expect_type( 22 | data, 23 | "list" 24 | ) 25 | expect_identical( 26 | names(data), 27 | c("accident", "person", "vehicle") 28 | ) 29 | }) 30 | -------------------------------------------------------------------------------- /tests/testthat/test-tigris-utils.R: -------------------------------------------------------------------------------- 1 | test_that("Test lookup_fips outputs", { 2 | expect_identical(lookup_fips(state = "MD"), 24L) 3 | expect_identical(lookup_fips(state = "MD", county = "Baltimore city"), 510L) 4 | expect_type( 5 | lookup_fips(state = "MD", county = "Baltimore city", list = TRUE), 6 | "list" 7 | ) 8 | expect_type( 9 | lookup_fips(state = "MD", int = FALSE), 10 | "character" 11 | ) 12 | expect_warning( 13 | lookup_fips(state = "XX"), 14 | "not a valid FIPS code or state name/abbreviation" 15 | ) 16 | }) 17 | 18 | test_that("validate_state and validate_county works", { 19 | expect_type(validate_state("MD", .msg = FALSE), "character") 20 | expect_type(validate_county("MD", "Garrett", .msg = FALSE), "character") 21 | expect_warning( 22 | validate_county("DC", "Garrett", .msg = FALSE), 23 | "'Garrett' is not a valid name for counties in District of Columbia" 24 | ) 25 | }) 26 | --------------------------------------------------------------------------------