-1

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!

JC25
  • 13
  • 2
  • I created an Excel spreadsheet that lists all contiguous states for each state, which I can send you, but I don't know how to accomplish that in R with zip codes. – lawyeR May 14 '16 at 12:17
  • Welcome to StackOverflow. Please read (1) [how do I ask a good question](http://stackoverflow.com/help/how-to-ask), (2) [How to create a MCVE](http://stackoverflow.com/help/mcve) as well as (3) [how to provide a minimal reproducible example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610). Then edit and improve your question accordingly. I.e., provide input data, the expected output, what lines of code you tried and in what way they failed. – lukeA May 14 '16 at 12:41

1 Answers1

1

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" 
lukeA
  • 53,097
  • 5
  • 97
  • 100