在R中将邮政编码与县份形状文件进行映射

3

我正在尝试绘制各种地理区域(例如县/邮政编码)的多边形。根据我在这篇博客中发现的内容,我可以很容易地为县完成此操作。

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)

enter image description here

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

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

我得到了一个完全不同的国家/地区,而不是纽约。

enter image description here

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


我在想,如果重新投影是否会出现问题? - Badger
第二个shapefile中的entry 0为ZCTA5CE10 (String) = 36426。那是阿拉巴马州,地图上的绘图区域也是阿拉巴马州。 - hrbrmstr
@hrbrmstr 我的印象是 GEOID10 的前两个数字对应于 fips 州代码(NY = 36)。 - cdeterman
1个回答

6
给 @hrbrmstr 注意到返回的邮政编码实际上是阿拉巴马州的邮政编码,这使我对之前对 GEOID10 变量结构的假设产生了怀疑。我发现了这个链接,其中提到使用 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接