What does bquote do in this example using mgcv::gam in a function

423 views Asked by At

in the following function I have to use the bquote function when fitting the gam model to avoid the error

Error in eval(expr, envir, enclos) : object 'x' not found

when plot.gam is called. The error occurs due to the factor variable I want to plot. However I don't really understand what the bquote does here and why I need it.

library(mgcv)
plot_model <- function(x){
  # agam <- gam(mean ~ s(bla) + bla2, data=x)
  agam <- eval(bquote(mgcv::gam(mean ~ s(bla) + bla2, data=.(x))))
  plot(agam, pages=1, all.terms = TRUE)
}
bla <- data.frame(bla=rnorm(20), bla2=sample(letters[1:4], size=20, replace=T), 
                  mean=sample(20))

plot_model(bla)

The R-help says "bquote quotes its argument except that terms wrapped in .() are evaluated in the specified where environment. Usage bquote(expr, where = parent.frame())." What is the where environment here (parent.frame = the plot_model environment?) and what environment would it be evaluated in without the bquote (the environment created by the call to gam?)?

1

There are 1 answers

5
Kamil Bartoń On

bquote substitutes the expression .(X) with the value of x. Therefore what is actually evaluated is:

mgcv::gam(mean ~ s(bla) + bla2, data = list(bla = c(-0.147370861075094, <...>)

This error pops up because plot.gam asks to look for the symbol x in the global environment rather than the environment of plot_model.

When debugged with recover:

<...>
3: plot.gam(agam, pages = 1, all.terms = TRUE)
4: termplot(x, se = se, rug = rug, col.se = 1, col.term = 1, main = attr(x$pterms, "term.
5: eval(model$call$data, envir)
<...>
Browse[1]> envir
<environment: R_GlobalEnv>