Multivariate Bayesian Modelling using Jags -Rjags

230 Views Asked by At

The error obtained is shown here in this image and as well written below

i.e.,

> model<-jags.model(file=textConnection(model1), data=df,inits =inits)
Compiling model graph
   Resolving undeclared variables
Deleting model

Error in jags.model(file = textConnection(model1), data = df, inits = inits) : 
  RUNTIME ERROR:
Compilation error on line 4.
Cannot evaluate subset expression for mean_0

The whole Code of my analysis is

library(rjags)
library(coda)
library(matrixStats)
library(tidyverse)
library(cowplot)
library(forecast)

data1<-data[order(nrow(data):1),]
prices<-data1[,c(5,7,9,11)]
y<-data1[,c(6,8,10,12)]


model1 <-  "model  {
  for ( i  in 100 : n )  {
      p[i,] ~ dmnorm(mean_0[], Sigma_0[1:4,1:4])
      mean_0[]<-lambda_hat[,] %*% t(y[i,])+c((p[(i-1),1]),(p[(i-1),2])
       ,(p[(i-1),3]),(p[(i-1),4]))
      
  }
  lambda_hat~dwish(mat[1:4,1:4], 4)
  Sigma_0~dwish(mat[1:4,1:4],4)
  for (j in 1:4){ for (k in 1:4){  mat[j,k] <-equals(j,k)*.1 } }

}"
params <-  c("lambda_hat")
inits <-  list("lambda_hat" = diag(1,1,1,1),"Sigma_0"=var(prices[1:100,]),"mat"=diag(1,1,1,1))
df<-list(p=prices,y=y,n=(dim(y)[1]-99))

model<-jags.model(file=textConnection(model1), data=df,inits =inits)
update(mod, 10000, progress.bar = "none")

I am getting error while running this particular line.

model<-jags.model(file=textConnection(model1), data=df,inits =inits)

Can you please help me out?

1

There are 1 best solutions below

0
On

It looks that the error in is due to the matrix operation in the definition of mean_0. It can be fixed by using a inner product to define each component.

Two minor things: a) since there is no variation in the matrix mat, it is easy to create that matrix in R and pass it to jags and, b) the correct syntax to create the intended diagonal matrix in R is diag(c(1,1,1,1))

The fixed code is the following:

library(rjags)

data1<-data[order(nrow(data):1),]
prices<-data1[,c(5,7,9,11)]
y<-data1[,c(6,8,10,12)]
mat = matrix(0,4,4)
diag(mat) <- 0.1

model1 <-  "model  {
  for ( i  in 100 : n )  {
        p[i,] ~ dmnorm(mean_0[i-99,], Sigma_0[1:4,1:4])
        for(j in 1:4){
        mean_0[i-99,j]<-inprod(lambda_hat[,j],y[i,]) + p[(i-1),j]
  }}
  lambda_hat~dwish(mat[1:4,1:4],4)
  Sigma_0~dwish(mat[1:4,1:4],4)

}"
params <-  c("lambda_hat")
inits <-  list("lambda_hat" = diag(c(1,1,1,1)),"Sigma_0"=var(prices[1:100,]),"mat"=diag(c(1,1,1,1))
df<-list(p=prices,y=y,n=(dim(y)[1]-99),mat = mat)

model<-jags.model(file=textConnection(model1), data=df,inits =inits)
update(mod, 10000, progress.bar = "none")