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

标签 r leaflet tiger-lines

我正在尝试为各种地理区域(即县/邮政编码)绘制多边形 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)

enter image description here

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

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

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

enter image description here

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

最佳答案

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

关于r - 在 R 中映射邮政编码与县 shapefile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176378/

相关文章:

r - 传单未在动态生成的 R markdown html knitr 中呈现

css - Leaflet全屏与Chrome中CSS位置冲突

google-maps - 2008 年 TIGER/Line® Shapefiles from Census.gov -> Google Maps

r - 计算大负值的指数

R:knitr + RGL:visreg 的 visreg2d 函数存在问题

r - 如何在R中使用重复生成正数

r - 在因子上减去对 `summary` 的两次调用的输出时,是否可以自动填充零?

javascript - 根据 leaflet.js 中 map 的缩放级别使用不同的 JavaScript 文件

latitude-longitude - 美国各州和城市的 Tiger/Lines 或 shapefile?