Louisa Wareing
Louisa Wareing

Reputation: 19

How do I correct the error: RUNTIME ERROR: Compilation error on line 4. Index out of range taking subset of y

I've built a linear regression model using rjags but I am getting a runtime error saying the index is out of range. I've looked for advice online but can't find anything that I understand or addresses this exact problem.

Here is my code:

modelstring1= "
model{
  for (i in 1:n) {
    y[i] ~ dnorm(mu[i], prec)
    mu[i] = b[1] + b[2]*lnimi[i]
  }
  
  for (j in 1:2) {
    b[j] ~ dnorm(0.0, 1.0/1.0E6)
  }
  
  prec ~ dgamma(20.0/2, 20.0*10.0/2)
  sig2 = 1.0 / prec
  sig = sqrt(sig2)
}"


jags_data1 = list(y=Reisby["hd"], n=nrow(Reisby))

params1 = c("b", "sig")

inits1 = function() {
  inits = list("b"=rnorm(2.0, 0.0, 100.0), "prec"=rgamma(1, 1.0, 1.0))
}

model1 = jags.model(textConnection(modelstring1), data=jags_data1, inits = inits1)

And the error is:

Compiling model graph
Resolving undeclared variables
Deleting model
Error in jags.model(textConnection(modelstring1), data = jags_data1, inits = inits1) :
RUNTIME ERROR:
Compilation error on line 4.
Index out of range taking subset of y

The closest advice I've seen says that the mu range is too small but I don't really understand how that is the problem here. Unsure if the "lnimi" field in the Reisby data needs to be specified anywhere as it is included in the mu[I] statement?

Upvotes: 1

Views: 269

Answers (1)

Louisa Wareing
Louisa Wareing

Reputation: 19

Thank you to all of the people who commented, I've now got a working model! The final code is:

 modelstring1= "
model{
  for (i in 1:n) {
    y[i] ~ dnorm(mu[i], prec)
    mu[i] = b[1] + b[2]*lnimi[i]
  }
  
  for (j in 1:2) {
    b[j] ~ dnorm(0.0, 1.0/1.0E6)
  }
  
  prec ~ dgamma(20.0/2, 20.0*10.0/2)
  sig2 = 1.0 / prec
  sig = sqrt(sig2)
}"


jags_data1 = list(y=Reisby_df$hd, lnimi=Reisby_df$lnimi, n=nrow(Reisby))


model1 = jags.model(textConnection(modelstring1), data=jags_data1, inits = inits1, n.chains = 2)

Upvotes: 0

Related Questions