2017-08-30 28 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