Reputation: 479
I am trying to utilize the noncensus package in R to join the data("zip_codes") which contains the county level fips code to get the data("counties") that has the actual county name.
My data set contains the zip codes for 100's of observations and I am trying to match up what county they are in. Both counties and zip_codes have the county fips code but when I join them they don't match as I get 0 values returned.
library(noncensus)
data("zip_codes")
data("counties")
counties$county_fips <- as.numeric(as.character(counties$county_fips))
Test <- zip_codes %>%
left_join(counties, c("fips"="county_fips"))
Test <- Test %>%
slice(1:5) %>%
select(zip, city, state.x, county_name)
If there are other packages in R to get the county from a zip code I'd be open to try that as well.
Thanks,
Upvotes: 1
Views: 818
Reputation: 1061
ZCTA FIPS codes have no relationship to county FIPS codes. ZCTAs also don't nest within counties and can cross county boundaries. As such, you'll need spatial methods without some other correspondence table. This R code will do it:
library(tigris)
library(tidyverse)
library(sf)
options(tigris_use_cache = TRUE)
options(tigris_class = "sf")
cty <- counties(cb = TRUE) %>%
select(cty_id = GEOID, cty_name = NAME)
zc <- zctas(cb = TRUE)
zipcty <- st_join(zc, cty)
The result returns a row for each unique ZCTA/county combination; the default spatial method for st_join
is "intersects" so this could mean that the ZCTA lies within, crosses the boundary of, or touches the boundary of the county.
Upvotes: 1