将 R 中一组点的边界作为多边形返回?

问题描述

我试图返回一组点的边界(如下)。我使用 {sf} 包尝试了三种方法

创建测试数据

t <- 
  crossing(x=1:5,y=1:5) %>% 
  filter(!(x > 3 & y > 3)) %>% 
  st_as_sf(coords=c("x","y"))

我想要的

ggplot()+
  geom_sf(data=t)+
  geom_segment(aes(x = c(1,1,3,5,5),xend = c(1,1),y = c(1,yend = c(5,col = "What I want"))

enter image description here

我的尝试

ggplot()+
  geom_sf(data=t)+
  geom_sf(data = t %>% st_union() %>% st_convex_hull(),aes(col="st_convex_hull"),fill=NA)+
  geom_sf(data = t %>% st_union() %>% st_cast("polyGON") %>% st_boundary(),aes(col = "st_boundary"))+
  geom_sf(data = 
            t %>% 
            st_union() %>% .
            st_buffer(0.5,endCapStyle = "SQUARE") %>% 
            st_buffer(-0.5,endCapStyle = "SQUARE"),aes(col="st_buffer twice"),fill=NA)

enter image description here

我想我可能会使用 st_buffer() 两次,但它仍然给出了一个弯曲的轮廓。此外,撇开曲线问题不谈,它在我的真实数据(包含数十万个点)上运行非常缓慢。

解决方法

我建议你考虑 {concaveman} 包;在您的玩具示例的特定情况下,它似乎工作得很好。您可能需要稍微调整 concavity 参数的值。

我无法评论它在您的实际数据上的表现有多好(或多快),但它应该给您一个开始。

library(tidyverse)

t <- 
  crossing(x=1:5,y=1:5) %>% 
  filter(!(x > 3 & y > 3)) %>% 
  sf::st_as_sf(coords=c("x","y"))

asdf <- t %>% 
  summarise() %>% 
  concaveman::concaveman(concavity = 1)

plot(asdf)

enter image description here