'list' object cannot be coerced to type 'double' error when using ggpredict() with "gam" object

60 Views Asked by At

I have generated a Generalized Additive Mixed Model (GAMM) with mcgv::gamm() and have no problem using ggeffects::ggpredict() to make estimated marginal means predictions with the model and then plot them with ggplot2(). However, I am running into an error when I save my workspace, close it, and re-open it. When I do this and try to plot the same model with ggeffects::ggpredict() I receive the error message:

Error in is.constant(y) : 'list' object cannot be coerced to type 'double'

This must surely be a glitch since the plotting works fine until I exit the session. I don't want to re-run my models every time that I want to plot them, because they are built using large datasets, smoothing functions, and random effects, and are very time-consuming (many hours) to run. Does anyone know of a work-around?

Thank you very much.

Edit: 05 Dec 2023 (in response to comments by Miff and Gavin Simpson)

Thank you both for your responses.

Both packages---i.e. ggeffects and mgcv---were loaded. As Gavin noted, the object generated by mgcv::gamm() gives two options: $lme or $gam. class(model) gives the class as "gamm" "list". For some reason, running ggeffects::ggpredict(model) works fine during the session in which you created the gamm object, but gives the error message if you save, exit, and restart R. However, specifying ggeffects::ggpredict(model$gam) seems to be resolving the issue (n.b. ggeffects::ggpredict(model$lme) gives the error message Error in eval(x$call$random) : object 'rand' not found, presumably because there is a random effect in my model that it can't handle).

I will update further if any other issues.

2

There are 2 best solutions below

2
On

The models returned by gamm() consist of a list with a $lme component and a $gam component, each representing the two views of the model. Try

ggpredict(my_model$gam)

or

ggpredict(my_model$lme)

depending on how you want to do predictions and how you want to handle predictions with the random effects.

0
On

Usually, when ggpredict() is called, the correct slot ($gam) is automatically selected:

  # for gamm/gamm4 objects, we have a list with two items, mer and gam
  # extract just the gam-part then
  if (is.gamm(model) || is.gamm4(model)) {
    model <- model$gam
  }

(https://github.com/strengejacke/ggeffects/blob/master/R/ggpredict.R#L638C1-L643C1)

Can you post your sessionInfo() for both situations (where it works, and when you get an error)?