3

I am trying to model temperature across seasons using (package mgcv) GAMs. I am interested in using terra::predict() to plot the predicted temperatures as a raster.

Ideally, the output would be 4 rasters of the study area to represent the four seasons (winter, spring, summer, fall). However, I do not understand how to predict/if this can be done when using non-spatial (non-raster) with factors/groups (season).

An example of my code looks like:

library(terra)
library(mgcv)
v <- vect(system.file("ex/lux.shp", package="terra"))
r <- rast(system.file("ex/elev.tif", package="terra"))
set.seed(50)
pnts <- spatSample(v, size = 50)
pnts_r <- terra::extract(r, pnts, method = "simple") 
pnts_r$temp <- sample(0:25, 50, replace = TRUE)
# Define the sequence of seasons
seasons <- c('winter', 'spring', 'summer', 'fall')

# random add seasons seq
pnts_r$season <- seasons[seq_len(nrow(pnts_r)) %% length(seasons) + 1]

mod_gam <- mgcv::gam(temp ~ elevation + factor(season), data = pnts_r, 
                     family = gaussian(), method = "REML")

p <- predict(mod_gam, type="response")
x <- terra::predict(r, mod_gam, type="response")

#Error in eval(predvars, data, env) : object 'season' not found
#In addition: Warning message:
#In predict.gam(model, d, ...) :
#  not all required variables have been supplied in  newdata!`

I understand that seasons are not included in this raster, but I do not know if I can stack empty rasters as place holders or temperature modelling per season should be performed individually. I'd also like to bring in more data to look at inter-year variation, but want to start simply with inter-season of one year.

Any help is appreciated

1 Answer 1

5

You can do

x <- terra::predict(r, mod_gam, type="response", const=data.frame(season="fall"))

And likewise for other seasons.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfect - thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.