2017-08-30 31 views
0

我想用shapefile識別每組緯度/經度座標的郵政編碼。將經度/緯度點映射到R中的一個形狀文件

緯度經度數據摘自:https://data.cityofchicago.org/Public-Safety/Crimes-2017/d62x-nvdr(犯罪_-_ 2001_to_present.csv)

Shape文件:https://www2.census.gov/geo/tiger/PREVGENZ/zt/z500shp/ zt17_d00.shp(爲伊利諾伊州郵政編碼定義)

library(rgeos) 
library(maptools) 

ccs<-read.csv("Crimes_-_2001_to_present.csv") 
zip.map <- readOGR("zt17_d00.shp") 
latlon<-ccs[,c(20,21)] 
str(latlon) 
    'data.frame': 6411517 obs. of 2 variables: 
    $ Latitude : num 42 41.7 41.9 41.8 42 ... 
    $ Longitude: num -87.7 -87.6 -87.7 -87.6 -87.7 ... 
coordinates(latlon) = ~Longitude+Latitude 
write.csv(cbind(latlon,over(zip.map,latlon)),"zip.match.csv") 

這是我得到的錯誤:

(函數(類,fdef,mtable)中的錯誤: 無法找到函數'over'進行簽名的繼承方法'「SpatialPolygonsD ataFrame「,」data.frame「'

我錯過了什麼?任何幫助表示讚賞!

+0

您正試圖創建一個從CSV和SpatialPolygonsDataFrame一個逗號分隔的文件,他們有完全不同的尺寸標註。您需要以不同的方式將數據與該SPDF文件組合在一起。嘗試共享'str(zip.map)'輸出以及綁定的目的與我們是什麼。我明白你最終在尋找什麼,但是如何實現這一目標?如果我能看到數據,我可能會提供幫助。 – sconfluentus

+0

我還沒有爲你的數據嘗試過,但是你可能想在'splancs'包中查找'?inout'。這是一種測試一組點是否落入多邊形(shapefile)的方法,它可能會讓您更接近您所需的。對不起,這不是確切的解決方案。 –

回答

3

從錯誤消息看來,您的coordinates(latlon) = ~Longitude+Latitude行看起來沒有成功將數據幀轉換爲空間對象。您可能希望在轉換後首先檢查class(latlon)電話。

繪製shapefile文件&覆蓋它與latlon層也是有幫助的,只是爲了確保你的數據集實際上是重疊的。如果不是,請檢查它們是否共享相同的投影(sp::identicalCRS)。

以下是使用虛擬數據的示例,因爲問題中的shapefile鏈接不起作用。

library(rgdal) 

# load Scotland shapefile, which came with the package 
dsn <- system.file("vectors", package = "rgdal")[1] 
shapefile <- readOGR(dsn=dsn, layer="scot_BNG") 
shapefile <- spTransform(shapefile, CRS("+proj=longlat +datum=WGS84")) #change CRS 

# create dummy data frame with coordinates in Scotland (I clicked randomly on Google Maps) 
csvfile <- data.frame(lat = c(-4.952, -4.359, -2.425), 
         long = c(57.57, 56.59, 57.56)) 

# convert data frame to SpatialPoints class 
coordinates(csvfile) <- ~lat+long 

# make sure the two files share the same CRS 
[email protected] <- [email protected] 

# visual check 
plot(shapefile, border = "grey") 
points(csvfile, col = "red", cex = 5) 
axis(1) # showing the axes helps to check whether the coordinates are what you expected 
axis(2) 

visual check

# if everything works out so far, the following should work 
points_in_shape <- over(csvfile, shapefile) 

> points_in_shape 
    SP_ID   NAME ID_x COUNT SMR LONG LAT  PY EXP_ AFF X_COOR Y_COOR ID_y 
1 50 Ross-Cromarty 5 15 352.1 57.71 5.09 129271 4.3 10 220678.6 870935.6 5 
2 11 Perth-Kinross 29 16 111.3 56.60 4.09 346041 14.4 10 291372.7 746260.5 29 
3  3 Banff-Buchan 2 39 450.3 57.56 2.36 231337 8.7 16 385776.1 852378.2 2 

> cbind(csvfile, points_in_shape["NAME"]) 
    lat long   NAME 
1 -4.952 57.57 Ross-Cromarty 
2 -4.359 56.59 Perth-Kinross 
3 -2.425 57.56 Banff-Buchan 
+0

感謝您的幫助Z. Lin!你是對的,我的座標()變換沒有正確地轉化爲空間對象 - 我錯過了緯度/經度數據中的一些空值......一旦我得到了修正並遵循了所有其他有用的步驟,工作。謝謝!!! – IsisDorus