R plot.gam Error “Error in 1:object$nsdf : argument of length 0”

佐手、 提交于 2019-12-01 18:04:47

If you still get this message, you need to update your mgcv and gam package to the latest version. A big change was made to gam package in Feb, 2018: Could not find function plot.gam. This means, a GAM fitted by gam package now have "Gam" class, and even if mgcv package is loaded, plot will not choose mgcv::plot.gam to plot it.

However, it is still unsafe to have both packages in an R session. So the following suggestion made in 2016 is still highly recommended.


Suggestion

It might be a good idea have this toy function to check whether an R session is OK to run GAM analysis.

GAM_status <- function () {
  if (all(c("gam", "mgcv") %in% .packages())) print("Not OK")
  else print("OK")
  }

nsdf is the the number of strict degree of freedom, a term exclusively used in mgcv. As you mentioned: mgcv is where the plot.gam function is from.

The problem is that you have gam and mgcv, two incompatible packages in your R session at the same time. You fit your gam.mod with gam::gam, but then plot the model with mgcv::plot.gam.

Note, what is normally true by using :: will lose effect here. Normally when two packages have some inter-masked functions, the :: is the remedy. But, for mgcv and gam, this is completely impossible. So my suggestion is, if you use gam, do not ever touch mgcv in your R session, and vice versa.

So, I start a fresh R session, and do the following, everything is fine!

library(gam)
library(ISLR) # contains the Wage dataset used here
gam.mod <- gam(wage ~ s(year, 4) + s(age, 5) + education, data = Wage)
par(mfrow = c(2,2)); plot(gam.mod)


Thank you for your answer. I never actually loaded mgcv, I just assumed it was a dependency for gam. I started a fresh R session and the code you provided worked. I found that it is actually the car library that is causing the same issue.

mgcv and gam does not depend on each other, but since mgcv is more popular than gam, many packages has dependency on mgcv, for example, car:

car: Companion to Applied Regression

Functions and Datasets to Accompany J. Fox and S. Weisberg, An R  Companion to
Applied Regression, Second Edition, Sage, 2011.
Version:    2.1-3
Depends:    R (≥ 3.2.0)
Imports:    MASS, mgcv, nnet, pbkrtest (≥ 0.4-4), quantreg, grDevices, utils,
            stats, graphics

Note the "Imports" field, library(car) will load these packages at the same time.

My mgcv version is 1.8-28, but I still have this issue. Consider converting all char variables into factors and rerun gam() or bam(). It works for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!