From 1be189e3a81006851ec012799223399242bbe8bf Mon Sep 17 00:00:00 2001 From: Sean Anderson Date: Mon, 23 Sep 2024 13:14:22 -0700 Subject: [PATCH] Add message on offset newdata prediction #372 --- DESCRIPTION | 2 +- NEWS.md | 3 +++ R/predict.R | 9 +++++++++ tests/testthat/test-offset.R | 16 ++++++++++++++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index c69e2f1d..a3e767fd 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: sdmTMB Title: Spatial and Spatiotemporal SPDE-Based GLMMs with 'TMB' -Version: 0.6.0.9005 +Version: 0.6.0.9006 Authors@R: c( person(c("Sean", "C."), "Anderson", , "sean@seananderson.ca", role = c("aut", "cre"), diff --git a/NEWS.md b/NEWS.md index 18375ff4..411966ac 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # sdmTMB (development version) +* Add informative message if fitting with an offset but predicting with offset + argument left at NULL on newdata. #372 + * Fix passing of `offset` argument through in `sdmTMB_cv()`. Before it was being omitted in the prediction (i.e., set to 0). #372 diff --git a/R/predict.R b/R/predict.R index b8172471..1981545b 100644 --- a/R/predict.R +++ b/R/predict.R @@ -495,6 +495,15 @@ predict.sdmTMB <- function(object, newdata = NULL, cli_abort("`area` should be of the same length as `nrow(newdata)` or of length 1.") } + # newdata, null offset in predict, and non-null in fit #372 + if (isFALSE(nd_arg_was_null) && is.null(offset) && !all(object$offset == 0)) { + msg <- c( + "Fitted object contains an offset but the offset is `NULL` in `predict.sdmTMB()`.", + "Prediction will proceed assuming the offset vector is 0 in the prediction.", + "Specify an offset vector in `predict.sdmTMB()` to override this.") + cli_inform(msg) + } + if (!is.null(offset)) { if (nrow(proj_X_ij[[1]]) != length(offset)) cli_abort("Prediction offset vector does not equal number of rows in prediction dataset.") diff --git a/tests/testthat/test-offset.R b/tests/testthat/test-offset.R index d19420d7..b8448429 100644 --- a/tests/testthat/test-offset.R +++ b/tests/testthat/test-offset.R @@ -160,6 +160,22 @@ test_that("offset gets passed through cross validation as expected #372", { expect_true(length(unique(y$cv_predicted)) == 684L) }) +test_that("predicting on newdata with a non-null offset in fit but a null offset in predict informs the user appropriately", { + dat <- subset(dogfish, catch_weight > 0) + fit <- sdmTMB( + catch_weight ~ 1, + data = dat, + family = Gamma("log"), + offset = "area_swept", + spatial = "off" + ) + pred <- predict(fit) + pred <- predict(fit, offset = rep(0, nrow(dat))) + pred <- predict(fit, newdata = qcs_grid, offset = rep(0, nrow(qcs_grid))) + pred <- predict(fit, newdata = qcs_grid) + expect_message({pred <- predict(fit, newdata = qcs_grid)}, regexp = "offset") +}) + # # # # offset/prediction setting checks: #