andrewallenbruce / provider

Public Healthcare Provider APIs :stethoscope:
https://andrewallenbruce.github.io/provider/
Other
18 stars 2 forks source link

Function: ZIP/FIPS to County #25

Closed andrewallenbruce closed 8 months ago

andrewallenbruce commented 8 months ago

Example use-case: (#18)

# `{zipcodeR}`: Retrieve Counties from Zip codes 
zip_db <- dplyr::tibble(zip_code_db) |> 
  dplyr::filter(state == "GA" | state == "FL") |> 
  dplyr::select(
    zipcode, 
    city = major_city, 
    county, 
    state, 
    lat, 
    lng, 
    pop_total = population, 
    pop_dense = population_density,
    med_income = median_household_income,
    dplyr::contains("bounds"))

# Join RHCs to Counties
rhc_zip <- dplyr::left_join(
  pivoted, ## zip code would be normalized dplyr::mutate(zipnorm = zipcodeR::normalize_zip(zip))
  zip_db, 
  by = dplyr::join_by(state, zipnorm == zipcode))

# Create data frame of unique state/county pairs
# Remove "County" from county names
st_cnty <- rhc_zip |> 
  distinct(state, county) |> 
  mutate(county = stringr::str_remove(county, " County"))

# Make separate, equal-length lists of the states and counties
x <- list(st_cnty$state)
y <- list(st_cnty$county)

# Retrieve county FIPS codes
# Retrieve geometries based on county FIPS
z    <- purrr::map2(x, y, fipio::as_fips)
z_sf <- purrr::map(z, fipio::fips_geometry) |> purrr::list_rbind()
z_sf[[1]]

# Unlist & insert into new tibble with geometry
st_ct_fips <- dplyr::tibble(
  state = unlist(x),
  county = unlist(y),
  fips = unlist(z),
  geometry = z_sf[[1]])