JAGS: unit-specific time trends

2019-09-04 03:44发布

Using JAGS I am trying to estimate a model including a unit-specific time trend. However, the problem is that I don't know how to model this and so far I have been unable to find a solution.

As an example, consider we have the following data:

rain<-rnorm(200)     # Explanatory variable
n1<-rnorm(200)       # Some noise
gdp<-rain+n1         # Outcome variable
ccode<-rep(1:10,20)  # Unit codes
year<-rep(1:20,10)   # Years 

Using normal linear regression, we would estimate the model as:

m1<-lm(gdp~rain+factor(ccode)*year)

Where factor(ccode)*year is the unit-specific time trend. Now I want to estimate the model using JAGS. So I create parameters for the indexing:

N<-200
J<-max(ccode) 
T<-max(year)

And estimate the model,

library(R2jags)
library(rjags)

set.seed(42); runif(1)
dat<-list(gdp=gdp,
      rain=rain,
      ccode=ccode,
      year=year,
      N=N,J=J,T=T)

parameters<-c("b1","b0")
model.file <- "~/model.txt"
system.time(m1<-jags(data=dat,inits=NULL,parameters.to.save=parameters,
        model.file=model.file,
        n.chains=4,n.iter=500,n.burnin=125,n.thin=2))

with the following model file, and this is where the error is at the moment:

# Simple model 

model {
  # For N observations
  for(i in 1:N) {
    gdp[i] ~ dnorm(yhat[i], tau)
    yhat[i] <- b1*rain[i] + b0[ccode[i]*year[i]]   
  }

  for(t in 1:T) {
    for(j in 1:J) {
      b0[t,j] ~ dnorm(0, .01)
    }
  }
  # Priors
  b1 ~ dnorm(0, .01)   

  # Hyperpriors
  tau <- pow(sd, -2)
  sd ~ dunif(0,20)  
}

I am fairly sure that the way in which I define b0 and the indexing is incorrect given the error I get when using the code: Compilation error on line 7. Dimension mismatch taking subset of b0. However, I don't know how to solve this so I wondered whether someone here has suggestions about this?

标签: r bayesian jags
1条回答
我命由我不由天
2楼-- · 2019-09-04 04:19

Your lm example can also be written:

m1 <- lm(gdp ~ -1 + rain + factor(ccode) + factor(ccode):year)

The equivalent JAGS model would be:

M <- function() {
  for(i in 1:N) {
    gdp[i] ~ dnorm(yhat[i], sd^-2)
    yhat[i] <- b0[ccode[i]] + b1*rain[i] + b2[ccode[i]]*year[i]   
  }

  b1 ~ dnorm(0, 0.001)   
  for (j in 1:J) {
    b0[j] ~ dnorm(0, 0.001)
    b2[j] ~ dnorm(0, 0.001)
  }
  sd ~ dunif(0, 100)  
}

parameters<-c('b0', 'b1', 'b2')
mj <- jags(dat, NULL, parameters, M, 3)

Comparing coefficients:

par(mfrow=c(1, 2), mar=c(5, 5, 1, 1))
plot(mj$BUGSoutput$summary[grep('^b0', row.names(mj$BUGSoutput$summary)), '50%'],
     coef(m1)[grep('^factor\\(ccode\\)\\d+$', names(coef(m1)))],
     xlab='JAGS estimate', ylab='lm estimate', pch=20, las=1,
     main='b0')
abline(0, 1)

plot(mj$BUGSoutput$summary[grep('^b2', row.names(mj$BUGSoutput$summary)), '50%'],
     coef(m1)[grep('^factor\\(ccode\\)\\d+:', names(coef(m1)))],
     xlab='JAGS estimate', ylab='lm estimate', pch=20, las=1,
     main='b2')
abline(0, 1)

enter image description here

查看更多
登录 后发表回答