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.
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/reference/format_crashes.html:
--------------------------------------------------------------------------------
1 |
2 | Format crash data — format_crashes • crashapi
10 | Skip to contents
11 |
12 |
13 |
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 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/docs/reference/crashapi-package.html:
--------------------------------------------------------------------------------
1 |
2 | crashapi: CrashAPI — crashapi-package • crashapi
6 | Skip to contents
7 |
8 |
9 |
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.
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)
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 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
--------------------------------------------------------------------------------
/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 | [](https://CRAN.R-project.org/package=crashapi)
20 | [](https://lifecycle.r-lib.org/articles/stages.html#experimental)
21 | [](https://opensource.org/licenses/MIT)
22 | [](https://app.codecov.io/gh/elipousson/crashapi?branch=main)
23 | [](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 |
--------------------------------------------------------------------------------
/docs/reference/fars_vars_labels.html:
--------------------------------------------------------------------------------
1 |
2 | FARS variable names and labels — fars_vars_labels • crashapi
10 | Skip to contents
11 |
12 |
13 |
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
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.
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 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
--------------------------------------------------------------------------------
/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 |
49 |
Download FARS data files as zipped CSV or SAS files
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.
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.