简体   繁体   中英

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

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 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM