R/pl_get_vtd.R

Defines functions pl_get_vtd

Documented in pl_get_vtd

#' Download 2020 Voting District Shapefiles
#'
#' `r lifecycle::badge("experimental")`
#' A (likely temporary) function to download TIGER shapefiles for 2020 voting
#' tabulation districts (VTDs).
#'
#' @param abbr Geography to download data for. See details for full list.
#' @param cache_to the file name, if any, to cache the results to (as an RDS).
#'   If a file exists and `refresh=FALSE`, will read from this file.
#' @param refresh if `TRUE`, force a re-download of the data.
#'
#' @return An `sf` object containing the VTDs.
#'
#' @examples
#' \donttest{
#' shp <- pl_get_vtd("RI")
#' }
#'
#' @concept basic
#' @export
pl_get_vtd = function(abbr, cache_to=NULL, refresh=FALSE) {
    if (!is.null(cache_to) && file.exists(cache_to) && !refresh) {
        return(readRDS(cache_to))
    }

    fips = match_fips(abbr)

    zip_url = stringr::str_glue("https://www2.census.gov/geo/tiger/TIGER2020PL/LAYER/VTD/2020/tl_2020_{fips}_vtd20.zip")
    zip_path = withr::local_tempfile(fileext = "zip")
    success = download_census(zip_url, zip_path)
    if (!success) {
        message("Download did not succeed. Try again.")
        return(NULL)
    }

    unz_path = file.path(dirname(zip_path), stringr::str_glue("vtd_2020_{fips}"))

    utils::unzip(zipfile=zip_path, exdir=unz_path)

    out = sf::read_sf(file.path(unz_path, stringr::str_glue("tl_2020_{fips}_vtd20.shp")))

    if (!is.null(cache_to)) {
        saveRDS(out, file=cache_to, compress="gzip")
    }

    withr::deferred_clear()
    out
}

Try the PL94171 package in your browser

Any scripts or data that you put into this service are public.

PL94171 documentation built on Sept. 12, 2022, 1:06 a.m.