Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created October 1, 2021 20:57
Show Gist options
  • Save walkerke/e587be0d7d74b5175a360c5ee59c78c3 to your computer and use it in GitHub Desktop.
Save walkerke/e587be0d7d74b5175a360c5ee59c78c3 to your computer and use it in GitHub Desktop.
library(tidycensus) # Make sure you have tidycensus 1.1 or higher
library(redist)
library(sf)
library(tidyverse)
library(tigris) # Make sure you have tigris 1.5 or higher
library(httr)
options(tigris_use_cache = TRUE)
set.seed(123456)
# Grab existing districts from
# https://mapitwest.fortworthtexas.gov/giszipfiles/POL_COUNCIL_DISTRICTS.zip
fw_districts <- st_read("data-raw/POL_COUNCIL_DISTRICTS/POL_COUNCIL_DISTRICTS.shp") %>%
select(district = DISTRICT)
vtds_in_fw <- voting_districts(cb = TRUE, state = "TX") %>%
st_transform(st_crs(fw_districts)) %>%
st_point_on_surface() %>%
st_join(fw_districts, left = FALSE) %>%
st_drop_geometry() %>%
select(GEOID = GEOID20, district)
fw_vtds <- get_decennial(
geography = "voting district",
year = 2020,
variables = c(
Total = "P1_001N",
Hispanic = "P2_002N",
White = "P2_005N",
Black = "P2_006N",
Asian = "P2_008N",
Multiple = "P2_011N"
),
output = "wide",
geometry = TRUE,
state = "TX"
) %>%
inner_join(vtds_in_fw, by = "GEOID") %>%
mutate(district = as.integer(district)) %>%
filter(!row_number() %in% c(78, 293)) %>%
st_transform(st_crs(fw_districts))# redist can't handle queen's case neighbors
fw_map <- redist_map(fw_vtds, total_pop = Total, ndists = 10)
fw_sol <- redist_smc(fw_map, nsims = 1000)
redist.plot.plans(fw_sol, draws = 1:6, geom = fw_map)
mat <- get_plans_matrix(fw_sol)
# Solution 6
fw_vtds$district <- as.numeric(mat[,6])
solution6 <- fw_vtds %>%
select(district, Total:Multiple) %>%
group_by(district) %>%
summarize(across(.cols = Total:Multiple,
.fns = ~sum(.x, na.rm = TRUE)))
mapview::mapview(solution6, zcol = "district", col.regions = RColorBrewer::brewer.pal(10, "Set1"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment