# Mean structure involving sums and multiple indexing

Hi all,

I am trying to specify the mean structure of my model. The model is as follow

Y_{ij} \sim N(\mu_{y_{ij}}, \sigma^2_y)
\mu_{y_{ij}}=(d_y +u_{1j})+(cp+u_{2j})X_{ij}+\sum_{k=1}^K(b^k +u_{(2+k)j})M^k_{ij}

The corresponding trial code is as follow. I’m not sure if this is the right way to specify the term involving sums. Any help?

data{
int<lower=1> N;             // Number of observations
int<lower=1> K;           // Dimension of M
int<lower=1> J;             // Number of participants
int<lower=1,upper=J> id[N]; // Participant IDs
}

transformed parameters {

// Participant-level varying effects
matrix[J, K+2] U;
}
parameters{
real dy;                           // Intercept
real cp;                           // X coef
vector[K] b;                     // M coef
}
model {

// Means of linear models
vector[N] mu_y;

for (n in 1:N){
mu_y[n] = (dy + U[id[n], 1])+ (cp + U[id[n], 2]) * X[n] +
sum(for(k in 1:K){ (b[k]+ U[id[n], 2+k]) * M[n,k] } )

}
}

You can write the for-loop like this:

model {
// Means of linear models
vector[N] mu_y;
for (n in 1:N) {
mu_y[n] = dy + U[id[n], 1] + (cp + U[id[n], 2]) * X[n];
for(k in 1:K) {
mu_y[n] += (b[k] + U[id[n], 2+k]) * M[n,k];
}
}
}
1 Like

Thank you very much @nhuurre!