簡體   English   中英

如何在R中使用gDistance計算距離矩陣?

[英]How to calculate distance matrix using gDistance in R?

我想計算與多邊形的距離。 為了計算方法,我使用hausdorff距離。 我只計算了2個多邊形。 如何計算多邊形? 請需要您的幫助。 此源代碼用於計算2個多邊形

庫(maptools)

庫(rgdal)

形狀<-readShapePoly(“ clipjawa.shp”)#加載文件.shp

pemalang <-shape [1,1]#將坐標從多邊形1保存到變量pemalang

tegal <-shape [2,1]#將坐標從多邊形2保存到可變tegal

距離<-gDistance(pemalang,tegal,hausdorff = TRUE)

有幾種方法可以解決此問題,但最簡單的方法可能是識別多邊形索引的所有組合(對),並將gDistance應用於這些組合中的每一個。

下面是一個例子,計算所有對非洲國家的豪斯多夫距離,使用wrdl_simpl附帶數據集maptools

# Load and project the data
library(maptools)
data(wrld_simpl)
africa <- spTransform(subset(wrld_simpl, REGION==2), 
                      CRS('+proj=eqc +lon_0=20.390625'))

# Calculate all pairs of polygons
combns <- t(combn(length(africa), 2))

# Split the SPDF into a list of SPDFs
africa.split <- split(africa, seq_len(length(africa)))

# For each row of combns, calculate Haus. dist. for the relevant pair of 
#  polygons
dists <- apply(combns, 1, function(x) 
  gDistance(africa.split[[x[1]]], africa.split[[x[2]]], hausdorff=TRUE))

為了方便起見,您可以將這些結果綁定到組合矩陣:

hdists <- cbind.data.frame(from=as.character(africa$NAME[combns[, 1]]), 
                           to=as.character(africa$NAME[combns[, 2]]), 
                           d=dists)

head(hdists)

#      from                               to       d
# 1 Algeria                           Angola 4733071
# 2 Algeria                            Benin 2807129
# 3 Algeria                            Congo 4056594
# 4 Algeria Democratic Republic of the Congo 4532625
# 5 Algeria                          Burundi 5464898
# 6 Algeria                         Cameroon 3071739

一種替代方法是使用outer ,但是這應該效率較低,因為它兩次計算所有距離(但是它確實會直接返回一個距離矩陣,這可能是合乎需要的)。

outer(africa.split, africa.split, FUN = Vectorize(function(x, y)  
  gDistance(x, y, hausdorff=TRUE)))

以示例更新

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM