[R] Metropolis-Hastings in R

Michael Williams mikeyy_lol at hotmail.co.uk
Wed Mar 14 18:21:15 CET 2012


Hi all,
I'm trying to write a MH algorithm in R for a standard normal distribution,
I've been trying for a good week or so now with multiple attempts and have
finally given up trying to do it on my own as I'm beginning to run out of
time for this, would somebody please tell me what is wrong with my latest
attempt:


n=100
mu=0
sigma=1
lik<-function(theta) exp(((theta-mu)^2)/2*sigma)
alpha<-function(theta,phi) min(lik(phi)/lik(theta),1)
theta1<-matrix(0,n,2)
theta1[1,]<-mu
for(i in 2:n){
theta<-theta1[i-1,]
phi<-theta+runif(-0.5,0.5)
k<-rbinom(1,1,alpha(theta,phi))
k1<-k1+k
theta1[i,]<-theta+k*(phi-theta)
}
plot(theta1)


Thanks alot :)
-Mike

--
View this message in context: http://r.789695.n4.nabble.com/Metropolis-Hastings-in-R-tp4472547p4472547.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list