Hello,

In brms one can use the `stanvar`

function to add code to a model.

For instance, if one specfies

```
dt = data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100))
dt$ysample(100,5)] = NA
bform =
bf(y ~ mi(x)) +
bf(x | mi() ~ z) +
set_rescor(FALSE)
my_stanvars =
stanvar(
scode = "Yl_x[Jmi_x] = Ymi_x;",
block = "model", position = "end")
make_stancode(
bform,
stanvars = my_stanvars,
data = dt)
```

The the stancode `Yl_x[Jmi_x] = Ymi_x;`

will be put at the very end of the model block:

```
model {
if (!prior_only) {
...
vector[N_x] Yl_x = Y_x;
...
Yl_x[Jmi_x] = Ymi_x;
...
}
...
Yl_x[Jmi_x] = Ymi_x;
}
```

This leads to an “out of scope” error because `Yl_x`

is used outside of `if (!prior_only) {...}`

.

**My question is if there is a way to use** `stanvar`

**for the model block such that the stan code is written inside of** ` if (!prior_only) {...}`

.

Thanks in advance!

Guido

So far I am just adding more stan code to re-create variables that were already created indside of ` if (!prior_only) {...}`

so that I can use them, but this is cumbersome and allows for errors.

The code above is only to illustrate the problem. The use case is a bit more complicated. In a nutshell, I want to evaluate the likelihood of y twice. Once for an outcome model with a restricted set of predictors (e.g. y \sim x) and once for an imputation model for a broader set of variables (e.g. y \sim x + z).