compbiostats
compbiostats

Reputation: 961

What is causing this rjags error: dimension mismatch?

I am experiencing issues with running the following time-series JAGS model in R:

data(lynx)
y <- as.vector(lynx)
y

x <- 1:length(y)

library(rjags)

mod <- "model {
  alpha ~ dnorm(0, 0.0001)
  beta ~ dnorm(0, 0.0001)
  lambda ~ dgamma(1, 1)

  for (i in 2:length(y)) {
    y[i] ~ dpois(lambda[i])
    lambda[i] <- alpha + beta * x[i - 1]
  }
}"

mod <- textConnection(mod)

samples <- jags.model(mod, data = list('x' = x, 'y' = y), n.chains = 3) # 
# Error in jags.model(mod, data = list(x = x, y = y), n.chains = 3) : 
# RUNTIME ERROR:
# Cannot insert node into lambda[1:114]. Dimension mismatch

Is someone able to explain what the above error is referring to and how to fix it?

Upvotes: 0

Views: 151

Answers (1)

mfidino
mfidino

Reputation: 3055

lambda is written as the rate term of the Poisson distribution in your loop but then you specify it as a gamma distribution in your priors. This is causing a dimension mismatch. On top of this, you need to use the appropriate link function for the Poisson distribution.

mod <- "model {
  alpha ~ dnorm(0, 0.0001)
  beta ~ dnorm(0, 0.0001)

  for (i in 2:length(y)) {
    y[i] ~ dpois(lambda[i])
    log(lambda[i]) <- alpha + beta * x[i - 1]
  }
}"

mod <- textConnection(mod)

# create model object
model_fit <- jags.model(mod, data = list('x' = x, 'y' = y), n.chains = 3)

# collect samples
samples <- coda.samples(model_fit, c("alpha", "beta"), n.iter = 10000)

Upvotes: 2

Related Questions