1

I am running a logistic model by rjags, but the error always happens (see below) and I felt my codes contain everything needed and they are logical, so up to now I can't detect the mistake in my codes. here is the error

Error in jags.model(textConnection(modelstring2), data = list(ro = ro$ro,  : 
RUNTIME ERROR:
Compilation error on line 22.
Unknown variable i
Either supply values for this variable with the data
or define it  on the left hand side of a relation.

Here are my codes:

#loading the data
data("ro")
?ro

str(ro)

Ntotal<-dim(ro)[1]

modelstring2 <- "
model {

#likelihood

for (i in 1:Ntotal) {

ro[i]~ dbern(mu[i])  



logit(mu[i]) <- alpha + beta[1]*rr[i]

}

#prior

alpha~ dnorm(0, 1.0E-6)

for (j in 1:4) {
beta[i]~ dnorm(0, 1.0E-6)
}
}"


#obatin the initial values by glm model
glm_int <- glm(ro ~ x1 + x2 + x3 + x4,
family= binomial,data = ro)
summary(glm_int)


#initiate the model

datalist<-list( 'ro'=ro[[1]], 'x1'=ro[[2]],'x2'= ro[[3]],
'x3'=ro[[4]],'x4'= ro[[5]],'Ntotal'=Ntotal)

model2<-jags.model(textConnection(modelstring2),
data=list( 'ro' = ro$ro,
'x1'=ro$x1,
'x2'=ro$x2,
'x3'= ro$x3,
'x4'= ro$x4, 'Ntotal'=Ntotal),

inits =list('alpha' =glm_int$coef[[1]],'beta[1]'=   glm_int$coef[[2]],
'beta[2]'=  glm_int$coef[[3]],'beta[3]'= glm_int$coef[[4]],
'beta[4]'= glm_int$coef[[5]]),

n.chains=3,
n.adapt=1000)

Looking forward to your help.

user5802211
  • 197
  • 1
  • 9

1 Answers1

1

The error tells you that the problem is on line 22. Lines 21-23 of your code are:

for (j in 1:4) {
     beta[i]~ dnorm(0, 1.0E-6)
}

i.e. the indexing variable i doesn't exist within this loop over j.

JAGS goes to quite a lot of effort to provide informative errors, so it is always worth reading them carefully. Note that the line number references are more useful if your model is in a separate text file (alternatively runjags will show your model with line numbers on request - r2jags may do something similar, I'm not sure).

Matt Denwood
  • 2,537
  • 1
  • 12
  • 16