如何使用 sf 按因子从点构造/绘制多边形的凸包?

Lut*_*ett 3 r spatial geos r-mapview r-sf

我有一个物种出现的数据集,我试图通过制作凸包将其转换为出现的区域。我可以手动执行此操作(即一次一个物种),但我真的很希望能够通过物种名称自动处理它。

可以在此处找到精简的示例数据集:https : //pastebin.com/dWxEvyUB

这是我目前手动执行的方法:

library(tidyverse)
library(sf)
library(rgeos)
library(maps)
library(mapview)
library(mapdata)
library(ggplot2)


fd <- read_csv("occurrence.csv")

spA.dist <- fd %>%
  filter(species == "sp.A") %>%
  dplyr::select(lon,lat) %>%
  as.matrix() %>%
  coords2Polygons(ID="distribution") %>%
  gConvexHull() %>%
  gBuffer()

spB.dist <- fd %>%
  filter(species == "sp.B") %>%
  dplyr::select(lon,lat) %>%
  as.matrix() %>%
  coords2Polygons(ID="distribution") %>%
  gConvexHull() %>%
  gBuffer() 

wrld2 = st_as_sf(map('world2', plot=F, fill=T))
ggplot() + 
  geom_sf(data=wrld2, fill='gray20',color="lightgrey",size=0.07) +
  geom_polygon(aes(x=long,y=lat,group=group),color="red",data=spA.dist,fill=NA) +
  geom_polygon(aes(x=long,y=lat,group=group),color="blue",data=spB.dist,fill=NA) + 
  coord_sf(xlim=c(100,300), ylim=c(-60,60))

Run Code Online (Sandbox Code Playgroud)

根据观察结果的凸包显示两个物种发生区域的地图。我意识到我在这里混合了不同的空间库,所以如果可能的话,最好在 sf 中完成所有操作。在我的真实数据中,我有两个以上的物种,我可以复制和粘贴我为每个物种获得的代码,但似乎应该可以简化这一点,因此多边形(以及随后的凸包)是按因子级别构建的自动地。更像这样的东西:

polys <- st_as_sf(fd) %>%
  group_by(species) %>%
  magically_make_polygons(lon,lat) %>%
  st_convex_hull() %>%
  st_buffer()
Run Code Online (Sandbox Code Playgroud)

我一直在寻找数天以及挖掘大量文档。很多这些空间的东西对我来说都是不直观的,所以我希望我缺少很多基本的理解。这能做到吗?

Wim*_*pel 6

这是使用tidyverse(实际上仅dplyr)和sf-package(以及mapview用于快速查看的包)的可能解决方案。

你和你自己的 sulution (kudo's) 非常接近。诀窍是summarise分组数据,然后创建外壳。

library( tidyverse )
library( sf )

#create simple feature
df.sf <- df %>%
  st_as_sf( coords = c( "lon", "lat" ), crs = 4326 )
#what are we working with? 
# perform fast visual check using mapview-package
mapview::mapview( df.sf )
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

#group and summarise by species, and draw hulls
hulls <- df.sf %>%
  group_by( species ) %>%
  summarise( geometry = st_combine( geometry ) ) %>%
  st_convex_hull()

#result
mapview::mapview( list( df.sf, hulls ) )
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明