# User defined formulas in bf()

I’m trying to use a rather simple two piece linear model (which makes it non-linear) to count data. However, I can’t figure out how to specify it correctly.

The function I wrote is

`````` two_piece <- function(x, x0, y0, xmax = 46, y_xmax = 0) {
delta_x <- xmax - max(x0, x) # val1 or val2
b0 = (y_xmax-y0)/(xmax - x0)
mu = y_xmax  - delta_x * b0
return(mu)
}
``````

But when I try using

``````fit <- brm(
bf(two_piece(x, x0, y0, xmax = 46, y_xmax = 0),
shape ~ 1,
x0 ~ 1, # + 1|xx,
y0 ~ 1, # + 1|yy,
nl = TRUE),
data = df,
prior =  prior(normal(150, 200), nlpar = "y0") +
prior(uniform(25, 45.5),
lb = 25, ub = 45.5, nlpar = "x0"),
save_model = "brms_two.piece.stan")
``````

I get the error

``````Compiling Stan program...
Error in stanc(file = file, model_code = model_code, model_name = model_name,  :
0

Syntax error in 'string', line 42, column 61 to column 62, parsing error:

Ill-formed expression. Found identifier. There are many ways to complete this to a well-formed expression.

``````

Where line 42 in `brms_two.piece.stan` has

``````mu[n] = two_piece(C_1[n] , nlp_x0[n] , nlp_y0[n] , xmax=46 , y_xmax=0);
``````

So, I infer that `stan` cannot see the definition of `two_piece`, which makes some sense since it’s an R function. However, what doesn’t make sense to me is how one might, if at all, use a user defined function within brms()

(Note that I have tried defining the formula directly in `bf()`, but that leads to its own problems that I am posting about separately.)

• Operating System: Ubuntu 22.04
• Interface Version:
• R version 4.2.2 Patched (2022-11-10 r83330)
• brms_2.18.0
• rstan_2.26.13
• Compiler/Toolkit:

Man this is embarrassing. I asked a similar question here. Which essentially addresses this question.