Search code examples
rgeocodingzipcode

How to Find Neighboring States through State Zip code information in R


I want to find the neighboring states for a given particular state in US through its zip code information in R, can anyone please help me on how to go ahead with it?

thanks in advance!


Solution

  • Get a list of zip codes, match them with states, get a states shape file and calculate the neighbours. Basically it could work like this:

    # get data
    library(spdep)
    library(raster)
    # https://www.census.gov/geo/reference/codes/cou.html
    fips <- read.csv("http://www2.census.gov/geo/docs/reference/codes/files/national_county.txt", header=F, col.names = c("STATE", "STATEFP", "COUNTYFP", "COUNTYNAME", "CLASSFP"))
    map <- getData("GADM", country="US", level=2)
    
    # select by code
    (county <- as.character(subset(fips, STATE=="NY" & STATEFP==36 & COUNTYFP==61, select=COUNTYNAME)[, 1]))
    # [1] New York County
    
    # get neighbour:
    nbs <- poly2nb(map) # takes some time to get the neighbour counties
    nam <- with(map@data, paste(NAME_2, TYPE_2))
    lst <- setNames(lapply(unclass(nbs), function(x) nam[x]), nam)
    lst[county]
    # $`New York County`
    # [1] "Bergen County" "Hudson County" "Bronx County"