if (FALSE) {
data(crotalus)
library(sf)
library(terra)
# get 10 species occurrence sets
uniqueSp <- split(crotalus, crotalus$genSp)
uniqueSp <- lapply(uniqueSp, function(x)
x[!duplicated(x[, c('decimallongitude', 'decimallatitude')]),])
uniqueSp <- names(uniqueSp[sapply(uniqueSp, nrow) > 5])
uniqueSp <- uniqueSp[1:10]
# create range polygons
ranges <- vector('list', length = length(uniqueSp))
for (i in 1:length(uniqueSp)) {
x <- crotalus[which(crotalus$genSp == uniqueSp[i]),]
ranges[[i]] <- getDynamicAlphaHull(x, coordHeaders = c('decimallongitude',
'decimallatitude'), clipToCoast = 'terrestrial')
}
# name the polygons
names(ranges) <- uniqueSp
# keep only the polygons
ranges <- lapply(ranges, function(x) x[[1]])
# Create a SpatRaster with the extent inferred from the polygons, and a cell
# resolution of 0.2 degrees.
# cells with the presence of a species get a value of 1, NA if absent.
rangeStack <- rasterStackFromPolyList(ranges, resolution = 0.2)
# calculate species richness per cell, where cell values are counts of species
richnessRaster <- app(rangeStack, fun=sum, na.rm = TRUE)
# set values of 0 to NA
richnessRaster[richnessRaster == 0] <- NA
#plot
ramp <- colorRampPalette(c('blue','yellow','red'))
plot(richnessRaster, col=ramp(100))
# to add a basic coastline, you can use the internal map
# world <- rangeBuilder:::loadWorldMap()
# plot(world, add = TRUE, lwd = 0.5)
}
Run the code above in your browser using DataLab