R 如何使用SF包计算质心和多边形边缘之间的最大距离?

R 如何使用SF包计算质心和多边形边缘之间的最大距离?,r,gis,sp,sf,R,Gis,Sp,Sf,我有一堆不同形状和大小的多边形,它们有质心。我想计算从每个质心到其各自多边形的最远点的距离 这个问题一直在使用package::sp和package::rgeos 据《每日邮报》报道,sf软件包“旨在长期取代sp”。仔细查看,我无法找到解决方案,但我对简单功能并不在行。使用sf软件包完成此操作有什么好方法吗?或者我现在应该继续使用sf和rgeos吗?将多边形投射到点(从而获得顶点),然后计算距离wrt质心应该可以工作。比如: 库(sf) #构建一个测试多边形 几何学[,1] #> [1,] 1.

我有一堆不同形状和大小的多边形,它们有质心。我想计算从每个质心到其各自多边形的最远点的距离

这个问题一直在使用package::sp和package::rgeos


据《每日邮报》报道,sf软件包“旨在长期取代sp”。仔细查看,我无法找到解决方案,但我对简单功能并不在行。使用sf软件包完成此操作有什么好方法吗?或者我现在应该继续使用sf和rgeos吗?

将多边形投射到点(从而获得顶点),然后计算距离wrt质心应该可以工作。比如:

库(sf)
#构建一个测试多边形
几何学[,1]
#> [1,] 1.201850
#> [2,] 1.054093
#> [3,] 2.027588
#> [4,] 1.201850
#最大距离:
最大距离[1]2.027588
#密谋看看这是否正确:似乎如此。
绘图(st_几何图形(pol))
绘图(st_质心(pol),相加=T)
绘图(st_cast(pol,POINT)【最大距离】,
cex=3,add=T,col=“红色”)

因为第一个顶点和最后一个顶点是相同的,所以两次得到相同的距离,但是因为您对最大值感兴趣,所以这不重要


HTH

我不确定你到底想要什么:到最远点的距离(这是你问的)或最远点的坐标(这是你指的答案提供的)

这是一个计算距离的解决方案(可以很容易地更改以提取坐标)

#这是一个多边形的示例。
#注意:多边形与问题中的答案相同
图书馆(sf)

sfPol我不知道
st\u cast
。有趣!但是,当我尝试在回答中使用它时,它对一个多边形正确工作,但在函数
最远处
中对多个多边形无效。这似乎是因为末尾的
lappy
部分执行:
st_-cast(st_-geometry(poly)[1],“点”)
只给出第一个点的坐标,而不是
st_-cast(st_-geometry(poly)[[1],“点”)
,后者给出所有顶点的预期坐标。
# This is an example for one polygon.
# NB the polygon is the same as in the answer pointed to in the question

library(sf)
sfPol <- st_sf(st_sfc(st_polygon(list(cbind(c(5,4,2,5),c(2,3,2,2))))))

center <- st_centroid(sfPol)
vertices <-  st_coordinates(sfPol)[,1:2]
vertices <-  st_as_sf(as.data.frame(vertices), coords = c("X", "Y"))
furthest <- max(st_distance(center, vertices))
furthest

## [1] 1.699673



# You can adapt this code into a function that will work 
# for multiple polygons

furthest <- function(poly) {
    # tmpfun find the furthest point from the centroid of one unique polygon
    tmpfun <- function(x) {
        center <- st_centroid(x)
        vertices <-  st_coordinates(x)[,1:2]
        vertices <-  st_as_sf(as.data.frame(vertices), coords = c("X", "Y"))
        furthest <- max(st_distance(center, vertices))
        return(furthest)
    }

    # We apply tmpfun on each polygon
    return(lapply(st_geometry(poly), tmpfun))
}


poly1 <- cbind(c(5,4,2,5),c(2,3,2,2))
poly2 <- cbind(c(15,10,8,15),c(5,4,12,5))

sfPol <- st_sf(st_sfc(list(st_polygon(list(poly1)), 
                           st_polygon(list(poly2)))))

furthest(sfPol)

## [[1]]
## [1] 1.699673
## 
## [[2]]
## [1] 5.830952