0
我有紐約市5449棵樹的經度和緯度,以及55個不同鄰居製表區(NTA)的shapefile。每個NTA在shapefile中都有一個唯一的NTACode,我需要在long/lat表中追加第三列,告訴我每棵樹屬於哪個NTA(如果有的話)。根據哪個多邊形包含它(紐約市公民地理空間數據)標記一個點
我已經取得了一些進展,已經使用其他在多邊形中的點在多邊形線程上,尤其是this one that looks at multiple polygons,但我仍然在嘗試使用gContains時出現錯誤,不知道如何檢查/標記每棵樹對於不同的多邊形(我猜一些sapply或for循環?)。
以下是我的代碼。數據/ shape文件可以在這裏找到:http://bit.ly/1BMJubM
library(rgdal)
library(rgeos)
library(ggplot2)
#import data
setwd("< path here >")
xy <- read.csv("lonlat.csv")
#import shapefile
map <- readOGR(dsn="CPI_Zones-NTA", layer="CPI_Zones-NTA", p4s="+init=epsg:25832")
map <- spTransform(map, CRS("+proj=longlat +datum=WGS84"))
#generate the polygons, though this doesn't seem to be generating all of the NTAs
nPolys <- sapply([email protected], function(x)length([email protected]))
region <- map[which(nPolys==max(nPolys)),]
plot(region, col="lightgreen")
#setting the region and points
region.df <- fortify(region)
points <- data.frame(long=xy$INTPTLON10,
lat =xy$INTPTLAT10,
id =c(1:5449),
stringsAsFactors=F)
#drawing the points/polygon overlay; currently only the points are appearing
ggplot(region.df, aes(x=long,y=lat,group=group))+
geom_polygon(fill="lightgreen")+
geom_path(colour="grey50")+
geom_point(data=points,aes(x=long,y=lat,group=NULL, color=id), size=1)+
xlim(-74.25, -73.7)+
ylim(40.5, 40.92)+
coord_fixed()
#this should check whether each tree falls into **any** of the NTAs, but I need it to specifically return **which** NTA
sapply(1:5449,function(i)
list(id=points[i,]$id, gContains(region,SpatialPoints(points[i,1:2],proj4string=CRS(proj4string(region))))))
#this is something I tried earlier to see if writing a new column using the over() function could work, but I ended up with a column of NAs
pts = SpatialPoints(xy)
nyc <- readShapeSpatial("< path to shapefile here >")
xy$nrow=over(pts,SpatialPolygons([email protected]), returnlist=TRUE)
我們檢查的NTAS是這些的(在GIS可視化):http://bit.ly/1A3jEcE
我試過這樣做,但它只給了我NAs? xy $ nrow = over(pts,SpatialPolygons(nyc @ polygons),returnlist = TRUE) – kmgong 2015-02-24 15:01:47
嘗試1)沒有任何參數 - 明顯的空間點和空間多邊形。 2)在我的應用程序中,我總是用'dimnames(coords)[[1]] < - name_vector'給出座標的名稱維度。我看不到它無法正常工作的原因。 – 2015-02-24 15:04:44
我在這裏嘗試了代碼,但我似乎正在獲取充足的NA?在原來的xy表中有幾棵樹缺失lon/lat,但我已經將它們更改爲0 ...不知道這是什麼導致了NAs? – kmgong 2015-02-24 17:41:12