0

I need to get multiple years from the American Community Survey (ACS). For this, I created and activated the API key from the census website (https://api.census.gov/data/key_signup.html).

My issue is that I'm able to use the key, sometimes. However, sometimes I run the API key in R and I got the same error over and over again.

I have tried in 4 ways to get over this error, but nothing seems to work:

library(tidyverse)
library(tidycensus)
library(sf)
library(ggsflabel)
library(scales)

#First option
census_api_key("xxxxxxxxxxxxxxxx", install = TRUE,overwrite=TRUE)

#Second option
census_api_key("xxxxxxxxxxxxxxxx")
readRenviron("~/.Renviron")

#Third option
api.key.install("xxxxxxxxxxxxxxxx", file = "key.rda")

#Fourth option
api.key.install("", file = "key.rda")

This is the error I'm having with all of the possibilities I tried:

"Error: You have supplied an invalid or inactive API key. To obtain a valid API key, visit https://api.census.gov/data/key_signup.html. To activate your key, be sure to click the link provided to you in the email from the Census Bureau that contained your key."

My final goal is to be able to run the following code from this blog (https://mattherman.info/blog/tidycensus-mult-year/):

# define years using purrr::lst to automatically creates a named list
# which will help later when we combine the results in a single tibble
years <- lst(2012, 2017) 

# which counties?
my_counties <- c(
  "Alameda",
  "Contra Costa",
  "Marin",
  "Napa",
  "San Francisco",
  "San Mateo",
  "Santa Clara",
  "Solano",
  "Sonoma"
  )

# which census variables?
my_vars <- c(
  total_pop = "B01003_001",
  median_income = "B19013_001"
  )

# loop over list of years and get 1 year acs estimates
bay_area_multi_year <- map_dfr(
  years,
  ~ get_acs(
      geography = "county",
      variables = my_vars,
      state = "CA",
      county = my_counties,
      year = .x,
      survey = "acs1",
      geometry = FALSE
      ),
  .id = "year"  # when combining results, add id var (name of list item)
  ) %>%
  select(-moe) %>%  # shhhh
  arrange(variable, NAME) %>% 
  print()

But of course, the "get_acs" requires the API key use, which is the one who is giving the error issue. Does anyone know how to get rid of this API key issue?

If you have any suggestions, I would greatly appreciate it.

1 Answers1

0

I just learnt that the right way of using the API key from the Census bureau is:

  1. Install only once the API key:
#census_api_key("xxxxxxxxxxxxxx", overwrite = TRUE, install = TRUE)
  1. Reload R environment:
readRenviron("~/.Renviron")
  1. Check if the API key is ready to use:
Sys.getenv("CENSUS_API_KEY")

The API key is ready to use now every time we open up a new R session. So we don't need to do these steps over again.