如何用R中的gDistance计算距离矩阵?

时间:2014-06-04 04:53:05

标签: r gis

我想计算多边形的距离。为了计算方法,我使用hausdorff距离。我只计算2个多边形。如何计算多边形?需要你的帮助。 这个计算2多边形的源代码

  

库(maptools)

     

库(rgdal)

     

shape< - readShapePoly(“clipjawa.shp”)#load for file .shp

     

pemalang< - shape [1,1] #save坐标从多边形1到变量pemalang

     

tegal< - shape [2,1] #save坐标从多边形2到变量tegal

     

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

1 个答案:

答案 0 :(得分:3)

有几种方法可以解决这个问题,但也许最简单的方法是识别多边形索引的所有组合(对),并将gDistance应用于这些组合中的每一种。

以下是使用wrdl_simpl中包含的maptools数据集计算非洲所有国家/地区的Hausdorff距离的示例。

# 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)))

更新了示例