[英]Find neighbouring polygons R
我有一張表,其中包含+ 500k行,其中的x
, y
坐標由shapeid
分組(總共289個id),並形成一個多邊形。
shapeid x y
1 679400.3 6600354
1 679367.9 6600348
1 679313.3 6600340
1 679259.5 6600331
1 679087.5 6600201
0 661116.3 6606615
0 661171.5 6606604
0 661182.7 6606605
0 661198.9 6606606
0 661205.9 6606605
... ... ...
我想找到相交或彼此最接近的坐標, 從本質上來說 , 是找到每個Shapeid的物理鄰居 。
結果應類似於:
shapeid shapeid_neighbour1 shapeid_neighbour2
所以我嘗試像這樣使用sp和rgeos:
library(sp)
library(rgeos)
mydata <- read.delim('d:/temp/testfile.txt', header=T, sep=",")
sp.mydata <- mydata
coordinates(sp.mydata) <- ~x+y
當我上課時,一切看起來都很好:
class(sp.mydata)
[1] "SpatialPointsDataFrame"
attr(,"package")
[1] "sp"
我現在嘗試計算每個點的距離:
d <- gDistance(sp.mydata, byid=T)
R Studio遇到致命錯誤。 有任何想法嗎? 我的計划是使用:
min.d <- apply(d, 1, function(x) order(x, decreasing=F)[2])
查找第二最短距離,即最近的點。 但這也許不是執行我想要的最佳方法-為每個Shapeid找到物理鄰居嗎?
假設數據shapeid
的每個shapeid
都可以標識多邊形的頂點,則需要首先根據坐標創建一個SpatialPolygons
對象,然后應用gDistance
函數了解任意一對多邊形之間的距離(假設這就是您要查找的) 。 為了創建SpatialPolygons
您需要一個Polygons
,然后一個Polygon
對象。 您可以在sp
包的幫助頁面Polygon
下找到詳細信息。
您可能很快就會發現一個問題:每個多邊形的坐標必須關閉,即每個Shapeid的最后一個頂點必須與第一個頂點相同。 據我從您的數據可以看出,您似乎並非如此。 因此,您應該“手動”為數據的每個子集添加一行。
您可以嘗試以下操作(假設df
是您的起始數據幀):
require(rgeos)
#split the dataframe for each shapeid and coerce to matrix
coordlist<-lapply(split(df[,2:3],df$shapeid),as.matrix)
#apply the following command only if the polygons don't close
#coordlist<-lapply(coordilist, function(x) rbind(x,x[1,]))
#create a SpatialPolygons for each shapeid
SPList<-lapply(coordlist,function(x) SpatialPolygons(list(Polygons(list(Polygon(x)),1))))
#initialize a matrix of distances
distances<-matrix(0,ncol=length(SPList),nrow=length(SPList))
#calculate the distances
for (i in 1:(length(SPList)-1))
for (j in (i+1):length(SPList))
distances[i,j]<-gDistance(SPList[[i]],SPList[[j]])
這可能需要一些時間,因為您要計算289 * 288/2多邊形的距離。 最終,您將獲得距離矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.