I am trying to estimate the slope coefficients for a VAR using a Metropolis algorithm. I was expecting that my output would have the same number of columns as my the X variable which has 20 columns, however, it has only 3 columns. I know I am doing something terribly wrong with the code, (that I found on this platform), but I am not sure what I should do. The code is as follows:
#example data
data<- matrix(rnorm(3600,10,1),ncol=20)
Y=data[,c(1:20)]
Y <- as.matrix(Y, ncol=20)
p=4
T=nrow(Y)
X <- Y[p:(T-1),]
set.seed(101)
#for the loglikelihood
logl <- function(m,X, Y) {
ly =sum(dnorm(X,m[1]+m[2]*X, (m[3])^2,log=TRUE))
}
#the proposal function
proposalfunction <- function(param,s){
return(rnorm(3, mean = param, sd= s))
}
#the metropolis step
Metropolis_MCMC <- function(startvalue, iterations,X, Y,s){
i=1
chain = array(dim = c(iterations+1,3))
chain[i,] = startvalue
while (i <= iterations){
proposal = proposalfunction(chain[i,],s)
probab = exp(logl(proposal,X = X, Y = Y) - logl(chain[i,],X = X, Y = Y))
if(!is.na(probab)){
if (runif(1) <= min(1,probab)){
chain[i+1,] = proposal
}else{
chain[i+1,] = chain[i,]
}
i=i+1
}else{
cat('\r !')
}
}
acceptance = round((1-mean(duplicated(chain)))*100,1)
print(acceptance)
return(chain)
}
r <- Metropolis_MCMC(startvalue= c(0,.9,1), iterations = 36000, X, Y, s=.00085)