Skip to content

Instantly share code, notes, and snippets.

@arthurgailes
Created December 21, 2023 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthurgailes/45f781c219320f3e9a962a2b3e9f55d2 to your computer and use it in GitHub Desktop.
Save arthurgailes/45f781c219320f3e9a962a2b3e9f55d2 to your computer and use it in GitHub Desktop.
Fix Census 2022 blocks with tigris
#' Fix broken Census Connecticut blocks post-2022
#' See: https://github.com/walkerke/tigris/issues/178
library(tigris)
library(sf)
library(dplyr)
library(readr)
library(testthat)
# load official CT crosswalk
# missing a few block ids, but tracts are a consistent 1:1 merge so use those
ct_url <- "https://raw.githubusercontent.com/CT-Data-Collaborative/2022-block-crosswalk/main/2022blockcrosswalk.csv"
xwalk_ct <- read_csv(ct_url, col_select = matches('tract_fips')) |>
mutate(across(everything(), \(x) paste0('0', x))) |>
distinct()
# double check no m:1 tract correspondence
expect_equal(0, anyDuplicated(xwalk_ct$tract_fips_2020))
# load block geographies with tigris
ct_block <- blocks(state = "09", year = 2022)
# merge new tracts to create new block ID
ct_block_fix <- ct_block |>
mutate(tract_fips_2020 = substr(GEOID20, 1, 11)) |>
inner_join(xwalk_ct, by = "tract_fips_2020") |>
mutate(block_fips_2022 = paste0(tract_fips_2022, substr(GEOID20, 12, 15)))
#test that all joined
expect_equal(nrow(ct_block_fix), nrow(ct_block))
expect_true(all(nchar(ct_block_fix$block_fips_2022) == 15))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment