Likelihood for multiple measurements

Hi Stan community,

I have a question about how to write the likelihood in the Stan code when there are repeated measurement in a timeseries. The timeseries is N datapoints long, and I have two columns, one for the first measurement and another for the second measurement. There are also predictors, which I don’t show here. I wonder if it works to write the likelihood twice (as in the below Stan-code), or if I should first gather the data into groups of measurements and then write the likelihood so that it loops first through measurements then through observations.

Thank you for the help.


data {
  int<lower=0> N; // number of datapoints
  real[N] y1; // first measurement for each datapoint
  real[N] y2; // second measurement for each datapoint
}
parameters {
  real mu[N]; // 
  real<lower=0> sigma;
}
model {
  for (i in 1:N) {
    y1[i] ~ normal(mu[i], sigma); 
    y2[i] ~ normal(mu[i], sigma); 
  }  
} 

Write it like

model {
  target += normal_lpdf(y1 | mu, sigma);
  target += normal_lpdf(y2 | mu, sigma);
}
1 Like

Thank you for the help Ben. May I ask why my above formulation does not work?

It does but requires N memory allocations instead of just one.