19-apis

Author
Affiliation

Prof Amanda Luby

Carleton College
Stat 220 - Spring 2025

TidyCensus

Install tidycensus if not on maize:

install.packages("tidycensus")

Example call:

acs_mn_2020 <- tidycensus::get_acs(
    year = 2020,
    state = "MN",
    geography = "county",
    variables = c("B01003_001", "B19013_001"),
    output = "wide",
    geometry = TRUE
)

Storing your API key

  1. Create a new text file in the same folder as your .rmd
  2. Copy and paste your census key into the empty file
  3. Save the file as census_api_key.txt
my_key <- readLines("census_api_key.txt")

and tell tidycensus what your API key is with:

Do not commit and push census_api_key.txt to github

acs_mn_2020 |>
  mutate(
    name = str_remove(NAME, ", Minnesota"),
    name = str_remove(name, " County")
  ) |> 
  ggplot(aes(x = B19013_001E, 
                          xmin = B19013_001E - B19013_001M, 
                          xmax = B19013_001E + B19013_001M, 
                          y = fct_reorder(name, B19013_001E))) + 
  geom_point() + 
  geom_errorbarh() + 
  labs(
    x = "",
    y = ""
  )

Your turn

  • Search for two new variables using load_variables (Can you explain what they are?)
  • Run another call to tidycensus::get_acs using your two variables

httr2

Install if not already installed:

Example call

hmong_state_request <- request("https://api.census.gov/data") %>% 
    req_url_path_append("2019") %>% 
    req_url_path_append("acs") %>% 
    req_url_path_append("acs1") %>% 
    req_url_query(get = c("NAME", "B02015_009E", "B02015_009M"), `for` = I("state:*"), key = census_api_key, .multi = "comma")
hmong_state_response <- req_perform(hmong_state_request)
hmong_state_tbl <- hmong_state_response %>%
  resp_body_json(simplifyVector = TRUE) %>%
  janitor::row_to_names(1) %>%
  as_tibble()

hmong_state_tbl

Your Turn

  • Edit the httr code to access a new variable of your choice
  • Make a httr request to access the 1-year ACS data from 2018, 2019, 2021, and 2022. Make sure to save your results from each call!
  • Combine all years into a single dataset
  • Make a time series plot with your chosen variable on the y-axis, year on the x-axis, colored by state.
    • You may want to first filter to only a few states
    • You will need to do some cleaning of the data