我正在尝试为各种地理区域(即县/邮政编码)绘制多边形 map 。根据我在 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,]
关于r - 在 R 中映射邮政编码与县 shapefile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176378/