# start with the southwest data set
# grab the columns with xy, site ID, and species data
sppTab <- southwest[, c("species", "site", "Lat", "Long")]
##fit gdm using rasters
rastFile <- system.file("./extdata/swBioclims.grd", package="gdm")
envRast <- terra::rast(rastFile)
sitePairRast <- formatsitepair(sppTab, 2, XColumn="Long", YColumn="Lat",
sppColumn="species", siteColumn="site",
predData=envRast)
##remove NA values
sitePairRast <- na.omit(sitePairRast)
##fit raster GDM
gdmRastMod <- gdm(sitePairRast, geo=TRUE)
##raster input, raster output
transRasts <- gdm.transform(gdmRastMod, envRast)
# map biological patterns
rastDat <- terra::spatSample(transRasts, 10000, na.rm = TRUE)
pcaSamp <- prcomp(rastDat)
# note the use of the 'index' argument
pcaRast <- terra::predict(transRasts, pcaSamp, index=1:3)
# scale rasters
pcaRast[[1]] <- terra::app(pcaRast[[1]], fun = scales::rescale, to = c(0, 255))
pcaRast[[2]] <- terra::app(pcaRast[[2]], fun = scales::rescale, to = c(0, 255))
pcaRast[[3]] <- terra::app(pcaRast[[3]], fun = scales::rescale, to = c(0, 255))
terra::plotRGB(pcaRast, r=1, g=2, b=3)
Run the code above in your browser using DataLab