D.Mercer - 4 months ago 49

R Question

I am trying to plot a gam object in R, which I made with the gam package. I receive the same error reported in Error in 1:object$nsdf : argument of length 0 when using plot.gam. However, the solution found there, updating to the latest versions (I think), is not working for me. I am running R 3.3.1, gam 1.12, and mgcv 1.8.12 (mgcv is where the plot.gam function is from).

Unfortunately, I cannot share the data I am working with. However, the following code -- pulled directly from the p.294 of Intro. to Statistical Learning with R -- reproduces the error for me:

`library(gam)`

library(ISLR) # contains the Wage dataset used here

gam.mod <- gam(wage ~ s(year, 4) + s(age, 5) + education, data = Wage)

plot(gam.mod)

Does anybody know what is going on here or how to fix it?

Thank you.

Answer

**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.