I have fitted following simple linear regression
Bayesian
model using rjags
.
I was able to run the model by specifying all the predictors separately(like for a lm
object). Now I want to learn how to specify the predictors by introducing them as a matrix instead of specifying them separately.
So I ran the following code, but it gave some errors.
I used tobbaco
data set in rrr
package to provide a reproducible example.
library(rrr)
require(dplyr)
library(rjags)
tobacco <- as_data_frame(tobacco)
N1 = length(tobacco$Y1.BurnRate)
x1 = model.matrix(Y1.BurnRate~X2.PercentChlorine+X3.PercentPotassium ,data = tobacco)
bayes_model_mul1=
"model {
for(i in 1:N1){
Y1.BurnRate[i]~dnorm(mu1[i],tau1)
for(j in 1:3){
mu1[i]=beta1[j]*x1[i,j]
}
}
for (l in 1:3) { beta1[l] ~dnorm(0, 0.001) }
tau1 ~ dgamma(.01,.01)
sigma_tau1 = 1/tau1
}"
model3 <- jags.model(textConnection(bayes_model_mul1),
data = list(Y1.BurnRate=tobacco$Y1.BurnRate, x1=x1, N1=N1),
n.chains=1)
After I run model3
, I got following error.
Error in jags.model(textConnection(bayes_model_mul1), data = list(Y1.BurnRate = tobacco$Y1.BurnRate, :
RUNTIME ERROR:
Compilation error on line 6.
Attempt to redefine node mu1[1]
Can anyone help me figure this out ? Does this due to introducing predictors as a matrix ?
There are a few ways to do this, here are two:
m1 =
"model {
mu1 = x1 %*% beta1 # ---> this
for(i in 1:N1){
Y1.BurnRate[i] ~ dnorm(mu1[i], tau1)
}
for (l in 1:3) { beta1[l] ~ dnorm(0, 0.001) }
tau1 ~ dgamma(.01,.01)
sigma_tau1 = 1/tau1
}"
inprod
to multiply the parameters with the design matrixm2 =
"model {
for(i in 1:N1){
mu1[i] = inprod(beta1, x1[i,]) #----> this
Y1.BurnRate[i] ~ dnorm(mu1[i], tau1)
}
for (l in 1:3) { beta1[l] ~ dnorm(0, 0.001) }
tau1 ~ dgamma(.01,.01)
sigma_tau1 = 1/tau1
}"
You received an error with for(j in 1:3){ mu1[i] = beta1[j]* x1[i,j] }
as every time you loop though the parameter index j
you overwrite mu1[i]
. It also doesn't sum up the individual terms. You may be able to index mu1
with j
as well and then sum
but untested ...