pbs-assess / sdmTMB

:earth_americas: An R package for spatial and spatiotemporal GLMMs with TMB
https://pbs-assess.github.io/sdmTMB/
183 stars 26 forks source link

Factor handling for Spatially Varying Coefficient models #269

Closed ericward-noaa closed 10 months ago

ericward-noaa commented 10 months ago

When using SVCs, predict() fails when all levels aren't included in the prediction dataframe. For example, this doesn't work:

data("pcod_2011")

pcod_2011$vessel <- sample(c("A","B"), size=nrow(pcod_2011),
                           replace=T)
mesh <- make_mesh(pcod_2011, xy_cols = c("X","Y"), cutoff=20)
fit <- sdmTMB(present ~ vessel,
              spatial_varying = ~ vessel,
              spatial="on",
              mesh=mesh,
              data=pcod_2011)

predict(fit, dplyr::filter(pcod_2011, vessel=="A"))

But when SVCs are removed, this all works great:

fit <- sdmTMB(present ~ vessel,
              #spatial_varying = ~ vessel,
              spatial="on",
              mesh=mesh,
              data=pcod_2011)

predict(fit, dplyr::filter(pcod_2011, vessel=="A"))
seananderson commented 10 months ago

The problem was that vessel was class character and not factor and so it only had one level in the new data after conversion internally. I think the simplest solution is just to issue a warning if the spatial_varying formula includes class character. See https://github.com/pbs-assess/sdmTMB/commit/6e9d3876650e7a2c88eae60bbfda0efb553c1499