I am fitting a large number of models with smooth terms. For each model, I set a different value of k
and pass it as a variable to the s()
term in the brms formula. I noticed that if the variable changes in the global environment, it will cause undesired behavior when predicting from the model. See errors below. Is there a better recommended way to pass variables to a brms formula to avoid this problem?
my_k <- 5
fit <- brm(
mpg ~ s(hp, k = my_k),
data = mtcars
)
predict(fit)
my_k <- 1
predict(fit)
my_k <- 1000
predict(fit)
The first call to predict(fit)
works as intended. The second two calls to predict(fit)
, after the value of my_k
has changed in the global environment, do not. The first one gives incorrect predictions with the warning:
Warning message:
In smooth.construct.tp.smooth.spec(object, dk$data, dk$knots) :
basis dimension, k, increased to minimum possible
The second gives this error:
Error in smooth.construct.tp.smooth.spec(object, dk$data, dk$knots) :
A term has fewer unique covariate combinations than specified maximum degrees of freedom
This is clearly because the “wrong” k value is being assumed when predicting from the fit. How can I pass a variable to the k
argument of s()
without it later depending on values in the environment?
Please also provide the following information in addition to your question:
- Operating System: Windows 11
- brms Version: 2.21.0