# Specifying nested random effects in RStan vs. RStanARM

Hi, I’m moving a project from RStanARM to Stan just to build by knowledge of Stan modeling. I’m struggling with representing nested random effects in a Stan script. In RStanARM, the model is

formula = close ~ (1|year_id\dsp_id) - 1...


That is, it’s a lme4 syntax representation of

formula = close ~ (1|year_id) + (1|year_id:dsp_id) - 1...


I’m trying to figure out how to represent this in native Stan code. I’ve been able to run the model for two random effects:

vector[N_obs] p = dsp[dsp_id] + year[year_id]


But I need help with how to write out the interaction. Please note that this is an interaction of two categorical random variables. Data and Stan model attached. I don’t think I need to change anything besides the function above, but please correct me if I’m wrong. Thanks.

stan_model.stan (745 Bytes)
trial.r (2.7 KB)
stan_data_dump.R (40.0 KB)

I think that is correct but look at the Z matrix produced by rstanarm or lme4 just to be sure.

Hi Ben, I know the RStanARM model for nested random effects is correct. My question is, how do I specify it in Stan?

You could pass that same \mathbf{Z} matrix to the data block of your Stan program. But if it is all zeros and ones, then you can also utilize indexing to pull out the parameters that are needed for a particular observation. You just need to make sure that your indexing scheme is equivalent to Z \mathbf{b}. The make_stancode in the brms package utilizes indexing, so you could look at that.