install.packages("tidycensus")
19-apis
TidyCensus
Install tidycensus
if not on maize:
Example call:
Storing your API key
- Create a new text file in the same folder as your .rmd
- Copy and paste your census key into the empty file
- Save the file as
census_api_key.txt
my_key <- readLines("census_api_key.txt")
and tell tidycensus
what your API key is with:
census_api_key(my_key)
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 = ""
)
Links to more info about census
https://www.census.gov/acs/www/data/data-tables-and-tools/subject-tables/
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:
install.packages("httr2")
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 thex-axis
, colored bystate.
- You may want to first filter to only a few states
- You will need to do some cleaning of the data