Search code examples
rmarkov-chainsmcmc

Metropolis-Hastings MCMC with R


I'm trying to implement a simple MCMC using MH algorith with R the problem, is that i get this error (i tried to calculate the alpha and it's not an NA problem)

Error in if (runif(1) <= alpha) { : missing value where TRUE/FALSE needed

here is my function can anyone spot the problem ?

    PoissonMetropolisHastingRW = function(n=100000,lambda=10,p=0.5,x0=0){

  x=rep(0,n); y=0; alpha = 0

  x[1]=x0
  for(i in 2:n){

    if (x[i-1] == 0){
      y = sample(c(0,1),1, prob=c(0.5,0.5))
      alpha = min(1,((lambda^y)*x[i-1]*p)/((lambda^x[i-1])*y*(1-p)))
      #alpha = min(1, ( ((lambda^y)*x[i-1])/( (lambda^x[i-1])*y) )*(p/(1-p)) ))
      if(runif(1)<=alpha) {x[i]=y}
      else {x[i]= x[i-1]}

    }
    if (x[i-1] > 0){
      y = sample(c(x[i-1]-1,x[i-1]+1), 1, prob=c(1-p,p))
      alpha = min(1,((lambda^y)*x[i-1]*p)/((lambda^x[i-1])*y*(1-p)))
      #alpha = min(1, (((lambda^y)*x[i-1]/((lambda^x[i-1])*y))*(p/(1-p))))
      if(runif(1) <= alpha) {x[i]=y}
      else {x[i]= x[i-1]}
    }
  } 
  return(x)



}

Solution

  • If y happens to be 0 (and with 0.5 probability for each iteration this will happen with certainty), then alpha is 0 / 0 (because x[i-1] == 0). It gives you NaN. Condition something <= NaN provides a NA.