8. Data Retrieval
Self-Paced Workshop #8
Asking for the Data Instead of Downloading It
Every dataset so far this semester arrived as a file: you downloaded it, put it in a folder, and pointed a file read command (read_csv() or read_dta()) at it. This read it from your file system into working memory so you could manipulate, analyze, and visualize it.
This week, we looked at a second way to get data into working memory. A package can fetch the data for you, straight from the organization that publishes it, so the script itself says exactly where the data came from and anyone who runs it gets the same thing. No filesystem to worry about, no data to download manually, no file to email, no “which version did I download and where did I put it?” This process is both more reproducible and easier - win/win.
This workshop works through the two examples from lecture:
- The General Social Survey, with Kieran Healy’s
gssrpackage (and its companiongssrdoc), which packages the whole cumulative GSS file — the same one you used for Problem Set 6 — inside R. - The US Census, with Kyle Walker’s
tidycensuspackage, which sends your request to the Census Bureau’s servers and hands back a tidy table.
Part 1, the GSS, runs in the browser, with one exception at the end. Part 2, the Census, does not: tidycensus has to reach the Census Bureau over the internet with your own key, which the in-browser R cannot do. For Part 2, open RStudio or Positron, start a new .R script, and copy each block into it as you go (the copy icon is in the top-right corner of each block). You must get your Census key in order to do this (see below).
- Get a Census API key now if you have not already: sign up here. It arrives by email, usually within a few minutes, and has to be activated from the link in that email. You need it for Part 2.
- Give the page a moment.
gssris a 30 MB download, because the data is inside the package, so the first box takes several seconds longer than usual (and longer if you are on a slow connection). - As usual, the boxes on this page share one R session; run them top to bottom or you’ll run into errors.
Part 2. The Census with tidycensus
The Census is a different kind of thing. It is not one file you could put in a package; it is thousands of tables, at every level of geography from the nation down to the city block, for many years and several surveys. The Census Bureau serves all of it through an API — a web address that answers requests for data — and tidycensus writes the requests for you.
Everything from here on needs your key and a live connection to the Census Bureau, which the browser cannot provide, so open up RStudio or Positron and work alongside this page.
Step 7. Install, and store your API key, once
tidycensus is on CRAN. In the console:
install.packages("tidycensus")The API wants your key with every request. Give it to tidycensus once, also in the console:
library(tidycensus)
census_api_key("PASTE YOUR KEY HERE", install = TRUE)
readRenviron("~/.Renviron")install = TRUE saves the key in a settings file in your home folder (.Renviron), which R reads every time it starts. From now on tidycensus finds it on its own, and your scripts never contain the key. That matters: a key in a script ends up on GitHub the first time you push, and a published key is one anyone can use under your name.4 Run this in the console, not your script, for the same reason.
Step 8. A first request: median age by state
age20 <- get_decennial(geography = "state",
variables = "P13_001N",
year = 2020,
sumfile = "dhc") # demographic and housing file
head(age20)Each argument is one part of the request:
| Argument | Says | Here |
|---|---|---|
geography |
which units, one row each | the 50 states, DC and Puerto Rico |
variables |
which numbers, by the Census Bureau’s code | P13_001N, median age |
year |
which census | 2020 |
sumfile |
which collection of tables from that census | the Demographic and Housing Characteristics file |
The result is a tibble with four columns: GEOID (the state’s FIPS code), NAME, variable, and value. Connecticut’s median age is 41.1; DC’s is 33.9.
Step 9. Graph it
The data comes back clean, so it goes straight into ggplot():
age20 |>
ggplot(aes(x = value, y = reorder(NAME, value))) +
geom_point()A dot plot, one row per state. reorder(NAME, value) sorts the states by their median age instead of alphabetically, which is what turns fifty-odd labels into something readable.
Try it yourself: finish the graph the way Workshop 7 ended — axis labels in words, a title that states the finding, a caption naming the source, a theme.
Step 10. Finding variable codes
Nobody remembers that P13_001N is median age. load_variables() downloads the full list of variables for a census and file — in effect, the codebook — into a tibble you can search:
vars <- load_variables(2020, "dhc", cache = TRUE)
varscache = TRUE saves a copy so the next call is instant. The name column is the code; label and concept describe it. Search the concepts with str_detect() from stringr (part of the tidyverse); regex(..., ignore_case = TRUE) matches regardless of capitals:
vars |>
filter(str_detect(concept, regex("population", ignore_case = TRUE))) |>
View()View() opens the result as a spreadsheet you can scroll and filter. Find P1_001N, total population.
Try it yourself: search the concepts for "median age", and confirm P13_001N is what Step 8 said it was. Then search for "race".
Step 11. Total population, with readable axis labels
totalpop <- get_decennial(geography = "state",
variables = "P1_001N",
year = 2020,
sumfile = "dhc")
totalpop |>
ggplot(aes(x = value, y = reorder(NAME, value))) +
geom_point() +
scale_x_continuous(
breaks = c(10000000, 20000000, 30000000, 40000000),
labels = c("10m", "20m", "30m", "40m"))Without the scale_x_continuous() line the axis reads 1e+07, 2e+07… in scientific notation. Writing the breaks and labels by hand works; the scales package can also do it for you, which keeps working if the data changes. Swap this in for the scale_x_continuous() line above:
scale_x_continuous(labels = scales::label_number(scale = 1e-6, suffix = "m"))Step 12. A ratio: two variables, wide
Counts are rarely the point. Usually you want a share, which means two variables — a part and a total — in one request. Name them as you ask, and ask for the table wide:
pop <- get_decennial(geography = "state",
variables = c(total = "P1_001N",
asian = "P3_005N"),
year = 2020,
sumfile = "dhc",
output = "wide") # without this, it comes back long
pop <- pop |>
mutate(asian_share = asian / total)
pop |>
ggplot(aes(x = asian_share, y = reorder(NAME, asian_share))) +
geom_point()Two things happened in the request. The names in c(total = ..., asian = ...) became the column names, instead of the codes. And output = "wide" put the two variables side by side, one row per state, so mutate() can divide one by the other. Without it you get the long shape from Step 8 — two rows per state, one per variable — which is tidy, but needs a pivot_wider() before you can do arithmetic across variables.
P3_005N is “Asian alone” from table P3, Race, which counts everyone.5 Checking a code against its label before you trust it is the single most useful habit with Census data; the codes are close together and one digit changes the meaning entirely.
Try it yourself: look up P3_005N and P10_007N in vars to see the difference. Then change the request to the share Black or African American alone (also in table P3) and redraw the graph.
Step 13. Smaller geography
The same call works at every level of geography; smaller units usually need a state (and sometimes a county) to say which ones. Median age for every county in New York:
ny_age <- get_decennial(geography = "county",
state = "NY",
variables = "P13_001N",
year = 2020,
sumfile = "dhc")
ny_age |>
ggplot(aes(x = value, y = reorder(NAME, value))) +
geom_point()Sixty-two counties, from the five boroughs of New York City to Hamilton County in the Adirondacks. Find Onondaga. The labels all end in “, New York”; str_remove(NAME, " County, New York") inside a mutate() cleans them up.
Try it yourself: change geography to "tract" and add county = "Onondaga" for every census tract in the county — well over a hundred rows, from the same one call.
A Practical Word
You could get every number on this page without code. The Census Bureau’s data.census.gov will build and download the same tables, and the GSS is a file you already know how to open. So why bother with all this?
Two reasons:
Simplicity: This is actually easier once you get used to it! No filesystem, no file downloads, less local management. Easier is better!
Reproducibility: The script is now a more complete record. The goal of all analysis is to move from original source files to output in a fully documented way, and a manual file download broke - or at least complicated - that chain. A file downloaded from a website carries no memory of which table, which year, which geography, or which file you clicked; a
get_decennial()call carries all four, and re-running it next year — or handing it to someone else — reproduces the data exactly. For the GSS the gain is mostly convenience. For the Census, which is too large and too finely divided to keep a copy of, a scripted request is essentially the only sensible way to work.
Work on Your Own
Two packages, one idea: ask the source for exactly the rows and columns you need, and let the script document the request. For more, the gssr site has a longer tour of the GSS data, and Kyle Walker’s free book Analyzing US Census Data covers tidycensus in depth — in particular, look at chapter 2, which covers both the decennial census you used here and get_acs() for the American Community Survey, which is where most current Census data lives.
Footnotes
This is an unweighted share, which is fine for a first look. For a published estimate you would weight it, as in Workshop 5; the GSS weight for all years is
wtssps, which is ingss_sub. Trysummarise(agree = weighted.mean(fefam <= 2, wtssps)).↩︎This is the same rule as
install.packages("tidyverse")back in Week 1: a script that reinstalls packages every time it runs is slow, and rude to anyone else who runs it. Put thelibrary()lines in the script, and the installs nowhere.↩︎If you have 16 GB or more of RAM, this is probably less of an issue. If your computer struggles, or as a habit regardless,
select()the handful of variables you need into a new, smaller object straight away (gss_small <- gss_all |> select(year, id, wrkstat, industry)) and thenrm(gss_all)to free the memory.↩︎If you ever do push a key by accident, deleting it in the next commit does not help — it is still in the history. Request a new key and stop using the old one.↩︎
The lecture slide used
P10_007N. Look it up invars: table P10 is Race for the population 18 years and over, and its row 7 is Native Hawaiian and Other Pacific Islander alone. Divided by total population, it is neither the right group nor the right denominator, and the graph would have looked perfectly reasonable anyway.↩︎