Brms: passing data argument to a custom function

Hi,
Is it possible to pass data argument to the custom function? In the example shown below, I would like to pass knots defined in the data block to the rcsfun function. But including knots in the formula throws the error as it expects knots to be a variable in the data frame dat.
I tried the data2 type approach also but it did not work.

stanvars <-stanvar(scode = rcsfun, block = "function")+
           stanvar(knots, name = "knots")

bf <- bf(Y ~ rcsfun(X, s1, s2, s3, knots),
         s1 + s2 + s3 ~ 1,
         nl = T,
         loop = F)

bp <- prior(normal(0, 5), nlpar = "s1")+
      prior(normal(0, 5), nlpar = "s2")+
      prior(normal(0, 20), nlpar = "s3")
 
scode <- make_stancode(bf, data = dat, prior = bp, stanvars = stanvars)

Error: The following variables are missing in 'data':
'knots'

Thanks for your help.

2 Likes

I am not completely sure, but I think passing custom data to your function is currently only possible for custom families via the vars argument (see docs: http://paul-buerkner.github.io/brms/reference/custom_family.html).

But it seems to me that you could plausibly implement your model with rcsfun as a custom family with s1,s2,s3 being distributional parameters that you can model (and the model would no longer need to be non-linear). See the vignette: http://paul-buerkner.github.io/brms/articles/brms_customfamilies.html and feel free to ask if anything seems complicated/unclear.

(tagging @paul.buerkner for a second opinion)

Best of luck with your model!

I agree with the suggestions of @martinmodrak. Right now, there is no direct way to pass any data that does not follow the structure of data into non-linear functions in the way intended by you.

1 Like

Thanks @martinmodrak and @paul.buerkner

I can understand and really appreciate your feedback.

Brms is such a wonderful package that I love to work within its framework. In cases when there is no direct way to pass arguments, I create a stan code, modify it and then pass it back to brms for model fitting and post-processing.