3

I'm going through the "Introduction to Statistical Learning with Applications in R" (ISLR), and I'm stuck on a part on page 295, the lab on Generalized Additive Models. When I run the following code I get an error Error in plot.gam(gam1, se = TRUE, col = "red") : could not find function "plot.gam".

library(ISLR)
gam1 = lm(wage ~ ns(year, 4) + ns(age, 5) + education, data=Wage)
par(mfrow=c(1,3))
plot.gam(gam1, se=TRUE, col="red")

The book says that plot.gam should be part of the general plot function, so why can't R find it? Am I supposed to be doing something differently? I tried unsuccessfully to re-download the plot library with install.packages('plot', repos='http://cran.us.r-project.org').

This confuses me because the book says this:

The generic plot() function recognizes that gam2 is an object of class gam, andinvokestheappropriateplot.gam()method.Conveniently,eventhough plot.gam() gam1 is not of class gam but rather of class lm, we can still use plot.gam() on it. Figure 7.11 was produced using the following expression:

plot.gam(gam1, se=TRUE, col="red")

brienna
  • 1,415
  • 1
  • 18
  • 45
  • 1
    @李哲源 I've tried library(gam) too but it doesn't help. I also cleared my workspace and re-entered everything. – brienna Jul 03 '18 at 15:47
  • 3
    I think you want the package `mgcv` – Esther Jul 03 '18 at 15:47
  • With `library(mgcv)`, I don't get the same error but I get `Error in if (se && x$Vp[1, 1] < 0) { : missing value where TRUE/FALSE needed`... This is weird because the book seemed to expect me to be able to just use `plot.gam` without importing anything. I had been told to import `gam` earlier though. – brienna Jul 03 '18 at 15:52
  • 1
    Do you mean `plot.Gam` then? Remember R is case sensitive. Also you can check which methods are available for regular `plot` (which is a function, not a package) by calling `methods(plot)`. There doesn't appear to be one for gam so I'm not sure why the book says that – Esther Jul 03 '18 at 15:59
  • `plot.Gam` works! Thanks - I didn't know about `methods()`, super useful. No idea why the book was able to use `plot.gam`... – brienna Jul 03 '18 at 16:00

1 Answers1

9

Use plot.Gam not plot.gam.

Software updates, but the book has not kept up. Checking the change log for the gam package, we can see that the case was changed in early 2018:

2018-02-06 Trevor Hastie version 1.15 * major change class "gam" to "Gam" to avoid conflict with mgcv (grr!)

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294