# For Github readme, do the following (delete as you go):
# 1. Save as readme.Rmd in project root directory 
# 2. Change date manually
# 3. Change output to: github_document
# 4. Delete Vignette: info
# 5. Change path (add vignettes/) in send_query (line 102) & image (line 255)
# 6. Knit twice, with fig.path = docs/articles and then articles/
# DON'T MAKE ANY CHANGES -- edit vignettes/IntroVignette.Rmd instead
knitr::opts_chunk$set(fig.width = 4, fig.height = 3,
                      fig.align = 'center')
library(tidyverse)
library(wonderapi)

Overview

This package makes it easier to use the CDC WONDER API: 1) users can write simple queries using human readable names rather than numeric codes, and 2) users receive data in a tidy data frame that is easy to work with.

NOTE, HOWEVER, THAT THE CDC DOES NOT ALLOW QUERIES WITH LOCATION FIELDS THROUGH THE API. If you wish to limit or group results by Region, Division, State or County, or Urbanization, use the CDC Wonder web interface rather than the API -- either with or without this package. For more information on this limitation, see: https://wonder.cdc.gov/wonder/help/WONDER-API.html.

Installation

This package is not on CRAN. It can be installed from Github with the remotes package:

remotes::install_github("socdataR/wonderapi", build_vignettes = TRUE)

(If you have trouble installing the vignettes, or prefer not to, you can access them on the package website under the Articles tab instead.)

Main functions

send_query() -- takes as input an .xml file exported from the CDC Wonder web interface

getData() -- takes as input an R list of query options

show_databases() displays available databases by name and code:

wonderapi::show_databases()

(Applies only to getData(). Any database can be used with send_query().)

More databases will be added in the future.

The best way to become familiar with CDC WONDER API options is to use the CDC WONDER web interface, as the options available through the API are nearly identical (except for the location variable limitation -- see above).

Getting started with send_query()

This function requires an .xml query request file. To obtain this file, create a query on CDC WONDER. Before clicking "Send", uncheck the "Show totals" button at the bottom, and take note of the database code starting with "D" at the end of the URL.

After sending the query, click the "API Options" tab and then the "Export API" button to download the query .xml.

Once you have this file, you can use it with the send_query() function:

send_query("D76", "Underlying Cause of Death, 1999-2020_1710519087439-req.xml")

Getting started with getData()

Queries are composed of parameter name-value pairs:

mylist <- list(list("And By", "Gender"))
mydata0 <- getData("Detailed Mortality", mylist)
head(mydata0)

Codebooks

Codebooks are provided as package vignettes to allow the user to conveniently look up the names and values of available parameters in each dataset. They may be accessed quickly by typing:

> ??codebook

in the console, or searching for "codebook" in the Help window. They are also available under the "Articles" tab of the package website.

The codebooks are an important contribution of the package and are not provided by the CDC. They are generated automatically by this script, which scrapes the CDC WONDER web interface form, and displays parameter names and values in human readable form. The benefit of this method is the ability to quickly produce and update codebook vignettes that closely follow the web interface, with parameters appearing in the same order. It also means, however, that the codebooks contain more information than the typical user needs to submit a query. Most users will only need Group By variables (codes beginning with "B_"), Measures (codes beginning with "M_"), and Limiting Variables (codes beginning with "V_").

Although some of the parameter names are long and/or awkward, for the sake of consistency, we follow the CDC names exactly. The only exception is that any content that appears in parentheses should be dropped. For example, "Fertility Rate" can be substituted for "M_5", but "Fertility Rate (Census Region, Census Division, HHS Region, State, County, Year, Age of Mother, Race) cannot.

Default query lists and requests

To facilitate the process of designing a query list, this package relies on default query lists. Each default query is set to request a single Group By Results parameter, generally set to "Year". It is set to request the Measures that are listed as default Measures on the web interface (i.e. Births for the Births dataset; Deaths, Population and Crude Rate for the Detailed Mortality dataset.) To see the default settings, perform a query request without specifying a querylist:

natdata <- getData("Natality for 2007 - 2022")
head(natdata)
dmdata <- getData("Detailed Mortality")
head(dmdata)

The default lists were prepared based on CDC examples, but we make no claim that they are error free. If you have any suggestions for improving them, please make a pull request on Github or open an issue. The default lists are available in the /data-raw folder.

Creating customized queries

There are different types of parameters. Most critical are Group Results By and Measures. The Group Results By parameters serve as keys for grouping the data; the maximum number of Group Results By parameters is five. Limiting Variables may also be used to constrain results behind the scenes.

To make changes to the default list, first create a list of lists, wherein each nested list is a name-value pair. For example, the following changes the first (and currently only) "Group Results By" variable to Weekday:

mylist <- list(list("Group Results By", "Weekday"))
mydata <- getData("Detailed Mortality", mylist)
head(mydata)

As the set up is slightly different depending on the parameter type, more details on setting up the name-value pairs by parameter types are provided below.

Group By variables

Each dataset allows for fixed number (5 or fewer) Group By variables, codes for which are "B_1", "B_2", "B_3", etc. "Group By Results" may be substituted for "B_1" and "And By" for "B_2". "And By" may not, however, be substituted for "B_3" on to avoid ambiguity (this may change in the future.) Values -- in this case, the Group By variables -- may be specified by code or human readable name. The following, thus, are equivalent:

## not run
mylist <- list(list("B_1", "D66.V2"))
mylist <- list(list("Group Results By", "Race"))
mylist <- list(list("B_1", "Race"))
mylist <- list(list("Group Results By", "D66.V2"))

See the appropriate codebook for all Group By options.

Measures

Measures do not need values; it is sufficient to specify a name only:

mylist <- list(list("Group Results By", "Marital Status"),
               list("And By", "Year"),
               list("Average Age of Mother", ""))
mydata2 <- getData("Natality for 2007 - 2022", mylist)
head(mydata2)

Limiting variables

Queries can be constrained with parameters that limit results in the background. For example, if you're only interested in February births, you may choose to limit results to February as follows, rather than grouping by Month:

mylist <- list(list("Month", "2"))
getData("D66", mylist)

Note that values for Limiting Variables must be entered as codes; in this case "2" rather than "February." We hope to add capability for human readable values in the future.

Plotting query results

By returning a tidy data frame, the query results are ready to be plotted without any additional data manipulation:

ggplot(mydata2, aes(x = Year, y = Births, color = `Marital Status`)) +
  geom_line() +
  labs(title = "Births by Marital Status")
ggplot(mydata2, aes(x = Year, y = `Average Age of Mother`, color = `Marital Status`)) +
  geom_line() +
  geom_point() +
  labs(title = "Average Age of Mother", y = "age (in years)")
mydata2 <- mydata2 |> 
    select(-`Average Age of Mother`) |> 
    spread(key = `Marital Status`, value = `Births`) |> 
    mutate(Total = Married + Unmarried)
ggplot(mydata2, aes(x = Year, y = Unmarried / Total)) +
  geom_line() +
  geom_point() +
  labs(title = "Births to Unmarried Mothers",
       y = "Percent of Total Births")

Combining results from multiple datasets

Some of the datasets, such as the Births, are divided into multiple databases by time period. wonderapi makes it easy to combine the data into one data frame. (Care needs to be taken as the variables are not identical in all. For example, the 1995 - 2002 dataset does not have any measure options; it only returns number of births. To find out what's available, see the codebooks (>??codebook) and crosscheck with the CDC Wonder web interface.)

births <- rbind(getData("Natality for 1995 - 2002"),
                getData("Natality for 2003 - 2006"),
                getData("Natality for 2007 - 2022"))
ggplot(births, aes(Year, Births)) +
  geom_line() +
  labs(title = "U.S. Births by Year, 1995 - 2022")

Errors

The main source of errors is improper query requests. The wonderapi package has some ability to catch problems before the query request is made but will not catch everything. It checks the list of parameter names and will reject the name-value pair if the name, either in code or human readable form, is not recognized or is a geographic variable not accessible through the API without permission. (Checking for value problems will be added in the future.) Here is an example of an unrecognized parameter name:

mydata3 <- getData("Detailed Mortality", 
        list(list("Suspect", "Mrs. Peacock")))
head(mydata3)

If the CDC WONDER API returns an error, the message in the response will be displayed. Sometimes the message will provide enough information to fix the problem. Other times, it is not. For example:

mylist <- list(list("And By", "Education"), 
               list("Birth Rate", ""))
mydata4 <- getData("Natality for 2007 - 2022", mylist)

In this case, the best approach is to visit CDC WONDER and try the same query. If all goes well, you will receive more detailed information on what went wrong:

We learn that we can't include "Education" if we request the "Birth Rate" measure. If we try again with "Bridged Race" instead of "Education", it works:

mylist <- list(list("And By", "Mother's Bridged Race"), 
               list("Birth Rate", ""))
mydata5 <- getData("Natality for 2007 - 2022", mylist)
head(mydata5)


socdataR/natality documentation built on March 20, 2024, 8:40 p.m.