if (FALSE) {
# you can run these examples if you have the 'terra' package installed
require(terra)
# import a raster map and aggregate it to a coarser resolution:
r <- terra::rast(system.file("ex/elev.tif", package = "terra"))
r <- terra::aggregate(r, 6)
plot(r)
# generate some random presence and absence points:
set.seed(123)
presences <- terra::spatSample(as.polygons(r), 100)
set.seed(456)
absences <- terra::spatSample(as.polygons(r), 70)
# add these points to the map:
points(presences, pch = 20, cex = 0.3, col = "black")
points(absences, pch = 20, cex = 0.3, col = "white")
# use 'gridRecords' on these points:
gridded_pts <- gridRecords(rst = r, pres.coords = terra::crds(presences),
abs.coords = terra::crds(absences))
head(gridded_pts)
# map the gridded points (presences black, absences white):
points(gridded_pts[ , c("x", "y")], col = gridded_pts$presence)
# you can also do it with only presence (no absence) records
# in this case, by default (with 'absences = TRUE'),
# all pixels without presence points are returned as absences:
gridded_pres <- gridRecords(rst = r, pres.coords = terra::crds(presences))
head(gridded_pres)
plot(r)
points(presences, pch = 20, cex = 0.2, col = "black")
points(gridded_pres[ , c("x", "y")], col = gridded_pres$presence)
# with only presence (no absence) records, as in this latter case,
# you can grid records for multiple species at a time
# by adding a 'species' argument
presences$species <- rep(c("species1", "species2", "species3"), each = 33)
values(presences)
plot(r, col = hcl.colors(n = 100, palette = "blues"))
plot(presences, col = as.factor(presences$species), add = TRUE)
gridded_pres_mult <- gridRecords(rst = r, pres.coords = terra::crds(presences),
species = presences$species)
head(gridded_pres_mult)
# add each each species' gridded presences to the map:
points(gridded_pres_mult[gridded_pres_mult[ , 1] == 1, c("x", "y")], col = 1, pch = 1)
points(gridded_pres_mult[gridded_pres_mult[ , 2] == 1, c("x", "y")], col = 2, pch = 2)
points(gridded_pres_mult[gridded_pres_mult[ , 3] == 1, c("x", "y")], col = 3, pch = 3)
# a large 'rst' may cause a crash, in which case you can grid in parts:
dir.create("gridRecords_tiles") # creates a folder to receive the tile files
terra::makeTiles(r, terra::divide(r, 2),
filename = "gridRecords_tiles/tile_.tif")
# give a larger 'n' to divide() if your 'rst' still crashes 'gridRecords'
tiles <- terra::sprc(list.files("gridRecords_tiles", full.names = TRUE))
par(mfrow = c(2, 2))
sapply(tiles, plot)
gridded_list <- lapply(tiles, gridRecords,
pres.coords = terra::crds(presences),
plot = TRUE)
gridded_pres <- do.call(rbind, unname(gridded_list))
unlink("gridRecords_tiles", recursive = TRUE) # deletes the tiles folder
}
Run the code above in your browser using DataLab