【问题标题】:How to calculate distance matrix using gDistance in R?如何在 R 中使用 gDistance 计算距离矩阵?
【发布时间】:2014-06-04 04:53:05
【问题描述】:

我想计算与多边形的距离。对于计算方法,我使用豪斯多夫距离。我只计算了 2 个多边形。如何计算多边形?需要你的帮助。 此源代码用于计算 2 个多边形

图书馆(地图工具)

图书馆(rgdal)

shape

pemalang

tegal

距离

【问题讨论】:

    标签: r gis


    【解决方案1】:

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

    这是一个示例,使用 maptools 中包含的 wrdl_simpl 数据集计算非洲所有国家对的 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)))
    

    更新了一个例子

    【讨论】:

    • 我使用了.shp中的数据,maptools中的数据也一样吗?
    • 最有可能(即它是一个带有属性表的多边形 shapefile)。我刚刚使用了 wrld_simpl 数据集,因为它在 R 中很容易获得,因此很容易重现。您为什么不尝试使用您的数据,如果它不起作用,请再次发表评论。
    • 我在这行代码中遇到了一些错误:hdists
    • 我假设您的意思是当您将自己的数据替换为非洲示例时,对吧? dim(combns)length(dists) 是什么?
    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    相关资源
    最近更新 更多