tidycensus

The tidycensus package by Kyle Walker and Matt Herman makes the process of acquiring and working with US Census Bureau population data in R much simpler. We’ll use it to get census data in a tidyverse-friendly format.

In addition to installing the package, you need to acquire and set their Census API key. Go to https://api.census.gov/data/key_signup.html to obtain an API key; once you’ve received it in your email, tell R about it like so (you only need to install it once – don’t add your key to the scripts you share).

library(tidycensus)
# census_api_key("YOUR KEY GOES HERE", install = TRUE)

While tidycensus can be used to pull decennial census data and population estimates data, we’ll use it to pull data from the American Community Survey’s 5-year estimates using the get_acs() function.

The primary arguments for get_acs() include

get_acs(
  geography = "county", # this determines what spatial geography you want
  variables = c("var1", "var2"), # these are variable IDs 
  state = "51", # this is the state fips code for Virginia
  county = c("003", "540)"), # these are the county fips codes for Charlotteville and Albemarle
  year = 2021,
  survey = "acs5",
  output = "tidy"
  )
  • Geography options include states, counties, tracts, and more.
  • Finding variable ids requires knowing what table the variables are in and knowing what cell the variables are in within that table.
    • Finding tables takes some getting used to, but a good resource is the Census Reporter site.
    • With a table number in mind, it can be helpful to look for that table at the data.census.gov site
    • And tidycensus provides a load_variables() function to drill down for variable IDs within a table – worth reading more about!

factors

Factors are variables which take on a limited number of values, aka categorical variables. In R, factors are stored as a vector of integer values with the corresponding set of character values you’ll see when displayed (colloquially, labels; in R, levels).

forcats

The forcats package, part of the tidyverse, provides helper functions for working with factors. Including

  • fct_recode(): change factor levels by hand
  • fct_collapse(): collapse factor levels into defined groups
  • fct_lump(): collapse least/most frequent levels of factor into “other”
  • fct_reorder(): reorder factor levels by another variable
  • fct_relevel(): change order of factor levels by hand
  • fct_infreq(): reorder factor levels by frequency of levels

Let’s Play with R!

First go to slack and copy the practice script for today (week3script.R) into your weeklymaterials/scripts folder from last week. Then open an RStudio session using the weeklymaterials.Rproj file.


XKCD, Randall Munroe, https://xkcd.com/2494/

XKCD, Randall Munroe, https://xkcd.com/2494/