map_species_richness(comm, coords)

Map species richness from a community matrix + site coordinates. Returns an sf object ready for ggplot2.

spatialcommunity
Args:comm — site × species binary matrixcoords — data.frame with lon/lat and site name
map_species_richness <- function(comm, coords,
                               lon_col = "lon", lat_col = "lat",
                               site_col = "site") {
  if (!requireNamespace("sf", quietly = TRUE)) install.packages("sf")
  library(sf)
  
  sr <- data.frame(site = rownames(comm),
                   richness = rowSums(comm > 0))
  
  df <- merge(coords, sr, by.x = site_col, by.y = "site")
  st_as_sf(df, coords = c(lon_col, lat_col), crs = 4326)
}