在 R 中映射邮政编码与县 shapefile

Mapping Zip Code vs. County shapefile in R

我正在尝试绘制各种地理区域的多边形地图(即 county/zip 代码)。根据我在 this blog 找到的内容,我可以轻松地为县完成此操作。

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<-subdat@data[,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)

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

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

我得到了这个国家完全不同的区域,而不是纽约。

不确定是否有人更熟悉这些数据集和这些函数来解释为什么会出现这种差异?

鉴于@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,]