2015-09-28 86 views

回答

4

over/%over%工作得很好,因爲@RobertH建議。

library(sp) 
library(raster) 
library(rgdal) 
library(dplyr) 

# get the shapefile without wasting bandwidth 
URL <- "http://gis.ny.gov/gisdata/data/ds_934/zip_codes_shp.zip" 
fil <- "nyzips.zip" 
if (!file.exists(fil)) download.file(URL, fil) 
shp <- grep("shp$", unzip(fil), value=TRUE) 
ny <- readOGR(shp[2], ogrListLayers(shp[2])[1], stringsAsFactors=FALSE) 

# you didn't give us data so we have to create some by random sampling 
# within the bounding box 
ny_area <- as(extent(bbox(ny)), "SpatialPolygons") 
set.seed(1492) # reproducible 
pts <- spsample(ny_area, 3000, "random") 
proj4string(pts) <- proj4string(ny) 

# this does the lon/lat to zip mapping 
zip_where <- pts %over% ny 

# since we fabricated data, not all will be in a zip code since 
# ny isn't a rectangle, so we remove the "bad" data 
zip_where <- zip_where[complete.cases(zip_where),] 

arrange(count(zip_where, POSTAL), desc(n)) 

## Source: local data frame [602 x 2] 
## 
## POSTAL  n 
##  (chr) (int) 
## 1 12847 16 
## 2 12980 14 
## 3 13367 14 
## 4 13625 10 
## 5 12843  9 
## 6 12986  9 
## 7 12134  8 
## 8 12852  7 
## 9 13324  7 
## 10 13331  7 
## .. ... ... 

由於您提供的座標的樣本,這裏是如何在閱讀它們,並將它們轉換爲您的紐約shape文件的投影,所以你可以做的聚合:用於快速回答

pts <- read.csv("http://pastebin.com/raw.php?i=mXntxhK2", na.strings="null") 
pts <- pts[complete.cases(pts),] 
coordinates(pts) <- ~longitude+latitude 
proj4string(pts) <- CRS("+proj=longlat +datum=WGS84") 
pts <- spTransform(pts, proj4string(ny)) 

# this does the lon/lat to zip mapping 
zip_where <- pts %over% ny 

# but since we fabricated data, not all will be in a zip code since 
# ny isn't a rectangle, so we remove the "bad" data 
zip_where <- zip_where[complete.cases(zip_where),] 

arrange(count(zip_where, POSTAL), desc(n)) 
## Source: local data frame [158 x 2] 
## 
## POSTAL  n 
##  (chr) (int) 
## 1 11238 28 
## 2 11208 25 
## 3 11230 20 
## 4 10027 19 
## 5 11229 17 
## 6 11219 16 
## 7 11385 16 
## 8 11206 15 
## 9 11211 15 
## 10 11214 14 
## .. ... ... 
+0

你可以給一些關於如何將我的緯度/經度格式轉換爲這個xy系統的指針嗎? – qwerty123

+1

解答已更新 – hrbrmstr

1

這裏有一個辦法:

library(raster) 
library(rgeos) 
# example data 
filename <- system.file("external/lux.shp", package="raster") 
zip <- shapefile(filename) 
set.seed(0) 
xy <- coordinates(spsample(zip, 10, 'random')) 
plot(zip, col='gray') 
points(xy, pch=20, col='red', cex=2) 
# 
extract(zip, xy) 

你也可以使用SP ::在

+0

謝謝。我是R新手,讓我試試看。 – qwerty123

+0

當我嘗試這個時,最後一行會拋出一個錯誤:'錯誤...: 無法找到函數'提取'的簽名爲''SpatialPolygonsDataFrame','矩陣''的繼承方法。' – jlhoward

+0

update.packages()? – RobertH

相關問題