# Example R code for the Metropolis and Metropolis-Hastings algorithms ############################################################## # From Seefeld and Linder, p.203 --- Metropolis sampling, beta(a,b) k<-3; n<-5; # experiment results a1<-k; b1<-(n-k); # posterior shape alpha-1,beta-1, after experiment nsteps<-1000; # number of steps in the Markov chain X<-vector(length=nsteps); # allocate storage for the steps x<-0.04; X[1]<-x; # initial state, somewhat arbitrary gx<-x**a1 * (1-x)**b1; # initial posterior value g(x) for(i in 2:nsteps){ # run the Markov process y<-runif(1); # proposal: sample the (symmetric) prior gy<-y**a1 * (1-y)**b1; # posterior value g(y), at proposal r<-gy/gx; # ratio of posteriors u<-runif(1); # acceptance function: compare r with U(1) if(u