plot.gam from mgcv with all.terms = TRUE within a function

365 views Asked by At

I want to write a function that estimates a gam with factor variables and plots the result of all variables, including the factor variables. However, the plot function from the mgcv-package produces an error. Why does this error occur and how can I solve it?

library(mgcv)
plot_model <- function(x){
  agam <- gam(mean ~ s(bla) + bla2, data=x)
  plot(agam, pages=1, all.terms = TRUE)
   # here Error in eval(expr, envir, enclos) : object 'x' not found
}
bla <- data.frame(bla=rnorm(20), bla2=sample(letters[1:4], size=20, replace=T), 
                  mean=sample(20))
plot_model(bla)
# Error in eval(expr, envir, enclos) : object 'x' not found 
1

There are 1 answers

4
Sébastien Rochette On

Apparently, x needs to be declared in the local environment so that plot.gam can use it for the plot. You can make it work as follows:

library(mgcv)
plot_model <- function(y){
  data <- y
  agam <- mgcv::gam(mean ~ s(bla) + bla2, data=data)
  mgcv::plot.gam(x = agam, pages=1, all.terms = TRUE)
  # here Error in eval(expr, envir, enclos) : object 'x' not found
}
dat <- data.frame(bla=rnorm(20), bla2=sample(letters[1:4], size=20, replace=T), 
                  mean=sample(20))
plot_model(dat)