Skip to content

Instantly share code, notes, and snippets.

@benjamin-chan
Last active September 23, 2020 19:26
Show Gist options
  • Save benjamin-chan/efc0eea12c28fac10c14456a5ce43faf to your computer and use it in GitHub Desktop.
Save benjamin-chan/efc0eea12c28fac10c14456a5ce43faf to your computer and use it in GitHub Desktop.
Example R snippet to wrangle US Census data via API
library(magrittr)
library(readr)
library(tidyr)
library(censusapi)
name <- "acs/acs5" # See https://api.census.gov/data.html for list of tables for the name argument for listCensusMetadata()
vintage <- 2012
metadata <-
listCensusMetadata(name = name, vintage = vintage) %>%
select(name, label) %>%
filter(grepl("^B01003", name))
key <- read_csv("C:/Users/or0250652/Documents/API keys/censusAPIKey.txt", col_names = FALSE) %>% pull(X1)
zcta5 <-
getCensus(name, vintage, var = metadata$name, region = "zip code tabulation area", key = key) %>%
pivot_longer(matches("\\d{5}"), values_to = "total") %>%
rename(zcta5 = zip_code_tabulation_area) %>%
mutate(vintage = vintage)
zcta3 <-
zcta5 %>%
mutate(zcta3 = substr(zcta5, 1, 3)) %>%
group_by(vintage, zcta3) %>%
summarize(total = sum(total, na.rm = TRUE)) %>%
ungroup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment