【问题标题】:Calculating the maximum/(or minimum) distance between each polygons within a shapefile计算 shapefile 中每个多边形之间的最大/(或最小)距离
【发布时间】:2021-11-03 12:10:05
【问题描述】:

我想使用 sf 包(或其他可能有效的包)计算 shapefile 中每个多边形之间的距离。我更喜欢距离是最大或最小距离(因为我不知道如何设置这些参数)。例如,假设 shapefile 中有三个多边形,即多边形 A、B 和 C,我想得到的结果将是一个数据框,表示 A 到 B、A 到 C、B 到 C 之间的距离。

对于示例 shapefile,您可以通过以下代码使用 sf 内置示例 shapefile:

library(sf) 
counties <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = T)

任何提示将不胜感激 :) 提前感谢您的帮助!

【问题讨论】:

    标签: r sf tmap


    【解决方案1】:

    您可能正在寻找sf::st_distance() 函数。

    它支持多边形到多边形的距离,因此它将为您提供 NC shapefile 中两个县多边形之间的最短距离作为矩阵。如果是相邻的多边形,这将是零。

    为了使矩阵更易于使用,您可能需要设置行名和列名;然后这些可以用于子集。

    考虑这段代码:

    library(sf) 
    counties <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = T)
    
    # matrix of county to county distances
    distances <- st_distance(counties, counties)
    
    # create colnames and rownames to make work easier
    colnames(distances) <- counties$NAME
    rownames(distances) <- counties$NAME
    
    # distance from county Mecklenburg / 100 values, inc. zeroes
    distances["Mecklenburg",] 
    
    # counties bordering Mecklenburg cnty / 6 counties - just the zeroes from example above
    distances[distances["Mecklenburg", ] == units::as_units(0, "meter"), "Mecklenburg"] 
    

    【讨论】:

    • 你好 Jandra:哇,我不知道你可以这样使用 st_distance :) 非常感谢你的帮助!非常感谢
    • 现在你可以了 :)
    最近更新 更多