rtidycensus

tidy way to load tidycensus variables (decennial)


I am using tidycensus to read in some census data. I am starting with loading the variables, and the way I am doing it just feels really clunky. Any advice on a cleaner way to code the load variable bit, so I don't load sf1, sf2, sf3 and sf4 in separately before binding?

ReqPkgs <-
  c(
    'dplyr',
    'tidyverse',
    'tidycensus',
    'sf'
  )

ReqPkgs <- as.list(ReqPkgs)

package.check <- lapply(
  ReqPkgs,
  FUN = function(x) {
    if (!require(x, character.only = TRUE)) {
      install.packages(x, dependencies = TRUE)
      library(x, character.only = TRUE)
    }
  }
)

#this is the part I want to tidy up:
vd_20001 <- load_variables(2000, "sf1", cache = TRUE)
vd_20002 <- load_variables(2000, "sf2", cache = TRUE)
vd_20003 <- load_variables(2000, "sf3", cache = TRUE)
vd_20004 <- load_variables(2000, "sf4", cache = TRUE)

vd_2000 <- rbind(vd_20001, vd_20002, vd_20003, vd_20004)
rm(vd_20001, vd_20002, vd_20003, vd_20004)

Solution

  • library(tidyverse)
    
    paste0("sf", 1:4) %>%
      map(load_variables, year = 2000, cache = TRUE) %>%
      bind_rows()