 # Advice on how to use a logical operator in brms formula?

Operating System: macOS Catelina 10.15.2
Interface Version: brms 2.10.0

Hi everyone,

I’m trying to do a relatively straightforward piecewise linear regression model in brms of the sort:

Y ~ 1 + (1 + x*(x > 0) + x*(x < 0) | subjectID)

x in this case is a vector of doubles between -1 and +1 (with no zero values).

When I create my formula and check the priors I get an error:

``````piecewise_formula <- bf(Y ~ 1 + (1 + x*(x > 0) + x*(x < 0) | subjectID)
get_prior(piecewise_formula,
data = df,
family = "gaussian")
``````

Error in parse(text = x, keep.source = FALSE) :
:1:12: unexpected ‘<’
1: ~ 1+x+x>0+x<

So I looked up logical operators in Stan and found this page: https://mc-stan.org/docs/2_21/functions-reference/logical-functions.html

But creating my formula using the operator function also returns an error:

``````piecewise_formula <- bf(Y ~ 1 + (1 + x*(operator>(x,0)) + x*(operator<(x, 0))|subjectID))
``````

Error: unexpected ‘,’ in “piecewise_formula <- bf(Y ~ 1 + (1 + x*(operator>(x,”

This looks like a syntax error but I’ve counted my parenthesis and can’t see a problem. Alternatively:

``````piecewise_formula <- bf(Y ~ 1 + (1 + x * step(x) + x * step(-x)|subjectID))
``````

Error: \$ operator is invalid for atomic vectors

And I can’t seem to find any examples of logical operators in brms formulas, or piecewise regression models like this in the Stan or brms webpages, so I’m at the end of ideas for troubleshooting this error message. Any help or advice would be welcome.

Best,

Rich

Hey!

I don’t know much about piecewise linear regression, but can’t you do something like

``````df2 <- df %>%
mutate(x_neg = if_else(x < 0, x, 0.0),
x_pos = if_else(x > 0, x, 0.0))

piecewise_formula <- bf(Y ~ 1 + x_neg + x_pos | subjectId)
...
``````

this?

The operator that you tried is the operator in the Stan language, not to be confused with the `brms` syntax.

Does this work? (Can’t confirm, because I’m on phone…)

Cheers!
Max

3 Likes

Thank you! Yes that works. Sometimes I get so close to the problem I can’t see the solution right in front of my nose

Yes, I know that all too well ;)