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

3

我想计算多边形之间的距离,使用Hausdorff距离进行计算。目前只能计算两个多边形之间的距离,请问如何计算多个多边形之间的距离?需要您的帮助。

代码如下:

library(maptools)

library(rgdal)

shape <- readShapePoly("clipjawa.shp") #加载.shp文件

pemalang <- shape[1,1] #将多边形1的坐标保存到变量pemalang中

tegal <- shape[2,1] #将多边形2的坐标保存到变量tegal中

distance <- gDistance(pemalang,tegal,hausdorff=TRUE) #计算距离

1个回答

3

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

以下是一个示例,使用 maptools 中包含的 wrdl_simpl 数据集,计算非洲所有国家之间的豪斯多夫距离。

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

(更新一个例子)


我使用了.shp文件中的数据,这和maptools中的数据一样吗? - user3705542
很可能是一个带有属性表的多边形shapefile。我只是使用了wrld_simpl数据集,因为它在R中很容易获取,因此易于再现。你为什么不试试用你的数据,如果不行再评论呢? - jbaums
我在这行代码中遇到了一些错误: hdists <- cbind.data.frame(from=as.character(africa$NAME[combns[, 1]]), to=as.character(africa$NAME[combns[, 2]]), d=dists)警告信息如下: Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 21我使用了7个数据,这使得有21个组合, 你能帮我看看出了什么问题吗? - user3705542
我猜你的意思是当你用自己的数据替换非洲示例时,对吗?dim(combns)length(dists)是什么? - jbaums

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接