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 thatplot.gam
can use it for the plot. You can make it work as follows: