开发者

Assign lat/long to zip codes

I have a dataframe latitude and longitude points in R. Using the R data science toolkit, I can assign these points to Country/State/County/City/Constituency/Neighborhood, which is useful.

I'd like to assign these points to 5 digit zip-codes (or even 9 digit zip codes!) in R or python. Is there an easy way to do this?

Edit: I found a file that contains zip code boundaries. Unfortunately, it is a .lpk file. 开发者_如何转开发 How do I import this into R?

Edit 2: I found a shape file, which will be easier to work with.


  1. Find a zip code shapefile somewhere (.shp format, sometimes called ArcGIS Shapefiles).

  2. Load it into R using the maptools package's readShapePoly command.

  3. Create a SpatialPointsDataFrame to hold the points.

  4. Make sure your projections are correct.

  5. Use the sp package's overlay command to overlay the points into the polygons.

You may find cleanLatLon in the taRifx package to be helpful.


I ran what gsk3 put together and it worked like a charm. Here is the specific code. I've also included the str of my latlong data frame for reference.

> # Shape files found here by state: http://www.census.gov/geo/www/cob/z52000.html#shp
> 
> library(maptools)
> library(maps)
> 
> zip.map <- readShapePoly("zt48_d00.shp")
> latlong <- read.csv("latlong.csv")
> str(latlong)
'data.frame':   2102 obs. of  3 variables:
 $ ref : Factor w/ 1594 levels ...
 $ lat : num  32.9 32.9 32.9 32.9 32.9 ...
 $ long: num  -96.7 -96.7 -96.7 -96.7 -96.7 ...
> coordinates(latlong) = ~long+lat
> write.csv(cbind(latlong, overlay(zip.map,latlong)),"zip.match.csv" )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜