I am running a MCMC algorithm with Metropolis Hastings step in R
, which requires accepting or rejecting a proposal sample according to a logical rule. Currently, I have implemented this as
if(sample meets condition){accept}
else{reject}
I heard that if
statements are slow, but MCMC requires usually evaluating many proposal samples, certainly in the ten thousands. What are faster alternatives to improve the speed of this part of any MCMC algorithm?
To give an example of the step in the code:
A = sample(c(0,1),1,prob=c(1-A,A))
if(A==1){
s_acc[i,] = s_new
s_old = s_new
acc[i] = 1
}
else{
s_acc[i,] = s_old
acc[i] = 0
}
where A
is the acceptance probability of a sample, s_new
is the value of the proposed sample, s_acc
is the vector of all accepted samples, s_old
is the current previously accepted sample, and acc
is a count of which samples were accepted. This part of the code is embedded in a for
loop with a high number of iterations.