我正在 R 中处理空间信息 (sf),并且我有一个物种列表及其各自的出现点。
我想使用 st_convex_hull 函数获得每个物种的多边形。我已设法为所有点创建一个多边形,但无法按物种变量对它们进行分组。
这是我迄今为止所拥有的脚本:
#Library
library(sf)
library(tidiverse)
library(mapview)
#create data frame
lat <- c(15.53033,15.53033,15.5219,15.1739,19.08333,17.13333,18.09861,21.27667,25.54863,18.80907,25.54147,
20.0605,23.299,25.5501,25.55005,25.54997)
lon <- c(-92.802,-92.802,-92.7997,-92.3361,-96.9667,-91.9333,-94.4297,-99.2117,-100.271,-99.2168,-100.272,-97.4713,
-106.443,-100.27,-100.27,-100.27)
species <- c("Sp1", "Sp1","Sp1", "Sp1","Sp1", "Sp1","Sp1", "Sp2","Sp2","Sp2","Sp2","Sp2","Sp2","Sp2","Sp2","Sp2")
df <- data.frame(lat, lon, species)
#create spatial matrix
df.1<- df %>%
sf::st_as_sf(coords = c("lon", "lat"),crs="EPSG: 4326")
mapview::mapview(df.1) #View map
#create polygon for the points
sp1_mcp <- st_convex_hull(st_union(df.1))
到目前为止,一切进展顺利,但我希望它根据数据框的“物种”值生成不同的多边形。真正的问题是我的数据库包含 200 个物种,这就是为什么我想自动化该过程。
最后,我还希望能够将 shapefile (.shp) 保存为文件。
您可以在使用
dplyr
聚合非空间数据集时应用相同的逻辑:group_by
后跟 summarise()
,每组返回一条记录。对于没有任何额外参数的 sf
对象 summarise()
仅总结几何图形,因此这里它将返回点的并集,即 MULTIPOINT
,您可以将其传递给 st_convex_hull()
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(dplyr, warn.conflicts = FALSE)
library(mapview)
# create data frame
lat <- c(15.53033,15.53033,15.5219,15.1739,19.08333,17.13333,18.09861,21.27667,25.54863,18.80907,25.54147,
20.0605,23.299,25.5501,25.55005,25.54997)
lon <- c(-92.802,-92.802,-92.7997,-92.3361,-96.9667,-91.9333,-94.4297,-99.2117,-100.271,-99.2168,-100.272,-97.4713,
-106.443,-100.27,-100.27,-100.27)
species <- c("Sp1", "Sp1","Sp1", "Sp1","Sp1", "Sp1","Sp1", "Sp2","Sp2","Sp2","Sp2","Sp2","Sp2","Sp2","Sp2","Sp2")
df <- data.frame(lat, lon, species)
df.1 <- df %>%
st_as_sf(coords = c("lon", "lat"),crs="EPSG:4326") %>%
group_by(species) %>%
summarise() %>%
st_convex_hull()
df.1
#> Simple feature collection with 2 features and 1 field
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: -106.443 ymin: 15.1739 xmax: -91.9333 ymax: 25.5501
#> Geodetic CRS: WGS 84
#> # A tibble: 2 × 2
#> species geometry
#> * <chr> <POLYGON [°]>
#> 1 Sp1 ((-92.3361 15.1739, -92.7997 15.5219, -96.9667 19.08333, -91.9333 17.…
#> 2 Sp2 ((-99.2168 18.80907, -106.443 23.299, -100.27 25.5501, -97.4713 20.06…
# visualise
mapview(df.1)
# save shp
dir.create("species")
st_write(df.1, "species/species.shp")
#> Writing layer `species' to data source
#> `species/species.shp' using driver `ESRI Shapefile'
#> Writing 2 features with 1 fields and geometry type Polygon.
# check result
fs::dir_tree("species/")
#> species/
#> ├── species.dbf
#> ├── species.prj
#> ├── species.shp
#> └── species.shx
st_layers("species/")
#> Driver: ESRI Shapefile
#> Available layers:
#> layer_name geometry_type features fields crs_name
#> 1 species Polygon 2 1 WGS 84
创建于 2023-10-04,使用 reprex v2.0.2