Likelihood for multiple measurements

specification

#1

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); 
  }  
} 

#2

Write it like

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

#3

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


#4

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