library(rstan)
options(mc.cores = 4)
rstan_options(auto_write = TRUE)

Check RStan setup: forward simulation

s <- "
data {
  real y_mean;
}
parameters {
  real y;
}
model {
  y ~ normal(y_mean, 1);
}
"
m <- stan(model_code = s, data = list(y_mean = 3))
print(m)
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1; 
## post-warmup draws per chain=1000, total post-warmup draws=4000.
## 
##       mean se_mean   sd  2.5%   25%   50%   75% 97.5% n_eff Rhat
## y     2.98    0.03 1.00  1.02  2.28  3.00  3.64  4.92  1358    1
## lp__ -0.50    0.02 0.71 -2.50 -0.69 -0.23 -0.05  0.00  1959    1
## 
## Samples were drawn using NUTS(diag_e) at Wed Oct 14 13:26:21 2026.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).

Estimate mu from data: solving the inverse problem

## Stan code
s <- "
data {
  int<lower=1>  N;   // sample size
  array[N] real y;   // observations
}
parameters {
  real mu;
}
model {
  y ~ normal(mu, 1);
}
"

## Data list
dat <- list(
  y = rnorm(20, 3, 1),
  N = 20
)

## Fit model
m <- stan(model_code = s, data = dat)
print(m)
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1; 
## post-warmup draws per chain=1000, total post-warmup draws=4000.
## 
##       mean se_mean   sd   2.5%   25%   50%   75% 97.5% n_eff Rhat
## mu    2.34    0.01 0.22   1.91  2.19  2.33  2.48  2.77  1374    1
## lp__ -9.08    0.02 0.66 -11.02 -9.25 -8.82 -8.65 -8.60  1698    1
## 
## Samples were drawn using NUTS(diag_e) at Wed Oct 14 13:27:23 2026.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at 
## convergence, Rhat=1).
bGlicmFyeShyc3RhbikKb3B0aW9ucyhtYy5jb3JlcyA9IDQpCnJzdGFuX29wdGlvbnMoYXV0b193cml0ZSA9IFRSVUUpCgojJyAjIyBDaGVjayBSU3RhbiBzZXR1cDogZm9yd2FyZCBzaW11bGF0aW9uCgpzIDwtICIKZGF0YSB7CiAgcmVhbCB5X21lYW47Cn0KcGFyYW1ldGVycyB7CiAgcmVhbCB5Owp9Cm1vZGVsIHsKICB5IH4gbm9ybWFsKHlfbWVhbiwgMSk7Cn0KIgptIDwtIHN0YW4obW9kZWxfY29kZSA9IHMsIGRhdGEgPSBsaXN0KHlfbWVhbiA9IDMpKQpwcmludChtKQoKIycgIyMgRXN0aW1hdGUgbXUgZnJvbSBkYXRhOiBzb2x2aW5nIHRoZSBpbnZlcnNlIHByb2JsZW0KCiMjIFN0YW4gY29kZQpzIDwtICIKZGF0YSB7CiAgaW50PGxvd2VyPTE+ICBOOyAgIC8vIHNhbXBsZSBzaXplCiAgYXJyYXlbTl0gcmVhbCB5OyAgIC8vIG9ic2VydmF0aW9ucwp9CnBhcmFtZXRlcnMgewogIHJlYWwgbXU7Cn0KbW9kZWwgewogIHkgfiBub3JtYWwobXUsIDEpOwp9CiIKCiMjIERhdGEgbGlzdApkYXQgPC0gbGlzdCgKICB5ID0gcm5vcm0oMjAsIDMsIDEpLAogIE4gPSAyMAopCgojIyBGaXQgbW9kZWwKbSA8LSBzdGFuKG1vZGVsX2NvZGUgPSBzLCBkYXRhID0gZGF0KQpwcmludChtKQoK