Help translate OpenBugs to Stan model: Hierarchical model

Could anyone help to translate this model from R2OpenBUGS to rstan:

Thanks!

##########################################################################################################
#### Hierarchical Model: hierarchical prior for thetas and within-plot variances
##########################################################################################################

linemodel<-function()
{
for(i in 1:Ntreat) {
    for(j in 1:Nsample) {
    y[i,j] ~ dnorm(theta[i], tau.with[i])   # normal likelihood
    }
    theta[i] ~ dnorm(mu, tau.btw)
    
    tau.with[i]     ~ dlnorm(logmu.tau.with, logtau.tau.with)
    sigma2.with[i] <- 1/tau.with[i]
}
  
	
# random effects: hyperpriors on random effects mean (overall) and variance (between-plot)
mu ~ dnorm(0.0, 1.0E-6)        # overall mean
tau.btw ~ dgamma(0.001, 0.001) # 1/variance of between-plot variance
sigma2.btw <- 1 / tau.btw      # between-plot variance


# random effects: hyperpriors on residual variance (within-plot variance) of normal likelihood 
logmu.tau.with    ~ dnorm(0.0, 1.0E-6) 
logmu.sima2.with <- 1/logmu.tau.with

logtau.tau.with ~ dgamma(0.001, 0.001)
logsima2.sigma2.with <- 1/logtau.tau.with
  
mu.sigma2.with <- exp(logmu.sima2.with)
sigma2.sigma2.with <- exp(logsima2.sigma2.with)

}

the last section of the Stan User’s Guide shows how to transition from Stan to BUGS.

2 Likes

Thank you for sharing it.