Generated Quantities: Getting an Error

Hi all,

I’m using Stan to fit a hierarchical regression model with one level (is_male). This is it:

data {
  int<lower=0> N; //number of obs
  
  vector[N] QT;
  vector[N] sqrtRR;
  int<lower=1, upper=2> is_male[N];
}

parameters {
  real<lower=0> sigma;
  real<lower=0> sigma_alpha;
  real<lower=0> sigma_beta;
  vector[2] alpha;
  vector[2] beta;
}

model {
  sigma ~ cauchy(0, 5);
  sigma_alpha ~ cauchy(0, 5);
  sigma_beta ~ cauchy(0, 5);
  alpha ~ normal(0, sigma_alpha);
  beta ~ normal(0, sigma_beta);
  
  QT ~ normal(alpha[is_male] + beta[is_male] .* sqrtRR, sigma); 
}

generated quantities {
  vector[N] log_lik;
  log_lik = normal_lpdf(QT | alpha[is_male] + beta[is_male] .* sqrtRR, sigma);
}

However, when I attempt to run it (from R), I get the following syntax error:

 SYNTAX ERROR, MESSAGE(S) FROM PARSER:

Base type mismatch in assignment; variable name = log_lik, type = vector; right-hand side type=real
error in 'model3eb34262430e_ec85b351a185e64d8db722a794a8238d' at line 25, column 14
      -------------------------------------------------
       23:   generated quantities {
       24:     vector[N] log_lik;
       25:     log_lik = normal_lpdf(QT | alpha[is_male] + beta[is_male] .* sqrtRR, sigma);                     ^
       26:   }
    -------------------------------------------------

    PARSER EXPECTED: <expression assignable to left-hand side>
    Error in stanc(file = file, model_code = model_code, model_name = model_name,  : 
    failed to parse Stan model 'ec85b351a185e64d8db722a794a8238d' due to the above error.

I noticed that the error goes away if I declare the generated quantities as such:

  generated quantities {
    vector[N] log_lik;
    for (i in 1:N) {
      log_lik[i] = normal_lpdf(QT[i] | alpha[is_male[i]] + beta[is_male[i]] * sqrtRR[i], sigma);
    }
  }

Is it not possible to declare the generated quantities fashion in a vectorized fashion?

Thanks!

Correct. All the _lpdf and _lpmf functions in Stan return scalars even if their arguments are not scalars.