Search code examples
rjagsr2jags

Error in jags.model RUNTIME ERROR: Compilation error on line 5. Index out of range taking subset of a


I'm quite new to Jags, I'm trying to calculate the model DIC but returned with such error: Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, : RUNTIME ERROR: Compilation error on line 5. Index out of range taking subset of a My code is attached below.

prior <- c(0.1, 0.15, 0.20, 0.25)
target <- 0.2
y<-c(0,0,0,4)
n<-c(0,5,5,8)
ndose=length(n)
bugs<-function(){
  for (j in 1: ndose){
    y[j]~dbin(p[j],n[j])
    p[j]<-exp(3+a[j]*log(prior[j]/(1-prior[j])))/(1+exp(3+a[j]*log(prior[j]/(1-prior[j]))))
  }
a~dgamma(1,1)
}
inits<-function(){
  list('a'=0.001)
}
parameter<-c('a')
bugs.data<-list(y=y,n=n,prior=prior,ndose=ndose)
fit<-jags(data=bugs.data,inits=inits,parameter,bugs)

Solution

  • You've specified a as a scalar given the prior you supplied, but above you have indexed it to 1:ndose. If a is indeed a scalar then change the code to:

    prior <- c(0.1, 0.15, 0.20, 0.25)
    target <- 0.2
    y<-c(0,0,0,4)
    n<-c(0,5,5,8)
    ndose=length(n)
    bugs<-function(){
      for (j in 1: ndose){
        y[j]~dbin(p[j],n[j])
        p[j]<-exp(3+a*log(prior[j]/(1-prior[j])))/(1+exp(3+a*log(prior[j]/(1-prior[j]))))
      }
    a~dgamma(1,1)
    }
    inits<-function(){
      list('a'=0.001)
    }
    

    If it is meant to be a vector, then you'd need a to have ndose values. Using just the code above, that could be done like so:

    target <- 0.2
    y<-c(0,0,0,4)
    n<-c(0,5,5,8)
    ndose=length(n)
    bugs<-function(){
      for (j in 1: ndose){
        y[j]~dbin(p[j],n[j])
        p[j]<-exp(3+a[j]*log(prior[j]/(1-prior[j])))/(1+exp(3+a[j]*log(prior[j]/(1-prior[j]))))
      }
    for(j in 1:ndose){
    a[j]~dgamma(1,1)
    }}
    inits<-function(){
      list('a'=c(0.001, 1, 0.5, 0.7))
    }