I’m trying to get my head around Stan, and so I’m trying to translate the simplest jags model I can find, and I can’t get it to work in Stan. Rather than taking up your time discussing my stupid Stan errors, could someone please explain how to model this normal=> normal conjugate jags program in Stan? Thanks so much:

Y <- 100
sigma <- 5
m <- 50
s <- 10
model_string <- "model{
Y ~ dnorm(mu,inv.var.y)
inv.var.y <- pow(sigma,-2)
mu ~ dnorm(m,inv.var.mu)
inv.var.mu <- pow(s,-2)
}"
model <- jags.model(textConnection(model_string),
data = list(Y=Y,sigma=sigma,m=m,s=s))
update(model, 10000)
samp <- coda.samples(model,
variable.names=c("mu"),
n.iter=20000, progress.bar="none")
summary(samp)

data {
real Y;
real<lower=0> sigma;
real m;
real<lower=0> s;
}
parameters {
real mu;
}
model {
target += normal_lpdf(Y | mu, sigma);
target += normal_lpdf(mu | m, s);
}

Call with

posterior <- stan("this_model.stan",
data = list(Y = 100, sigma = 5, m = 50, s = 10))

Read Appendix B of the Stan User Manual and the FAQ

Thank you Ben. It’s the “target +=” object / operation syntax that I need to get my head around. It appears that I can just add distributions to it, including nonconjugates. Which could be really powerful. Hmmm. Thanks again. This is pretty cool stuff!

The target += foo_lpdf(... | ...) means add the logarithm of the pdf of the foo distribution to the symbol (target) that defines the log-kernel of the posterior PDF. So, you add those for each of the priors and likelihood components. At that point, you have defined the joint posterior distribution that Stan is drawing from. Conjugacy or lack thereof has nothing to do with it because the proposals for the next MCMC iteration are proposed jointly. Avoiding (full-)conditional distributions is what allows Stan to sample more efficiently than BUGS for many (differentiable) models.