Accessing Census data via API

R Users Group

March 2, 2016

Getting started - request an API key

http://api.census.gov/data/key_signup.html

Save this email!

How do we access Census data?

Application

Program

Interface

APIs are sets of requirements that govern how one application can talk to another - readwrite.com

http://api.census.gov/data/2014/acs5?get=NAME,B01001_001E,B19013_001E&for=county:*

Over 100 available Census APIs

API pros

  • Get data directly from source
  • Fully reproducible
  • Retrieve lots of data at once
  • Read data directly into R - no export/import
  • Don't need to save files locally

Cons

  • Requires an Internet connection
  • Need to understand Census geographies and variables

R can do everything for you besides reading the documentation

(But some functions can help with that)

Getting that web response into R

Install censusapi package


install.packages("devtools")
devtools::install_github("hrecht/censusapi")

# Load the library
library("censusapi")
                

getCensus function required arguments:

1. name


"acs5"
                

2. vintage - required for all datasets besides time series


2014
                

3. key
string emailed by Census

4. vars


c("NAME", "B01001_001E", "B19013_001E", "B17010_017E", "B17010_037E")
                

5. region


"county:*"
                

How do we get information about those arguments?

METADATA

Arguments: name and vintage

http://api.census.gov/data.html

apis <- listCensusApis()
View(apis)

Argument: variables


vars2014 <- listCensusMetadata(name="acs5", vintage=2014, "v")
View(vars2014)

Argument: geography


geos2014 <- listCensusMetadata(name="acs5", vintage=2014, "g")
View(geos2014)

Putting it all together...


data2014 <- getCensus(name="acs5", 
    vintage=2014,
    key=censuskey, 
    vars=c("NAME", "B01001_001E", "B19013_001E",
    "B17010_017E", "B17010_037E"), 
    region="county:*")
View(data2014)
                

Code!

Questions?

More government APIs!

https://api.data.gov/

Advanced geography

region + regionin


data2000 <- getCensus(name="sf3", vintage=2000, 
key=censuskey, 
vars=c("P001001", "P053001", "H063001"), 
region="county:*", regionin="state:06")

Advanced geography

Looping over a list of states


tracts <- NULL
# For all states in the fips list
for (f in fips) {
    # Define what state to get
    stateget <- paste("state:", f, sep="")
    # Get data for all tracts within that state
    temp <- getCensus(name="acs5", vintage=2014, 
    key=censuskey, 
    vars=c("B01001_001E", "B19013_001E", "B17010_017E", "B17010_037E"), 
    region="tract:*", regionin=stateget)
    # Bind to existing data
    tracts <- rbind(tracts, temp)
}
View(tracts)

Especially useful for tracts and blocks - can only get one state at a time