2015-10-16 24 views
3

我想要映射各个地理区域(即县/邮政编码)的多边形。根据我在this blog发现的内容,我可以轻松地为县做到这一点。在R中映射邮政编码与郡县shapefile

library(rgdal) 
library(rgeos) 
library(leaflet) 

url<-"http://www2.census.gov/geo/tiger/TIGER2010DP1/County_2010Census_DP1.zip" 
downloaddir<-getwd() 
destname<-"tiger_county.zip" 
download.file(url, destname) 
unzip(destname, exdir=downloaddir, junkpaths=TRUE) 

filename<-list.files(downloaddir, pattern=".shp", full.names=FALSE) 
filename<-gsub(".shp", "", filename) 

# ----- Read in shapefile (NAD83 coordinate system) 
# ----- this is a fairly big shapefile and takes 1 minute to read 
dat<-readOGR(downloaddir, "County_2010Census_DP1") 

# ----- Create a subset of New York counties 
subdat<-dat[substring(dat$GEOID10, 1, 2) == "36",] 

# ----- Transform to EPSG 4326 - WGS84 (required) 
subdat<-spTransform(subdat, CRS("+init=epsg:4326")) 

# ----- save the data slot 
subdat_data<[email protected][,c("GEOID10", "ALAND10")] 

# ----- simplification yields a SpatialPolygons class 
subdat<-gSimplify(subdat,tol=0.01, topologyPreserve=TRUE) 

# ----- to write to geojson we need a SpatialPolygonsDataFrame 
subdat<-SpatialPolygonsDataFrame(subdat, data=subdat_data) 

leaflet() %>% 
    addTiles() %>% 
    addPolygons(data=subdat) 

enter image description here

但是,如果我运行一个不同的文件完全相同的代码,邮政编码

url <- "http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_zcta510_500k.zip" 

我得到的国家,而不是纽约的一个完全不同的领域。

enter image description here

不知道,如果有人更熟悉这些数据集,这些功能来解释为什么这种差异会发生什么?

+0

我不知道,当你重新项目存在问题? – Badger

+0

第二个shapefile中的条目0具有'ZCTA5CE10(String)= 36426'。那是阿拉巴马州,地图上的阴谋地区是阿拉巴马州。 – hrbrmstr

+0

@hrbrmstr我的印象是“GEOID10”中的前两位数字对应于fips状态码(NY = 36)。 – cdeterman

回答

5

鉴于@hrbrmstr注意到邮政编码的返回实际上是阿拉巴马州的邮政编码,这使我猜测我之前对GEOID10变量的结构的假设。我发现this link其中说,与zcta文件GEOID10变量实际上只是邮政编码,所以它是不可能过滤相同的县文件。

我想出了另一种使用noncensus包中的zip_codes数据集进行过滤的方法。然后,我取代了线

subdat<-dat[substring(dat$GEOID10, 1, 2) == "36",] 

# get zip codes for New York 
ny_zips <- zip_codes[zip_codes$state=="NY",] 
subdat<-dat[dat$GEOID10 %in% ny_zips$zip,] 

enter image description here