Rstan: Generated quantities are not accessible

I try to do posterior predictive checks but fail to access the results from the generated quantities block. I’m new to Stan and I can’t figure out, what I’m doing wrong.

Here’s a short reproducible example in R with rstan.

RT <- (rnorm(1e4, 210, 54) / 1000)^(-1)

dat <- list(
  y = RT,
  N = length(RT)
)

model <- "
data {
  int<lower=0> N;
  vector[N] y;
}

parameters {
  real mu;
  real<lower=0> sigma;
}

model {
  y ~ normal(mu, sigma);
}

generated quantities {
  vector[N] y_rep;
  for (n in 1:N) 
    y_rep[n] = normal_rng(mu, sigma);
}
"

fit <- rstan::stan(
  model_code = model, 
  data = dat,
  chains = 3,
  pars = c("mu", "sigma"), 
  warmup = 500,
  iter = 1000,
  seed = 12
)

But when I try to access y_rep with extract(fit, pars = "y_rep"), I get an error that there is no y_rep. I tried it with R 3.6.3 and 4.0.0. Thanks in advance!

Hey! Welcome to the Stan forum! Thanks for providing your code.

The problem is that you are actually telling Stan to not save y_rep in the line pars = c("mu", "sigma"). To save everything, just drop this line and you should be able to extract y_rep (you have to re-run the model though).

Cheers,
Max

1 Like

Thanks a lot! I ended up adding "y_rep" to the pars argument.

1 Like