How to apply weights in a stan model

Dear stan community. I want to apply weights in my stan model using the brms approach explained here:

but when I do the same in my stan model I am getting the error:

SYNTAX ERROR, MESSAGE(S) FROM PARSER:

error in ‘model163045c662ad_m’ at line 31, column 10

29: alpha_3 ~ normal(0, 5);
30: // likelihood
31: ncases ~ weights*binomial(nn, pp_hat);
             ^
32: }

PARSER EXPECTED:
Error in stanc(file = file, model_code = model_code, model_name = model_name, :
failed to parse Stan model ‘m’ due to the above error.

##model

model {
// priors
alpha_0 ~ normal(0, 5);
alpha_1 ~ normal(0, 5);
alpha_2 ~ normal(0, 5);
alpha_3 ~ normal(0, 5);
// Likelihood
ncases ~ binomial(nn, pp_hat);
}

Thank you in advance for any help.

If you want to use weights, you have to use a loop and binomial_lpmf.

In particular, this line in the model block:

ncases ~ binomial(nn, pp_hat);

has to be replaced with:

for (i in 1:N)
  target += weights[i] * binomial_lpmf(ncases[i] | nn[i], pp_hat[i]);
2 Likes

This solution is perfect. Thanks a lot for that @Guido_Biele.