为多个组创建动态 Alpha 船体时出现问题

问题描述 投票:0回答:1

你好吗?我需要你的帮助,在 R 中为不同的组创建 alpha 多边形。我希望这些多边形被我的“物种”列分开。

我知道

dplyr
库可以帮助我,可能可以使用
group_by
summarize
函数,但我在集成它时遇到了麻烦。

到目前为止,这就是我所做的工作

创建数据框并加载库

library(sf)
library(tidiverse)
library(mapview)
library(ggplot2)
library(rnaturalearth)
library(rangeBuilder)


#create data frame
decimalLat <- 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)
decimalLon <- 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(decimalLat, decimalLon, species)

标绘点

              #Mexico map
wrld <- ne_countries(scale = "small",returnclass = "sf")
mexico <- filter(wrld, name %in%  "Mexico")
           #create spatial matrix
df.1<- df %>%
  sf::st_as_sf(coords = c("decimalLon", "decimalLat"),crs="EPSG: 4326")
             #plot points
ggplot()+
  geom_sf(data=mexico)+
  geom_sf(data=df.1)

创建动态 alpha 外壳并转换为可视化

#Creating dynamic alpha hull

ah_dyna <- getDynamicAlphaHull(
  df, #Tabla de puntos/registros de la especie
  coordHeaders = c("decimalLon", "decimalLat"),# x y y
  fraction = 0.90,   # la fracción mínima de registros que debe incluir el polígono
  partCount = 1,  # el máximo de polígonos disyuntos permitidos
  initialAlpha = 1, # Alpha inicial
  alphaIncrement = 0.3,
  alphaCap = 1000,
  clipToCoast = "terrestrial")


#transforming
alpha <- ah_dyna[[2]]
alpha
dynalpha <- st_make_valid(st_as_sf(ah_dyna[[1]]))

#ploting
ggplot()+
  geom_sf(data=mexico)+
  geom_sf(data=dynalpha,
          fill="blue")


到目前为止,一切都很好,但是我遇到了一个问题,我想为初始数据框中的每个物种创建一个动态 alpha 外壳。我想它与

group_by
函数有关,但我不知道如何一起实现它。

这对我来说是一个挑战,因为我想将其自动化,因为我的最终数据框有超过 200 个物种。

非常感谢您的回复。

r gis geospatial polygon r-sf
1个回答
0
投票

您可以通过

split
species
获取数据,然后在
lapply
内的每个数据帧上运行该函数:

df.2 <- do.call("rbind", lapply(split(df, df$species), function(d) {
  st_sf(geometry = getDynamicAlphaHull(
  d, 
  coordHeaders = c("decimalLon", "decimalLat"),
  fraction = 0.90,   
  partCount = 1,  
  initialAlpha = 1, 
  alphaIncrement = 0.3,
  alphaCap = 1000,
  clipToCoast = "terrestrial")[[1]])
})) |>
  cbind(species = levels(factor(df$species)))

ggplot() +
  geom_sf(data = mexico) +
  geom_sf(data = df.2, aes(fill = species)) +
  geom_sf(data = df.1)

© www.soinside.com 2019 - 2024. All rights reserved.