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

How to compute the greatest distance between a centroid and the edge of the polygon using the SF package?

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

此问题已 使用 package::sp 和 package::rgeos。

根据 its vignette, the sf package "aims at succeeding sp in the long term." Looking through the documentation,我找不到解决方案,但我不是简单功能方面的专家。有没有使用 sf 包完成此操作的好方法,还是我现在应该坚持使用 sf 和 rgeos?

将多边形投射到 POINT(从而获得顶点),然后计算质心的距离应该可行。类似于:

library(sf)

# build a test poly
geometry <- st_sfc(st_polygon(list(rbind(c(0,0), c(1,0), c(1,3),  c(0,0))))) 
pol <- st_sf(r = 5, geometry)

# compute distances 
distances <- pol %>% 
  st_cast("POINT") %>% 
  st_distance(st_centroid(pol))

distances
#>          [,1]
#> [1,] 1.201850
#> [2,] 1.054093
#> [3,] 2.027588
#> [4,] 1.201850

# maximum dist:
max_dist <- max(distances)
max_dist
#> [1] 2.027588

# plot to see if is this correct: seems so.
plot(st_geometry(pol))
plot(st_centroid(pol), add = T)
plot(st_cast(pol, "POINT")[which.max(distances),],
     cex =3, add = T, col = "red")

你得到了两次相同的距离,因为第一个和最后一个顶点相同,但既然你对最大值感兴趣,那应该无关紧要。

HTH

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

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

# 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