The whole future of the US census has been coming under scrutiny recently, but, thankfully, we are getting more tools to scrutinise both its decennial data and that of its sister-source, the American Community service (ACS).
Specifically, Kyle Walker’s tidycensus and tigris packages which return data-frames (including shape-files as list-columns, if required) from the census API and Edzer Pebesma’s sf, simple features, package
Setup
Let’s first load the required libraries
library(tidycensus)
library(tigris)
library(sf)
#data carpentry
library(tidyverse)
library(stringr)
# maps
library(leaflet)
# tables
library(DT)
# plots
library(plotly)
A census API key is required to access the data. I have a hidden key in this post but if you want to do your own analyses, you will want to obtain one and probably save in .Renviron so that it will work automatically henceforth
For speed of interaction, I have downloaded shapefiles using the states()
, counties()
and tracts()
functions and tables which show what variables are available. Check the tigris documentation for details and options
#Enter here and uncomment
#census_api_key("xxxx")
# ensures shapefiles are downloaded by default
options(tigris_class = "sf")
#
#options(tigris_use_cache = TRUE)
# previosly downloaded
states <- readRDS("data/usCensus/states_sf.rds")
counties <- readRDS("data/usCensus/counties_sf.rds")
tracts <- readRDS("data/usCensus/tracts_sf.rds")
censusVars <- readRDS("data/usCensus/censusVars.rds")
acsVars <- readRDS("data/usCensus/acsVars.rds")
Lets show the downloadable tables
censusVars %>%
DT::datatable(height=800,class='compact stripe hover row-border order-column',rownames=FALSE,options= list(paging = TRUE, searching = TRUE,info=FALSE))