Search code examples
rlinear-regressionbayesianmcmcjags

jags bayesian linear regression, how can i set priors when the priors are dependent each other?


library(rjags)
jags_code = "model{
for (i in 1:n){
Y[i] ~ dnorm(mu[i], tau)
mu[i] <- beta0 + beta1*x[i]}

beta0 ~ dnorm(0,0.001)
beta1 ~ dnorm(0,0.001)
eta <- dgamma(0.1/2, 0.1/2)
tau ~ dgamma(5/2, 5*eta/2)"

jags_data = list(x = c(5,1,2,3,4),
                 Y = c(6,11,12,3,4), n=5)

jags_model = jags.model(textConnection(jags_code), data=jags_data)
update(jags_model, 10000)
samp <- coda.samples(jags_model, variable.names=c('beta0', 'beta1', 'eta'),
                     n.iter=5000)

summary(samp)
plot(samp)

Hi, I'm trying to run Gibbs sampler and fit linear regression using rjags. However, above code produces error like this.

Error in jags.model(textConnection(jags_code), data = jags_data) : 
Error parsing model file:
syntax error on line 10 near ""

I guess it's due to tau which contains eta in its argument. How can I solve this?


Solution

  • The error message you got is because you didn't provide a closing curly brace to pair with the opening curly brace of the model statement. Once you fix that error, you'll also notice that you accidentally used eta <- rather than eta ~, which will cause the error

    Incorrect number of arguments in function dgamma

    So, the completely fixed code is

    library(rjags)
    jags_code = "model{
    for (i in 1:n){
    Y[i] ~ dnorm(mu[i], tau)
    mu[i] <- beta0 + beta1*x[i]}
    
    beta0 ~ dnorm(0,0.001)
    beta1 ~ dnorm(0,0.001)
    eta ~ dgamma(0.1/2, 0.1/2)
    tau ~ dgamma(5/2, 5*eta/2)}"
    
    jags_data = list(x = c(5,1,2,3,4),
                     Y = c(6,11,12,3,4), n=5)
    
    jags_model = jags.model(textConnection(jags_code), data=jags_data)
    

    which will run just fine