# Modeling Penalized-Splines in Stan

Hi,

Currently I am fitting some regression type model and would like to apply penalized-spline model on one of the continuous covariates X. The idea is applying the trucated linear spline basis function on the K pre-selected fixed knots (a_1,..., a_k) as \sum_{k=1}^{K}\beta_l(x_i - a_k)_{+}, where (x_i - a_k)_{+} = x_i - a_k \text{ if } x_i > a_k and 0 otherwise, \beta_l are used to constrain the influence of the K knots. I found the following reference Splines In Stan but I am still confused about the specific model I would like to construct. May I ask that how should I program such ideas in Stan?

Thanks so much!

Are you able to make a start at things then when you get stuck or are unsure of something, post your attempts to that point? That would make it much easier for folks here to provide help.

Note also that R package brms can auto-generate human-readable Stan code for penalized splines. It might be worth taking a peek at this code to see if it clarifies your problem. See, for example, the examples here Defining smooths in brms formulas — s • brms, in conjunction with brms::make_stancode.

Although brms doesn’t generate the spline basis functions in Stan, but uses mgcv to generate them in R and passes then un as data, which makes it bit more difficult to see what is going on or apply splines as part of models but supported by brms

1 Like

True! For somebody comfortable in R but not in Stan, this can still be a useful way forward, i.e. to write down the desired basis functions and evaluate them over the points in R, and then to follow the brms generated boilerplate.