Search code examples
rrasterpredictmixed-modelsglmmtmb

Predicting to raster stack at population level with glmmTMB in R


I'm trying to predict to a raster stack in R, using a GLMM I fit with the glmmTMB package, at the population level (i.e. setting random effects to 0). I followed Ben Bolker's solution in this thread which works for models fit with lme4, but even though the function argument re.form=~0 appears to be applicable to predict.glmmTMB in addition to predict.merMod, it's not working for me when I predict using a glmmTMB model. Here is an example using the same example code provided by Robert Hijmans in the aforementioned thread:

# example data. See ?raster::predict
logo <- brick(system.file("external/rlogo.grd", package="raster"))
p <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 
   66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 
   22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
a <- matrix(c(22, 33, 64, 85, 92, 94, 59, 27, 30, 64, 60, 33, 31, 9,
   99, 67, 15, 5, 4, 30, 8, 37, 42, 27, 19, 69, 60, 73, 3, 5, 21,
   37, 52, 70, 74, 9, 13, 4, 17, 47), ncol=2)
xy <- rbind(cbind(1, p), cbind(0, a))
v <- data.frame(cbind(pa=xy[,1], extract(logo, xy[,2:3])))
v$Year <- sample(2000:2001, nrow(v), replace=TRUE) 

#fit model using glmmTMB
library(glmmTMB)
m <- glmmTMB(pa ~ red + blue + (1 | Year), data=v)

# use argument "re.form=~0" to make population-level prediction
x <- predict(logo, m, re.form=~0)

When I run the above predict code (to make object x), I get the error: Error in eval(predvars, data, env) : object 'Year' not found. Can someone tell me what I might be doing wrong or how I can work around this?


Solution

  • Since "Year" is not a predictor raster you need to provide it in a different way. You can do

    x2000 <- predict(logo, m, re.form=~0, const=data.frame(Year=2000))
    x2001 <- predict(logo, m, re.form=~0, const=data.frame(Year=2001))
    

    This is equivalent (but less efficient)

    logo$Year <- 2000
    x2000 <- predict(logo, m, re.form=~0)
    

    If there are many years, perhaps like

     years <- c(2000, 2001)
     s <- list()
     for (i in 1:length(years)) {
        s[[i]] <- predict(logo, m, re.form=~0, const=data.frame(Year=years[i]))
     }
     s <- stack(s)
     sm <- mean(s)